Russian Doll Caching in Rails
cough cough, not like Russian Dolls
TL:DR
You can make caches within caches so if the outer cache busts then the inner cache is still there. This can go as deep as you like. In this example if the article gets updated but the comments do not the outer cache will be missed but the inner cache will be hit.
<% cache [@article, @article.comments] do %>
<h1><%= @article.title %></h1>
<p><%= @article.body %></p>
<% cache @article.comments do %>
<% @article.comments.each do |comment| %>
<p><%= comment.body %></p>
<% end %>
<% end %>
<% end %>
Russian Dolls and why this is a little bit like them
Russian dolls are these ones where you have a doll and you open the doll and there’s another doll and you open that doll and there’s yet another doll and it keeps going pretty low. So you can have a cache inside another cache so kind of Russian Doll Caching is like Russian dolls.
Extreme Russian dolls
But, this kind of implies to me that this is what Russian Doll Caching would look like (THIS IS NOT WHAT IT IS LIKE!)
+----------------------------------+
| C1 |
| +------------------------------+ | NOT WHAT RUSSIAN DOLL CACHING
| | C2 | | IS LIKE!
| | +----------------------------+ |
| | | || |
| | | C3 || |
| | | +-----------------------+ || |
| | | | | || |
| | | | C4 | || |
| | | | | || |
| | | | | || |
| | | | | || |
| | | | | || |
| | | +-----------------------+ || |
| | +----------------------------| |
| +------------------------------| |
+----------------------------------+
whereas in reality its a bit more like this with C1 being surrounding cache of everything, then C2 being inside C1, C3 also being in side C1, C6 being inside C5 inside C3 inside C1.
+------------------------------------+
| |
| C1 |
| +-------------------------------+ |
| | | |
| | C2 | |
| | | |
| +-------------------------------+ |
| +-------------------------------+ |
| | C3 | |
| | | |
| | +----------- --+----+-----+ | |
| | | | | | | C5 | | |
| | | C4 | | | C6 | | | |
| | | | | +----+ | | |
| | +----------+ +------------+ | |
| +------+ +-----+ +-------+ |
| || C7 | | C8 | | C9 || |
| +------+-----+-----+----+-------+ |
| |
+------------------------------------+
Sample of what our Listing page cached could look like each coloured box being a different cache. (we’re still working on it)
So the outside red cache would be based on the product itself, the product images, and the user.
The reason for this is the rather annoying Add to Wish List and Add to Basket which we have to be very careful about caching as we don’t want someone putting their product in someone else’s basket, or it continuing to say Add to Basket after they’ve added to basket.
The very fastest website would also be the most useless. User features and personalisation make caching harder but we need to work around this with our caching strategy.