Fragment Caching is a handy technique in which you cache a fragment of your view logic for subsequent requests. This allows one to decrease the time a request takes to complete and put less load on resources. Before you even ask, no, you don’t need this on your todo list or whatever other crappy app you’re building, because odds are, you’re not going to get enough traffic to need it. Moving on. As with any decent caching system, there are multiple backends: file, memcache, etc. I have a love hate relationship with MemCache. I love it for its scalability and stupid simple use. I hate it, well, you’ll see why.
Say you actually do have traffic to your site, and you implement a fragment cache for each products star ratings:
1 2 3 | <% cache "rating-#{product.id}" do %> <%= show_stars(product) %> <% end %> |
Simple enough, right? Now to expire:
1 | expire_fragment "rating-1" |
The problem, is say I need to clear ALL ratings, simple, expire_fragment takes a regexp as a key:
1 | expire_fragment %r{rating-(\d+)} |
Score! Not really. This works in file caching, but not in MemCache. MemCache doesn’t support an internal index (that I know of) for allowing one to iterate over keys, which is precisely what is required (if I read correctly) in order to expire based on regexp. This means I can do one of two things:
- Use file caching and endure a horrible IO bottleneck (no thanks).
- Collect all product IDs, iterate over them and expire. (no thanks).
What’s a good recommendation? I’m not sure, to be honest. One would think that, being a scalable memory store, it’d have this basic functionality, but apparently they opted against it for a performance increase. Leave me a comment with your own solution.
Related posts: