I’ve covered a ton of material in this article. I’ve given a through explanation of how all the Rails cache layers fit together and how to use the lowest level to it’s full potential. I’ve provided a solution for managing the cache outside the HTTP request cycle as well as shown you how to bring caching into the model layer. This is not the be-all-and-end-all Rails caching. It is a in-depth look at caching in a Rails application. I’ll leave you with a quick summary of everything covered and some few goodies.
- Very Handy! You should strive to reach this goal
- Cuts down on bandwidth when requests are fresh
- Cacheable responses are stored in
If-Modified-Sincedate to check freshness
- The simplest that could possibly work
- Usually not applicable to any web application. Have a form? No good,
form_authenticity_tokenwill be no good and Rails will reject it
- Most bang for the buck. Can usually be applied in many different circumstances
- Uses fragment caching under the covers
- Generates a cache key based off the current URL and whatever other options are passed in
- Get more mileage by caching actions with an composite timestamped key
- Good for caching reusable bits of HTML or JSON. Think shared partials or forms
- Use a good cache key for each cache block.
- Don’t go overboard. Requests to memcached are not free. Maximize benefits by caching a small number of large fragments instead of a large number of small fragments.
- Don’t worry about sweepers unless you have too.
- Understand the limitations of Rail’s HTTP request cycle
- Use cryptographic hashes to generate cache keys when permutations of input parameters are involved
- Don’t be afraid to use
Rails.cachein your data layer
- Tagged based caching is useful in certain situations
- Consolidate your cache expiration logic in one place so it’s easily testable.
- Test with caching turned on in complex applications.
- Look into Varnish for more epic wins.
- belongs to with
:touch => trueis your friend
- Use association timestamps
- Spend time upfront considering your cache strategy
- Be weary of examples with expire by regex. This only works on cache stores that have the ability to iterate over all keys. Memcached is not one of those
- Use auto expiring keys for everything!
- Understand how cache validation and expiration works according to the HTTP caching spec.
- Cache your static assets! If possible, serve them through a CDN
- In rare situations, excessive calls to memcached may be slower than skipping it.
- Consider the current locale when caching HTML.
- Don’t forget to set
ENV['RAILS_APP_VERSION']on every deploy
I really hope you learned and enjoyed this guide. It has been a fun to right and I know it has helped a ton of Rails developers.