1

I have recently added low level caching to a query in Rails 3.2.14 app. In my local I do not see the cached query running twice but its getting logged in production.

I have even checked answers given on this thread where it talks about converting the query result to an array using to_a method.

@top_quiz_creators = Rails.cache.fetch("/quiz/creators", expires_in: 1.hours) do
   Quiz.find_by_sql("some complex query").to_a
end

In mysql-slow.log:

# Time: 170118  8:28:32
# User@Host: db[db] @ ip-xyz.ec2.internal [xyz]
# Query_time: 5.403992  Lock_time: 0.000074 Rows_sent: 5  Rows_examined: 10272991
SET timestamp=1484728112;

How can I stop this query from hitting DB again and again?

Community
  • 1
  • 1
Sahil
  • 3,338
  • 1
  • 21
  • 43
  • Caching isn't going to speed up your query. – shmosel Jan 18 '17 at 08:33
  • @shmosel yes that's true but I want to reduce the hits. Right now its running every second I just want to run it once every hour across sessions as it is leaderboard related. I am also working on optimizing the query but I want to know why does it get logged. Why production and development are having this difference? – Sahil Jan 18 '17 at 08:34

1 Answers1

1

To speed up your query have to keep two things in your mind

  1. First implement the foreign keys and indexes in the database level
  2. And use ActiveRecord wisely
Sumit Dey
  • 71
  • 6
  • I have added indexes on all the tables required in this query. Now the queries takes .22 seconds to run and now due to some reason it is not getting logged. I did not do any change to the query. – Sahil Jan 18 '17 at 09:24
  • So I think its better no?? previously I was taking 5.403992 seconds? Anyway.. also add the foreign key if needed – Sumit Dey Jan 18 '17 at 11:33
  • If you found this useful could you please upvote this? – Sumit Dey Jun 06 '19 at 04:25