A cache keeps a copy of data in a faster place so repeated reads can skip slow work: a disk read, a network hop, a heavy query or an expensive computation. Caching is the single biggest lever most systems have for latency and cost. It is also a classic source of bugs: stale data, inconsistency between cache and database, and outages where a cold or failed cache lets the full load crash into the database.
Think of it like
Books on your desk
The library (your database) has every book, but a trip there takes ten minutes. So you keep the books you're using on your desk (the cache). The desk is small, so when it fills up you return the one you haven't opened for longest (LRU eviction). And if the library gets a new edition, the copy on your desk is now out of date (invalidation), unless you agreed to swap desk copies every week regardless (a TTL).
Why caching works
Two facts make caches effective. First, access is skewed: a small fraction of keys (today's top posts, popular products) receives most of the traffic, often following a Zipf-like distribution. Second, there is a huge latency gap between storage tiers, so serving even part of the traffic from a faster tier pays off enormously.
In-process cache
~100 ns
a hash map lookup in RAM
Redis / Memcached
~0.5 ms
one network round trip in the same zone
Indexed DB query
~1–10 ms
plus connection and query-planning overhead
Cross-region call
~70–150 ms
e.g. US East ↔ Europe
Where caches live
A request can be answered by any of several caching layers, and each hit shields every layer behind it. Press play to watch a full miss and then hits at different depths.
| Layer | What it caches | Typical TTL | How it's invalidated |
|---|---|---|---|
| Client (browser, mobile app) | HTTP responses, assets, app data | Seconds to a year | Cache-Control, versioned URLs |
| CDN | Static assets, public pages, cacheable API GETs | Minutes to a year | Purge API, versioned URLs. See Content Delivery Networks |
| Reverse proxy | Full responses, micro-caching | 1 s to minutes | TTL, purge |
| Application (in-process) | Hot objects, config, computed values | Seconds to minutes | TTL; one copy per instance, so hard to invalidate everywhere |
| Distributed cache | Query results, objects, sessions, counters | Minutes to hours | Delete on write, TTL |
| Database | Pages in the buffer pool, query plans | Managed by the engine | Automatic |
Caching strategies
A strategy answers two questions: who loads data into the cache on a read, and what happens to the cache on a write. The simulation above lets you switch between these strategies and watch reads and writes flow.
| Strategy | Read path | Write path | Pros | Cons |
|---|---|---|---|---|
| Cache-aside (lazy loading) | App checks cache; on a miss it reads the DB and fills the cache | App writes the DB, then deletes the cache key | Only caches what is read; a cache outage degrades, it doesn't break | Three trips on a miss; brief staleness windows; logic lives in the app |
| Read-through | App asks the cache; the cache loads from the DB on a miss | Usually paired with write-through or write-around | Simpler app code; loader logic in one place | Needs a cache library or provider that supports loaders |
| Write-through | Reads hit a cache that is always populated | Write cache and DB synchronously, together | Cache is never stale for written keys | Slower writes; caches data that may never be read |
| Write-behind (write-back) | Reads from cache | Write the cache, flush to the DB asynchronously in batches | Very fast writes; absorbs bursts; coalesces updates | Data loss if the cache dies before flushing; ordering is tricky |
| Write-around | Cache-aside reads | Write only the DB; the cache fills on the next read | Write-once data doesn't pollute the cache | First read after a write is always a miss |
Eviction policies
A cache is smaller than the data behind it, so when it's full something must go. The eviction policy decides what, and the right choice depends on your access pattern. See LRU & LFU Cache for the classic O(1) hash map plus doubly linked list implementation.
| Policy | Evicts | Good for | Weakness |
|---|---|---|---|
| LRU | Least recently used entry | Most workloads, where recent use predicts future use | One large scan flushes the hot set (scan pollution) |
| LFU | Least frequently used entry | Stable popularity: catalogs, CDN objects | Slow to adapt when popularity shifts; needs counter decay |
| FIFO | Oldest inserted entry | Simplicity; works surprisingly well under heavy skew | Ignores how often an item is used |
| TTL expiry | Entries past their time to live | Bounding staleness | A freshness rule, not a capacity policy on its own |
| Random | A random entry | No bookkeeping at all | Unpredictable; may evict hot items |
| W-TinyLFU, ARC, 2Q | Blend of recency and frequency | Scan-resistant, high hit ratios (Caffeine in Java uses W-TinyLFU) | More complex to implement |
maxmemory 4gb
maxmemory-policy allkeys-lfu # or allkeys-lru; volatile-* only evicts keys that have a TTL
maxmemory-samples 10 # Redis approximates LRU/LFU by sampling; more samples = more accurateInvalidation and consistency
- TTL expiry: every entry eventually refreshes. Simple, and it bounds how stale data can get. Always set one, even alongside other strategies.
- Delete on write: the writer removes the key after committing; the next reader reloads it.
- Write-through update: the writer sets the new value. Fresh, but vulnerable to ordering races between writers.
- Event-driven invalidation: tail the database's change log (CDC, for example Debezium) and delete affected keys. Facebook's memcache fleet is invalidated this way from the MySQL commit log.
- Versioned keys: include a version in the key (
user:7:v42); a write bumps the version and old entries simply age out.
The classic stale-cache race
- 1
Reader misses
Reader A misses on
user:7and reads version 1 from the database. - 2
Writer updates
Writer B commits version 2 and deletes
user:7(which isn't cached yet, so nothing happens). - 3
Slow reader fills
Reader A, delayed by a GC pause, now sets
user:7= version 1. - 4
Stale until TTL
The cache serves version 1 while the database holds version 2, until the TTL expires.
Fixes include short TTLs, a delayed second delete (delete again a second or so after the write), leases (the cache hands the missing reader a token, and a later delete invalidates it so the stale SET is rejected, as Facebook's memcache does) and version checks on write. Also remember that the database commit and the cache delete are not atomic: if the delete fails, retry it through a queue or drive invalidation from CDC.
Failure modes at scale
Cache stampede (thundering herd)
A hot key expires and thousands of concurrent requests miss at the same instant. Every one of them runs the same expensive query, the database saturates, latency climbs, and more requests pile up behind it. Three families of fixes:
Locking
- The first miss takes a short lock (
SET lock:key 1 NX EX 10) - Only it rebuilds the value; others wait briefly and retry, or serve stale
- Needs a lock timeout in case the holder dies
Request coalescing
- Concurrent misses for the same key share one in-flight load
- Go's
singleflight, a promise map in Node, NGINXproxy_cache_lock - Per process: N servers still mean up to N loads
Refresh before expiry
- Probabilistic early expiration (XFetch): each reader may refresh early, more likely as expiry nears
stale-while-revalidate: serve the old value while one background refresh runs- Users never see the miss
import math
import random
import time
def xfetch(cache, key, recompute, ttl, beta=1.0):
"""Recompute early with probability that rises as expiry approaches.
cache.get returns (value, delta, expiry) or None, where delta is how long
the last recomputation took. Slow-to-compute keys refresh earlier.
"""
entry = cache.get(key)
now = time.time()
# -log(U) for U in (0, 1] is a random positive number, usually small
if entry is None or now - entry[1] * beta * math.log(1.0 - random.random()) >= entry[2]:
start = time.time()
value = recompute()
delta = time.time() - start
cache.set(key, (value, delta, now + ttl), ttl)
return value
return entry[0]Hot keys
Sometimes one key (a celebrity's profile, a flash-sale item) is so popular that the single cache shard holding it saturates its CPU or network, while the rest of the cluster idles. Fixes: put a small in-process cache with a few seconds of TTL in front of Redis, replicate the key under several names (item:42#1 to item:42#8) and read a random copy, or serve reads from replicas. Detect them with redis-cli --hotkeys (requires an LFU eviction policy) or client-side sampling.
Cache penetration
Requests for keys that don't exist (often an attacker iterating random IDs) always miss the cache and always hit the database. Fixes: cache the negative result with a short TTL (store a null marker for 60 s), put a Bloom filter of valid IDs in front so impossible keys are rejected without any lookup (see Bloom Filters & Probabilistic Structures), and validate inputs.
Cache avalanche
Many keys expire at the same moment (because they were bulk-loaded with an identical TTL) or the whole cache cluster restarts empty, and the database receives the full read load at once. Fixes: jitter TTLs (300 s plus a random 0–60 s), warm the cache before shifting traffic, run replicated cache clusters, and protect the database with rate limits and circuit breakers (Resilience Patterns).
| Problem | Symptom | Fixes |
|---|---|---|
| Stampede | DB spike every time a hot key expires | Locks, request coalescing, early refresh, stale-while-revalidate |
| Hot key | One cache shard at 100% while others idle | Local L1 cache, key replication, read replicas |
| Penetration | Steady DB load from lookups of nonexistent keys | Negative caching, Bloom filters, input validation |
| Avalanche | DB overwhelmed after mass expiry or cache restart | Jittered TTLs, warm-up, replicated cache, circuit breakers |
| Stale data | Users see old values after updates | Delete on write, short TTLs, CDC invalidation, leases |
Redis vs Memcached
| Feature | Redis | Memcached |
|---|---|---|
| Data types | Strings, hashes, lists, sets, sorted sets, streams, bitmaps, HyperLogLog, geo | Opaque strings (blobs) only |
| Threading | Commands execute on a single thread (I/O threads since 6.0) | Fully multi-threaded |
| Persistence | Optional RDB snapshots and AOF log | None: purely in memory |
| Replication and HA | Replicas, Sentinel failover, Redis Cluster with 16,384 hash slots | None built in; clients shard with consistent hashing |
| Eviction | Eight policies, including approximate LRU and LFU | LRU (segmented) |
| Max value size | 512 MB | 1 MB by default (configurable) |
| Extras | Lua scripting, transactions, pub/sub, per-key TTLs | Very simple and memory-efficient for small objects (slab allocator) |
| Best for | Rich structures: leaderboards, rate limiters, queues, sessions | Huge, simple object caches with very high throughput |
Sizing a cache
Size for the working set, not the whole dataset. Example: a store with 10 million products where, per the 80/20 rule, the top 20% receive most views. Each cached product is about 2 KB of JSON.
Hot keys
2 M
20% of 10 M products
Raw data
~4 GB
2 M × 2 KB
With overhead
~6 GB
×1.5 for per-key metadata and fragmentation
With one replica
~12 GB
fits on two modest nodes
When not to cache
- Data that is written far more often than it is read.
- Data that must be strongly consistent on every read (account balances during a transfer).
- Values that are cheap to compute or fetch already.
- Highly personalized data with almost no reuse between requests.
- Before you have measured a performance problem: a cache adds a second source of truth and new failure modes.
Implementation
Read-through-the-app with jittered TTLs, negative caching and one loader per key. Writes commit to the database, then delete the cached copy.
import json
import random
import time
import redis
r = redis.Redis(host="localhost", port=6379, decode_responses=True)
TTL = 300 # seconds
NULL = "__null__" # marker for "does not exist" (negative caching)
def _decode(raw: str):
return None if raw == NULL else json.loads(raw)
def get_user(user_id: int, db):
key = f"user:{user_id}"
raw = r.get(key)
if raw is not None:
return _decode(raw)
# Only one caller rebuilds a missing key. (In production, store a unique
# token in the lock and release it only if it still matches.)
if r.set(f"lock:{key}", "1", nx=True, ex=10):
try:
row = db.fetch_user(user_id)
if row is None:
r.set(key, NULL, ex=60)
else:
r.set(key, json.dumps(row), ex=TTL + random.randint(0, 60)) # jitter
return row
finally:
r.delete(f"lock:{key}")
# Someone else is loading: wait briefly for their result
for _ in range(50):
time.sleep(0.02)
raw = r.get(key)
if raw is not None:
return _decode(raw)
return db.fetch_user(user_id) # degrade gracefully rather than fail
def update_user_email(user_id: int, email: str, db) -> None:
db.update_user_email(user_id, email) # 1. commit to the source of truth
r.delete(f"user:{user_id}") # 2. invalidate; don't update in placeKey takeaways
- Caching works because access is skewed and the latency gap between tiers is huge; hit ratio drives everything.
- Caches exist at every layer: client, CDN, reverse proxy, in-process, distributed cache and the database itself.
- Cache-aside (read: fill on miss; write: commit then delete) is the sensible default; write-behind trades durability for write speed.
- Choose eviction by access pattern: LRU for recency, LFU for stable popularity, and always set TTLs.
- Plan for stampedes, hot keys, penetration and avalanches: coalescing, local caches, negative caching and Bloom filters, jittered TTLs.
- Invalidation is inherently racy; bound staleness with TTLs and use deletes, CDC or leases to tighten it.
Common pitfalls
- Updating (instead of deleting) cache entries on writes, letting racing writers leave old values behind.
- Giving every key the same TTL, so they all expire together and stampede the database.
- Running Redis with the default
noevictionpolicy as a cache, so writes fail when memory fills. - Treating the cache as the source of truth without persistence or replication.
- Caching per-user data under a shared key, leaking one user's data to another.
Interview tips
- Say which strategy you're using (usually cache-aside), what the key is, what the TTL is, and how writes invalidate it.
- Proactively mention stampede protection for hot keys; it's one of the most common follow-up questions.
- Size the cache from the working set with a quick back-of-envelope calculation.
- Be explicit about consistency: what staleness is acceptable for this data, and for how long?
Real-world applications
- Product, profile and feed caches in front of databases.
- Session stores and authentication token caches.
- Rate-limit counters and leaderboards in Redis.
- Rendered HTML and API response caching at the proxy or CDN.
- Memoizing expensive computations such as recommendations or search results.
Test yourself
In cache-aside, what should the application do when it updates a user's record?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.