Rails: Invalidate cache based on query results

357 Views Asked by At

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.

1

There are 1 best solutions below

2
On

As you've got a new_this_month scope, I assume Prices have a created_at timestamp. In that case you could simply use the latest created_at in your cache key:

cache_key = "new_prices-#{Prices.order('created_at DESC').take.created_at}"

If you've got a good database index in place, this should be a very fast query.