Caching in distributed systems
Cache clusters, invalidation across services, stampedes, hot keys and the consistency they cost.
18 min readCache clusters
A single Redis node serves on the order of 100 000 simple operations per second and holds what fits in its memory. Beyond that, shard the cache with consistent hashing or a fixed slot map (Redis Cluster uses 16 384 slots), and replicate each shard so a node failure does not turn into a sudden cold cache and a database stampede. Size the cluster by working set, not total data: if 20% of 500 GB gets 90% of reads, you need about 100 GB plus overhead.
Invalidation across services
The classic race: service A reads the old value from the database, service B writes a new value and deletes the cache key, then A writes its stale value into the cache, where it stays until the TTL expires. Mitigations stack.
- Invalidate from change data capture so every database write produces a delete
- Use leases: the cache issues a token on a miss and rejects a fill whose token was invalidated (the approach in Facebook's memcache paper)
- Always set a TTL as a backstop so any inconsistency heals on its own
- Version values and refuse to overwrite a newer version with an older one
Stampedes and hot keys
When a popular key expires, thousands of concurrent requests miss together and all hit the database. Coalesce them so only one request recomputes while the rest wait (single-flight), or refresh probabilistically before expiry. A single key receiving 200 000 reads per second will overload its shard no matter how many shards you have; replicate hot keys to several shards with a suffix, or hold them in a small in-process cache with a 1 to 5 second TTL.
Caching and consistency
A cache turns any store into an eventually consistent one, bounded by the TTL and your invalidation path. That is acceptable for catalogue pages and feeds, and dangerous for availability checks just before a booking. A common pattern: serve the search and browse path from cache, but re-check against the source of truth inside the transaction that commits. In the Feedback panel, adding a cache raises hit rate and cuts database load, while the rubric checks you did not put it in front of a decision that needs fresh data.
Key takeaways
- Shard and replicate cache clusters; size them by working set
- Invalidate from change data capture, keep TTLs as a backstop, and guard against stale fills
- Coalesce misses to prevent stampedes and replicate hot keys
- Read from cache to browse, but re-check the source of truth before committing a decision
Sign in to track lessons and earn badges.