How to keep caches warm using Russian Doll caching?

572 Views Asked by At

I've been experimenting with Russian Doll fragment caching on a Rails app, more specifically on its main Dashboard page. This is the first page the user sees after he logs in and is a great candidate for Russian Doll, since it contains many nested elements.

Caching is working well in situations when the user himself makes changes which requires the app to re-render the Dashboard. Load time with caching is about 4x faster than rendering the full page.

There are, however, situations when the data is changed by the system. For example, every night, we update all the values by the new exchange rate for the previous day. This will automatically expire most of the fragments in the Dashboard and the next morning the user will hit a cold cache when logging in.

It is possible to regenerate these fragment caches after the system updates in order to keep them warm? I guess I could manually write the fragments after any system update, but I would have to manage the keys and dependencies manually as well. (I'm currently using the cache_digest gem, which is very convenient.).

Any ideas?

2

There are 2 best solutions below

1
On

If it's an option for you then you could include all the data you need for the calculations in data- attributes, and then convert this into text using Javascript.

So your raw output might be:

<li data-gbp-amount="2.50"></li>

Then you come along with JS and do something like:

$(document).find("[data-gbp-amount]").each(index, el) ->
  $(el).text($(el).data("gbp-amount") * todaysExchangeRate)

That way everything outputted by Rails will be cached, and won't change with the exchange rate.

1
On

Everything depends of cache_key. cache_key is based on the model id, updated_at attribute and on the md5 from the html template. So, if you change one of these 3 keys, then you expired the cache.

I dont know how complex is your data, but you could just use the touch method in your main AR::model in order to change the cache key. Maybe you have a main AR::model where the others records are dependents.