Caching
Dramatically improve response speed by reducing repeated computations
Rails caching works at multiple levels.
1. Fragment Caching (most common): Cache view fragments with cache @post do ... end blocks. Cache auto-invalidates when @post updated_at changes.
2. Russian Doll Caching (nested caching): Nest cache blocks. When a child (comment) changes, only that cache is refreshed. When parent (post) changes, everything refreshes. Set up cascade invalidation with belongs_to :post, touch: true.
3. Low-Level Caching: Cache arbitrary values with Rails.cache.fetch("key", expires_in: 1.hour) { expensive computation }.
Stores: Memory Store, Redis, Memcached, Solid Cache (Rails 8)
Key Points
<% cache @model do %> โ cache view fragments with Fragment Cache
Auto cache key generation + invalidation based on Model updated_at
Russian Doll: fine-grained invalidation with nested caching
belongs_to :post, touch: true โ invalidate parent cache on child change
Rails.cache.fetch("key", expires_in: 1.hour) { expensive computation }
config.cache_store = :redis_cache_store โ cache store configuration
Pros
- ✓ Response speed improved 10x+
- ✓ Significant DB load reduction
- ✓ Auto invalidation based on updated_at
- ✓ Fine-grained cache management with Russian Doll
Cons
- ✗ Need to design cache invalidation strategy
- ✗ Risk of showing stale data
- ✗ Cache store management (Redis, memory)
- ✗ Changes may not appear during debugging due to cache