Skip to content

Caching strategies

A cache keeps a copy of data closer to where it’s used, so reads are faster and the source of truth does less work. Caching is one of the most effective performance tools there is, and one of the most common sources of subtle bugs: stale data, stampedes after an expiry, and outages when a cold cache meets full traffic.

Before adding a cache, check that you need one. An index, a better query or a read replica may solve the problem without the consistency questions a cache brings.

Layer Examples Good for
Browser and CDN HTTP caching, edge caches Static assets, public pages, API responses that are the same for many users
In-process A map or LRU cache in the application Small, hot, rarely changing data; fastest, but each instance has its own copy
Distributed Redis (opens in a new tab), Memcached (opens in a new tab) Shared data across many instances, sessions, computed results
Database Buffer pool, materialized views Repeated queries; mostly automatic

Cache-aside (lazy loading). The application checks the cache; on a miss, it reads the database and writes the result to the cache. It’s the most common pattern and works with any cache. Only requested data is cached, but every miss costs an extra round trip, and the first request after an expiry is slow.

Read-through. The cache itself loads missing data from the source. Same behavior as cache-aside, with the loading logic moved into the cache layer.

Write-through. Every write goes to the cache and the database together. Reads after writes are fresh, but writes are slower, and data that’s never read still fills the cache.

Write-behind (write-back). Writes go to the cache and are written to the database later, in batches. Writes are fast, but anything not yet written is lost if the cache fails. Use it only where losing recent writes is acceptable, such as counters and analytics.

Refresh-ahead. Popular entries are refreshed before they expire, so users never wait for a reload. It needs a good guess about what will be read next.

There are two ways to stop serving old data, and most systems use both.

  • Expiry (TTL). Each entry lives for a fixed time. Simple and self-healing, but data can be stale for up to the TTL. Choose the TTL from how stale the business can tolerate, not from what makes the hit rate look good: seconds for prices and stock levels, hours for reference data.
  • Invalidation. When data changes, delete or update the cache entry. Fresher, but every write path must remember to do it, and races between a slow read and a fast write can put old data back after the invalidation. Always keep a TTL as a safety net.

A safe pattern for cache-aside invalidation: update the database, then delete the cache entry (don’t write the new value into the cache). If two writes race, the next read reloads from the database. For data that changes through events, invalidating from a change data capture stream catches changes that bypass your application.

Cache stampede. A popular entry expires, and hundreds of requests miss at once and all hit the database. Defenses:

  • Request coalescing: only one request reloads a key; the others wait for its result.
  • Early or probabilistic refresh: refresh an entry shortly before it expires, at a slightly random time.
  • Jittered TTLs: add a random few percent to each TTL so entries written together don’t expire together.
  • Serve stale while revalidating: return the old value while one request fetches the new one. HTTP supports this with the stale-while-revalidate directive (RFC 5861 (opens in a new tab)).

Cold cache. After a restart, a deploy or a failover, the cache is empty and every request goes to the database, which was sized for the cache’s hit rate, not for full load. Warm caches before sending traffic, roll restarts gradually, and know what your database can take with a 0% hit rate.

Decide what you’ll do when the cache is down

Section titled “Decide what you’ll do when the cache is down”

A cache that the system can’t run without isn’t a cache any more; it’s a database without the durability. Decide which of these applies, and test it:

  • The system runs slower but correctly without the cache, and the database can take the load.
  • The system sheds load or degrades features until the cache recovers.
  • Hit rate per key pattern, not just overall. A 95% overall rate can hide a 10% rate on the expensive queries.
  • Latency of hits and misses separately.
  • Evictions. Many evictions mean the cache is too small for the working set.
  • Load on the source of truth if the hit rate dropped to zero.

Written and edited by Abhinav Taduka, enterprise software architect.