SD/Lesson 3 of 8/5 min read
Caching
Where to cache, cache-aside, read-through, write-through, write-behind and write-around strategies, eviction policies, TTLs, invalidation, cache stampede and hot keys.
On this page
Caching
Caching stores the result of an expensive operation (a database query, a computation, a remote call) in fast storage so later requests can reuse it. It cuts latency and offloads the slower layer behind it.
Caching works because access patterns are skewed: a small fraction of data gets most requests (the 80/20 rule). It is the same idea as the CPU's cache memory, applied across a network.
Where to cache
| Layer | Example | Caches |
|---|---|---|
| Client | Browser cache, mobile app storage | Static assets, API responses |
| Edge | CDN | Static files, public pages |
| Reverse proxy | Nginx, Varnish | Full HTTP responses |
| Application | In-process map, Redis, Memcached | Objects, query results, sessions |
| Database | Buffer pool, query cache | Pages, plans |
In-process caches are fastest but each instance has its own copy, so they diverge and waste memory. A distributed cache (Redis cluster) is shared by all instances.
Read strategies
Cache-Aside
The application manages the cache (also called lazy loading). The most common pattern.
def get_user(id):
user = cache.get(f"user:{id}")
if user is None: # miss
user = db.query("SELECT * FROM users WHERE id = %s", id)
cache.set(f"user:{id}", user, ttl=300)
return user- Only requested data gets cached; a cache failure degrades to slower reads, not an outage.
- First request for each key is a miss; data can go stale until TTL or invalidation.
Read-Through Cache
The cache sits inline and loads from the database itself on a miss. The application only talks to the cache. Same behavior as cache-aside, but the loading logic lives in the cache library or provider.
Write strategies
| Strategy | Write path | Pros | Cons |
|---|---|---|---|
| Write-through | Write cache and DB synchronously | Cache always fresh | Slower writes, caches data never read |
| Write-around | Write DB only, skip cache | No cache pollution | Recent writes miss on first read |
| Write-Behind (write-back) | Write cache, flush to DB async | Fastest writes, batching | Data loss if the cache dies before flush |
Common combination: cache-aside reads + invalidate on write (delete the key after updating the database, so the next read reloads it).
Delete instead of update on write: two concurrent writers updating the cache can leave it with the older value; deleting is idempotent.
Cache Eviction
When the cache is full, something must go.
| Policy | Evicts | Notes |
|---|---|---|
| LRU | Least recently used | Good default; see the LRU cache design |
| LFU | Least frequently used | Keeps long-term popular items; slow to adapt |
| FIFO | Oldest inserted | Simple, ignores usage |
| TTL | Expired entries | Bounds staleness, not size |
| Random | Any | Cheap, surprisingly decent |
Redis offers allkeys-lru, allkeys-lfu, volatile-ttl and others via maxmemory-policy.
Cache Invalidation
"There are only two hard things in computer science: cache invalidation and naming things."
Approaches:
- TTL: every entry expires after N seconds. Simple and bounds staleness. Pick TTL by how stale the data may be.
- Explicit invalidation: delete keys when the source changes. Fresh, but every write path must remember to do it.
- Event-driven: the database's change stream (CDC) publishes updates that consumers use to invalidate.
- Versioned keys: include a version in the key (
user:42:v7); bumping the version orphans old entries.
Use both: invalidate on write for freshness, plus a TTL as a safety net for missed invalidations.
Cache Stampede
When a popular key expires, thousands of requests miss at once and all hit the database together (also called thundering herd or dog-piling).
Mitigations:
- Request coalescing / locking: only one request recomputes; others wait or get the stale value.
- Stale-while-revalidate: serve the old value while one background job refreshes it.
- Probabilistic early expiration: each reader refreshes slightly before expiry with increasing probability.
- Jitter: add randomness to TTLs so many keys do not expire at the same instant.
Hot Key
One key receiving a huge share of traffic (a celebrity profile, a viral post) can overload the single cache node that owns it.
- Replicate the hot key under several names (
post:1:a,post:1:b) and pick one at random. - Add a small in-process cache in front of the distributed cache for the hottest keys.
Redis vs Memcached
| Redis | Memcached | |
|---|---|---|
| Data types | Strings, hashes, lists, sets, sorted sets, streams | Strings only |
| Persistence | Optional (RDB snapshots, AOF) | None |
| Replication, clustering | Built in | Client-side sharding |
| Threads | Mostly single-threaded command execution | Multithreaded |
| Extra uses | Rate limiters, leaderboards, pub/sub, locks, queues | Pure cache |
Default to Redis unless you need Memcached's simple multithreaded key-value performance.
What not to cache
- Data that must be strongly consistent (account balances at the moment of a transfer).
- Data that is rarely read again (low hit rate means added latency and cost for nothing).
- Highly personalized responses at shared layers such as CDNs, unless keyed correctly (risk of leaking one user's data to another).
Quick revision
- Cache what is read often and changes rarely; measure hit rate.
- Cache-aside is the default: read cache, on miss load DB and fill; on write update DB then delete key.
- Write-through keeps the cache fresh; write-behind is fast but risks loss; write-around avoids pollution.
- LRU is the default eviction policy; TTLs bound staleness.
- Prevent stampedes with locking, stale-while-revalidate and TTL jitter.
- Redis is the usual distributed cache.