๐Ÿ’จ

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

1

<% cache @model do %> โ€” cache view fragments with Fragment Cache

2

Auto cache key generation + invalidation based on Model updated_at

3

Russian Doll: fine-grained invalidation with nested caching

4

belongs_to :post, touch: true โ€” invalidate parent cache on child change

5

Rails.cache.fetch("key", expires_in: 1.hour) { expensive computation }

6

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

Use Cases

Post list/detail page caching Sidebar/navigation caching Caching expensive aggregation results API response caching