Programming - - By Tim Lucas

The effect of using Rails fragment caching

Rails provides a few caching techniques, one of which is a fragment cache. The fragment cache is a dead-easy way to cache bits of your view.

After checking that your queries are doing sensible things, the next often slowest part of the Rails stack is view rendering, especially if there’s lots of URL generation involved. More often than not you don’t want to cache the entire page as static HTML and bypass Rails altogether, instead, you want to retain the dynamic goodness of a web app and just cache the slow bits.

I recently added fragment caching to the toolmantim.com home page. Before I added fragment caching my production.log looked a little something like this:


Completed in 0.12385 (8 reqs/sec) | Rendering: 0.10077 (81%) | DB: 0.02210 (17%) | 200 OK [http://toolmantim.com/]

After fragment caching 2 parts of the application layout and the body of the home page my production.log looks a little something like this:


Completed in 0.00615 (162 reqs/sec) | Rendering: 0.00583 (94%) | DB: 0.00000 (0%) | 200 OK [http://toolmantim.com/]

A 17 times speed increase in rendering time for the cost of 2 dead-simple cache sweeper models, 4 lines of controller code and 6 lines of view code. I’d say that was worth the 30 minutes it took to implement.

There’s a few other things besides fragment caching I could have used to increase performance–optimise the DB call by SELECTing only the needed columns, or write a helper that generates Article and Comment URLs instead of relying on Rails to figure it all out for me–but I wanted to see how fast I could make the page whilst still keeping it within the Rails stack, and keeping things flexible.

Look out for tomorrow’s post when I’ll show how easy it is to take advantage of fragment caching in your own applications.

Sponsors