Caching Strategies
Caching is the most common answer to "how do we make this faster?" and "how do we handle 10x the reads?" in system design interviews, and it's usually the right one. Reading a value from memory takes microseconds; reading it from a database that has to parse a query, check indexes and maybe hit disk takes milliseconds. Put a cache in front of a database that serves mostly repeated reads, and the database might see only a few percent of the traffic.
But caching is also where a lot of subtle bugs live. A cache is a second copy of your data, and as soon as there are two copies, they can disagree. A cache can also fail in ways that take the database down with it: a popular key expires and ten thousand requests hit the database at once, or the cache restarts empty during peak traffic.
A good interview answer goes beyond "add Redis." It says what is cached, where, how it gets populated, how it stays fresh, what happens when it's wrong, and what happens when it's gone. We'll cover:
- Why caching works, and the arithmetic of hit rates.
- Where caches live, from the browser to the database.
- Read and write patterns: cache-aside, read-through, write-through, write-behind.
- Eviction policies and sizing.
- Invalidation and consistency, including the race conditions interviewers like.
- Failure modes at scale: stampedes, penetration, avalanches and hot keys.
Why Caching Works
Caching works because access patterns are skewed. A small fraction of the data gets most of the reads: the front page, today's trending posts, the celebrity profile, the product on sale. If 20% of keys get 80% of the reads (often the skew is far stronger), caching that 20% absorbs most of the load.
The Arithmetic
Two numbers describe a cache: its hit rate (fraction of reads served from the cache) and the latencies of a hit and a miss.
Average latency = hit_rate × hit_latency + (1 − hit_rate) × miss_latency
With a 1 ms Redis hit, a 20 ms database read, and a 95% hit rate: 0.95 × 1 + 0.05 × 20 = 1.95 ms. Without the cache it's 20 ms.
Database load is just the miss rate times the read rate. At 100,000 reads per second:
| Hit rate | Reads reaching the database |
|---|---|
| 90% | 10,000/s |
| 95% | 5,000/s |
| 99% | 1,000/s |
| 99.9% | 100/s |
Notice that going from 95% to 99% cuts database load by 5x. Small improvements in hit rate at the high end matter enormously, and the same math works in reverse: if your hit rate drops from 99% to 90% (a deploy that changed key formats, a cold cache after a restart), database load goes up 10x. That's the core insight behind most caching failure modes.
In an interview, put numbers on the cache: "We serve 100k reads per second; with a 99% hit rate the database sees 1k per second, which one Postgres primary with replicas handles easily." Then ask yourself what happens if the hit rate drops, because your interviewer will.
Where Caches Live
There are caches at every layer between the user and the data, and a good design usually uses several:
- Client cache. Browsers and mobile apps cache responses according to HTTP headers (
Cache-Control: max-age=60,ETagfor conditional requests). Free for you, zero latency for the user, but you can't invalidate it once it's on the device, so use it for static assets (with content-hashed file names) and for data that tolerates staleness. - CDN. Edge servers close to users cache static files, images, video segments and even API responses (/system-design/cdn). Ideal for content that's the same for many users. Purging is possible but takes time to propagate, so CDNs prefer versioned URLs.
- Reverse proxy / API gateway cache. Nginx, Varnish or the gateway caches full responses in front of your services (/system-design/nginx).
- In-process application cache. A map in your service's memory (Caffeine in Java, an LRU dict in Python). Nanosecond-to-microsecond access, no network hop. But each instance has its own copy, so 100 instances means 100 copies to keep fresh, and memory per instance is limited. Great for small, hot, rarely changing data: configuration, feature flags, a currency table.
- Distributed cache. A shared cluster like Redis or Memcached that all instances talk to over the network, typically sub-millisecond within a data center. One copy per key, large capacity (sharded across nodes), and the default "cache" in most designs (/system-design/redis, /system-design/distributed-cache).
- Database-internal caches. The buffer pool (InnoDB) or shared buffers plus OS page cache (Postgres) keep hot pages in memory. You get this for free; it's why a "database read" is often much faster than a disk read. Materialized views and precomputed tables are another form of database-side caching.
Caches also show up as precomputed results: a user's home timeline stored as a list of post IDs in Redis is a cache of an expensive query, even though nobody calls it a cache (/system-design/twitter).
Reading and Writing Through a Cache
Cache-Aside (Lazy Loading)
The most common pattern, and the right default. The application manages the cache explicitly:
- Read: check the cache. On a hit, return it.
- On a miss, read from the database, store the result in the cache with a TTL, and return it.
- Write: update the database, then delete the cache entry.
def get_user(user_id):
key = f"user:{user_id}"
cached = redis.get(key)
if cached is not None:
return deserialize(cached)
user = db.query("SELECT * FROM users WHERE id = %s", user_id)
redis.set(key, serialize(user), ex=3600) # 1 hour TTL as a safety net
return user
def update_user(user_id, fields):
db.execute("UPDATE users SET ... WHERE id = %s", user_id)
redis.delete(f"user:{user_id}") # next read repopulates
Why delete instead of update on write? Updating the cache on write sounds fresher, but two concurrent writers can update the database in one order and the cache in the other, leaving the cache permanently wrong. Deleting is idempotent and lets the next read fetch the current value. It also avoids computing cache entries for data nobody reads.
Strengths: only requested data gets cached; the cache can fail and the system still works (slower); simple. Weaknesses: every miss pays three steps; data in the cache can be stale until deleted or expired; a cold cache sends everything to the database.
Read-Through
Like cache-aside, but the cache itself loads missing data from the database, so the application only talks to the cache. Libraries like Caffeine's LoadingCache, or caching layers such as DAX in front of DynamoDB, work this way. Same trade-offs as cache-aside, with the loading logic centralized.
Write-Through
Every write goes to the cache and the database synchronously, typically via the cache layer. The cache is always populated with the latest written values, so reads right after writes hit.
Weaknesses: every write pays both latencies; you cache data that may never be read; and you still need a story for what happens when one of the two writes fails. Write-through is usually combined with read-through, and it suits data that's read soon after it's written.
Write-Behind (Write-Back)
Writes go to the cache only, and the cache flushes them to the database asynchronously, often batched. Writes are very fast and the database sees far fewer, larger writes.
Weaknesses: if the cache node dies before flushing, the writes are lost. Use it only where that's acceptable or where the cache itself is durable and replicated: view counters, likes, analytics, game state checkpoints. Counting likes in Redis and persisting every few seconds is write-behind (/system-design/likes-counter).
Write-Around
Writes go straight to the database and don't touch the cache; the cache is only filled on reads. This is effectively what cache-aside does on writes, and it's useful when written data is rarely read soon after (logs, bulk imports), so it doesn't flood the cache.
| Pattern | Read path | Write path | Best for |
|---|---|---|---|
| Cache-aside | App checks cache, loads DB on miss | Write DB, delete cache key | General default |
| Read-through | Cache loads DB on miss | (Combine with another) | Centralized loading logic |
| Write-through | Cache (always warm) | Cache + DB synchronously | Read-after-write heavy data |
| Write-behind | Cache | Cache now, DB later | High write rates, loss-tolerant data |
| Write-around | Cache-aside reads | DB only | Write-once, read-rarely data |
Eviction and Sizing
A cache is smaller than the data behind it, so something has to decide what to throw out when it's full.
- LRU (least recently used): evict the entry that hasn't been accessed for the longest time. The standard choice, and a good fit for recency-driven workloads. Weakness: a one-time scan of many keys flushes out the genuinely hot ones.
- LFU (least frequently used): evict the entry with the fewest accesses. Better for stable popularity, but slow to forget keys that were hot yesterday. Practical versions decay counts over time.
- TTL-based expiry: entries expire after a fixed time regardless of space. Not an eviction policy in itself, but a freshness bound, and almost every cache entry should have one.
- Hybrids: modern caches like Caffeine use W-TinyLFU, which admits a new entry only if it's likely to be accessed more than the one it would replace, giving near-optimal hit rates for many real workloads.
Redis exposes this as maxmemory-policy: allkeys-lru and allkeys-lfu evict any key, volatile-lru evicts only keys with a TTL, and noeviction rejects writes when memory is full (the right choice when Redis holds data you can't lose, the wrong one for a cache). Redis's LRU and LFU are approximations that sample a few keys rather than tracking exact order, which keeps them cheap.
Sizing. Cache the working set, not the whole data set. If you have 500 million users but 50 million are active on a given day, and each cached profile is 1 KB, the daily working set is about 50 GB: a small Redis cluster. Measure hit rate as the cache grows; beyond the working set, extra memory buys very little.
Invalidation and Consistency
The cache is a copy, and copies go stale. There are three ways to keep them fresh, usually combined:
- TTL: every entry expires after some time. Simple and guarantees a staleness bound, but the bound is the whole TTL, and short TTLs lower the hit rate. Pick TTLs per data type: seconds for prices or stock levels, hours for profiles, days for immutable content.
- Explicit invalidation: delete (or update) the cache entry when the data changes, in the write path. Fresh in the common case, but every code path that writes must remember to do it, and a failed delete leaves stale data until the TTL.
- Event-driven invalidation: consume the database's change stream (/system-design/change-data-capture) and delete keys for every changed row. This catches writes from every code path, including batch jobs and manual fixes, and can retry failed deletes. It adds a small delay (the CDC lag) but is the most robust option for important data.
Versioned keys sidestep invalidation entirely for some data: include a version in the key (product:42:v17), and bump the version on change. Old entries are never read again and simply age out. This is how static assets on CDNs work (app.3f9a2c.js), and it works well when you can cheaply know the current version.
The Race Conditions
Cache-aside with delete-on-write still has a classic race. Two requests interleave:
- Reader A misses the cache and reads the user from the database:
name = "Old". - Writer B updates the database to
name = "New"and deletes the cache key. - Reader A, which was slow, now writes
"Old"into the cache.
The cache now holds stale data until the TTL expires, possibly hours. It requires an unlucky interleaving (a read that started before the write and finished after it), but at high traffic, unlucky interleavings happen every day.
Ways to close or shrink the window:
- Short TTLs as a backstop: bounded staleness even when the race hits.
- Delayed double delete: delete on write, then delete again a second or so later, after any in-flight reads have finished. Crude but effective.
- Leases: on a miss, the cache hands the reader a lease token. A write invalidates outstanding leases. When the reader tries to fill the cache, the fill is rejected if its lease was invalidated. Memcached-based systems at large scale have used this approach, and it also solves stampedes (below).
- Version checks: store a version or
updated_atwith the cached value and only overwrite an entry with a newer version (RedisSETwith a Lua script that compares versions).
When an interviewer asks "how do you keep the cache consistent with the database?", don't claim perfect consistency. Say: "Cache-aside with delete-on-write keeps it fresh in the common case, CDC-driven invalidation catches writes from every path, and a TTL bounds staleness when something goes wrong. For data that must never be stale, like a balance at checkout, we read from the database." That's the honest and senior answer.
Read-your-writes comes up too: a user edits their profile and sees the old one. If invalidation is synchronous in the write path, this is handled. If it's asynchronous (CDC), route the user's own reads to the database for a few seconds after a write, or write the new value into the cache directly for that user's key.
Failure Modes at Scale
Cache Stampede (Thundering Herd)
A hot key expires. In the next few milliseconds, thousands of requests miss, and all of them query the database for the same row and try to write the same value back. The database, sized for a 99% hit rate, receives a burst it can't handle, slows down, and more requests pile up. For an expensive query (a home page aggregation), one expired key can take down the database.
Fixes:
- Request coalescing (single flight): only one request per key recomputes the value; the rest wait for its result. Within one process, a per-key in-flight map does it. Across many servers, use a short-lived lock in the cache (
SET key:lock 1 NX EX 5): the winner recomputes, the others wait briefly and retry the cache, or serve the stale value. - Serve stale while revalidating: keep the value past its soft expiry, return the stale copy, and refresh it in the background. HTTP's
stale-while-revalidatedirective and CDNs work this way. - Probabilistic early expiration: each request near the expiry time has a small, increasing chance of refreshing early, so one request refreshes before the key actually expires.
- Never expire, refresh actively: for a small set of very hot keys (the home page), a background job recomputes them on a schedule and the TTL never runs out.
Cache Penetration
Requests for keys that don't exist always miss the cache, because there's nothing to cache, and always hit the database. A bug or an attacker requesting random IDs can push full traffic through to the database.
Fixes: negative caching (cache "not found" with a short TTL, say 60 seconds), and a Bloom filter of existing keys checked before the cache: if the filter says the key definitely doesn't exist, return 404 without touching anything (/system-design/storage-engines). Rate limiting by client helps against deliberate abuse (/system-design/rate-limiter).
Cache Avalanche
Many keys expire at the same moment, often because they were all loaded at the same time (a cache warm-up job, or a deploy that cleared the cache) with the same TTL. The result is a stampede across thousands of keys at once. A cache cluster restarting empty is the same problem at full scale.
Fixes: add jitter to TTLs (ttl = 3600 + random(0, 600)), so expiries spread out; warm the cache gradually before shifting traffic to a new cluster; keep the cache replicated so a node failure doesn't empty it; and protect the database with load shedding or circuit breakers so a cold cache degrades service instead of causing an outage.
Hot Keys
One key gets a huge share of traffic: a celebrity's profile, a viral post, a flash-sale product. In a distributed cache, every key lives on one shard (/system-design/consistent-hashing), so one cache node takes all of it. A single Redis node handles on the order of 100,000 or more simple operations per second, and a viral key can exceed that, or saturate the node's network bandwidth if the value is large.
Fixes:
- Local in-process cache in front of the distributed cache for detected hot keys, with a TTL of a few seconds. Load on the cache node drops by the number of application instances.
- Replicate the key: store copies under
post:123#0topost:123#7, spread across nodes, and have readers pick one at random. Writes update all copies. - Read replicas of the cache shard holding the key.
- Detect hot keys automatically, by sampling access counts in the client or proxy, so these protections kick in only when needed.
Large Values and Serialization
A cache entry that's a 2 MB JSON blob costs real time to serialize, transfer and deserialize, and blocks Redis's single-threaded command execution while it's read. Keep values small (a few KB is comfortable), cache the specific fields you need, and compress large ones.
Redis vs Memcached
Both are in-memory distributed caches with sub-millisecond latency. The choice is usually Redis, with Memcached in specific cases:
| Redis | Memcached | |
|---|---|---|
| Data types | Strings, hashes, lists, sets, sorted sets, streams, HyperLogLog | Strings (opaque blobs) |
| Threading | Commands execute on a single thread per node (I/O can be threaded) | Multi-threaded |
| Persistence and replication | Optional snapshots/AOF, replicas, Redis Cluster | None; purely a cache |
| Use beyond caching | Leaderboards, rate limiters, locks, queues, pub/sub | No |
| Best when | You want data structures, replication, or one tool for several jobs | Pure, simple, very large caches using many cores per node |
Caching in an Interview
When to Add a Cache
- Read-heavy with skewed access: profiles, product pages, feeds, configuration. Cache-aside in Redis, with TTLs.
- Expensive computations: aggregated pages, recommendation results, rendered fragments. Precompute and cache, with active refresh for the hottest ones.
- Static or shared content: images, video, scripts, public API responses. CDN with versioned URLs.
- Latency-critical lookups: rate limit counters, session tokens, feature flags. Redis or in-process.
When Not To
- Data that must be exactly current: account balances at payment time, inventory at checkout, permission checks right after revocation. Read from the source, or keep the cache only as a hint.
- Write-heavy data with little reuse: caching it costs more than it saves.
- Uniformly random access over a huge data set: hit rates will be low.
Common Follow-ups
- "How do you keep the cache and database consistent?" Delete on write, CDC-driven invalidation for safety, TTL to bound staleness, and the read-then-write race with its fixes.
- "A hot key just expired. What happens?" Stampede; request coalescing or stale-while-revalidate.
- "The cache cluster restarted. What happens?" Hit rate goes to zero and the database sees 100x load; replication, warm-up, jittered TTLs and load shedding.
- "What's your eviction policy?" LRU by default, LFU for stable popularity, TTLs on everything.
- "How big is the cache?" Working set times entry size, with the arithmetic.
- "Redis or Memcached?" Redis unless you need only opaque values at very large scale per node.
Summary
Caching trades freshness for speed and load: because access patterns are skewed, a small cache in front of a database can absorb most reads, and the hit rate determines how much load the database sees. Caches exist at every layer, from the browser and CDN to in-process maps, distributed caches like Redis, and the database's own buffer pool.
Cache-aside with delete-on-write is the default pattern; read-through, write-through and write-behind each fit specific workloads. Evict with LRU or LFU, put TTLs on everything, and size for the working set. Keep data fresh with explicit invalidation, change data capture and TTLs as a safety net, and know the read-then-write race and how leases, version checks or short TTLs contain it.
Finally, design for the cache failing: coalesce requests so a hot key's expiry doesn't stampede the database, cache negative results and use Bloom filters against penetration, jitter TTLs and warm caches against avalanches, and spread hot keys across nodes. A strong answer names what's cached, where, for how long, how it's invalidated, and what happens when it's wrong or gone.