I've decided to finally update my advanced caching post. The original is over a year old. It's still one of the most referenced and respected posts on the subject. This revision is a refactor and update all rolled into one. I've decided to split the post into multiple parts due to depth and length. I think all the content doesn't fit in a single post. Splitting it up into different chapters allows people to skip to their level or find relevant information. See the revision notes below for more information.
This series means to teach you everything you need to know to implement any different caching level inside your Rails application. It assumes you know nothing at all about caching in any of its forms. It takes from zero to knowledge to an intermediate level in all areas. If you can't implement caching in your app after reading this then I've failed.
- Caching Strategies
- Using Strategies Effectively
- Handling Static Assets
- Stepping Outside the HTTP Request
- Tag Based Caching
- Fast JSON APIs
- Tips and Tricks
Further Explantion of Cache Strategies
I've added a totally new section on HTTP caching. Page caching is covered briefly. HTTP caching gets much more love in this version. I'd like to push developers towards HTTP caching as much as possible.
Since HTTP caching was added I felt that it was only natural to cover static assets. This aspect is usually left uncovered. Correctly handling static assets is increasingly important as applications contain more and more JS and CSS.
Tag Based Caching & Sweepers
These sections have been slimmed down. I don't think they are as important any more.
This post was originally written for Rails 2. Some of log examples are extracted from Rails 2 applications. Rails 3 does not output any cache information by default. There are two ways to see what's happening in real time.
- Start a local memcached process with:
memached -vvand watch $stdout.
- Enable cache instrumentation and attach a log subscriber. Rails cache
adatpers emit notifications through
ActiveSupport::Notifications. These events can be logged. It's easy to attach a log subscriber. See the embedded gist:
Cache Log Subscriber
I've elected to not update the log examples for Rails 3 because it does not add any useful to the post. Following either of the methods above will show you in real time what keys are written to cache. The only thing that's changed is the formatting. Keep this in mind as you read through the post.
— Adam Hawkins