Ankit KanojiyaIntermediate
Evergreen guide by Ankit Kanojiya · Intermediate · System Design
Caching Strategies Every Engineer Should Know
A practical tour of cache-aside, read-through, write-through, write-back, CDN caching, and Redis patterns, with the trade-offs and failure modes of each.
- Caching
- Redis
- CDN
- Performance
- Scalability
Caching trades freshness and complexity for speed and reduced load. Used well, it is the cheapest large performance win available. Used carelessly, it is the source of the hardest bugs you will ever debug: stale data, thundering herds, and inconsistency between layers. The strategy matters more than the technology.
Why cache at all
A cache stores the result of expensive work so the next request can skip it. Expensive can mean a slow database query, a remote API call, or a heavy computation. The two questions that define every caching design are:
- Who writes to the cache, and when?
- What happens when the cached data is wrong?
Cache-aside (lazy loading)
The most common pattern. The application checks the cache first and loads from the database only on a miss.
value = cache.get(key)
if value is None:
value = db.query(key)
cache.set(key, value, ttl=300)
return value
- Pros: only requested data is cached; a cache outage degrades gracefully to the database.
- Cons: the first request after a miss is slow (cold cache), and writes must invalidate the cache separately or risk staleness.
Read-through
Similar to cache-aside, but the cache library itself loads from the backing store on a miss. The application only talks to the cache. This centralizes the loading logic but couples you to a cache that supports it.
Write-through
On every write, update the cache and the database together, synchronously.
db.write(key, value)
cache.set(key, value)
- Pros: the cache is never stale for written keys; reads are fast immediately.
- Cons: every write pays the cost of two systems, and you cache data that may never be read.
Write-back (write-behind)
Writes go to the cache and are flushed to the database asynchronously in batches.
- Pros: very fast writes, and batching reduces database load dramatically.
- Cons: a cache crash before the flush loses data. Only acceptable where some loss is tolerable, such as view counts or metrics.
Choosing a write strategy
| Need | Strategy | | --- | --- | | Simple, read-heavy | Cache-aside | | Reads must be fresh after writes | Write-through | | Write throughput is critical, some loss OK | Write-back |
Expiration and invalidation
Two independent levers control staleness:
- TTL (time to live): data expires after a set time. Simple and self-healing, but data can be stale for up to the TTL.
- Explicit invalidation: delete or update the key when the source changes. Fresh, but easy to miss a code path and leak staleness forever.
A common robust approach combines both: invalidate on write, and keep a modest TTL as a safety net.
The thundering herd
When a popular key expires, many concurrent requests miss at once and all hit the database together, sometimes crashing it. Mitigations:
- Locking / single-flight: only one request recomputes; others wait for the result.
- Early recomputation: refresh the value slightly before it expires.
- Jittered TTLs: add randomness so keys do not all expire simultaneously.
CDN caching
A CDN caches responses at edge locations near users. It is ideal for static assets and cacheable responses. Control it with HTTP headers:
Cache-Control: public, max-age=3600
ETag: "a1b2c3"
An ETag lets the browser revalidate cheaply: the server returns 304 Not Modified when nothing changed. For dynamic pages, use short TTLs or cache only fragments.
Redis as an application cache
Redis is the common choice for a shared application cache because it is fast, networked, and offers more than key-value storage: sorted sets for leaderboards, TTLs per key, and atomic counters. Keep these in mind:
- Set a memory limit and an eviction policy (
allkeys-lruis a sensible default for a cache). - Treat Redis as a cache, not a database, unless you deliberately configure persistence.
- Keep keys namespaced and versioned, for example
user:v2:42, so a schema change can invalidate a whole class of keys at once.
Practical guidance
- Start with cache-aside plus a TTL. It covers most needs.
- Cache the results of reads that are both expensive and frequent; caching rare queries wastes memory.
- Always design for a cache that is empty or unavailable. The system should be slower, not broken.
- Measure hit rate. A cache with a low hit rate adds complexity and latency for no benefit.