I've got query in my Rails application that doesn't take long to run (~180ms), but does return a lot of results. The result is used in an API, and the transformation of the result to JSON is expensive (~3s). To speed things up, I'm caching it like this:
key = 'new_prices'
query = Prices.new_this_month.where('...')
json = cache(key, expires_in: 60.minutes) do
render_to_string json: query, each_serializer: PriceSerializer
end
render json: json
In the background, new prices can be added to the database. How can I generate the cache key in such a way that if the result of query
changes, the cache is invalidated?
I'm using Rails 3.2, with memcached via the dalli
gem.
As you've got a
new_this_month
scope, I assumePrices
have acreated_at
timestamp. In that case you could simply use the latestcreated_at
in your cache key:If you've got a good database index in place, this should be a very fast query.