Caching
Where to cache, the four read and write patterns, how eviction works, and the failure modes (stale data, stampedes, hot keys) that interviewers love to probe.
ConceptCore12 min readUpdated
- 1 architecture diagram
- 2 sequence flows
- 2 code samples
- 5 interviewer follow-ups
- 3 self-checks
On this page12 sectionsHLDLLDSenior depth
Read first: Load balancing
- Pick a caching pattern (cache-aside, read-through, write-through, write-behind) and justify it.
- Explain LRU, LFU and TTL, and when each helps.
- Recognise and mitigate cache stampedes, hot keys and cache penetration.
- Reason about hit ratio and what staleness you are accepting.
Replay one request stream through FIFO, LRU and LFU
Change the traffic (a hot set, a trend, a scan, a loop) and the cache size, and watch which eviction policy keeps the keys that matter and what it does to latency.
Open the interactive2 code samples (64 lines), collapsed so the explanation stays in focus.
A cache stores the result of expensive work so the next request can skip it. Because reading from memory is orders of magnitude faster than a database query or a network call, a cache is often the cheapest way to cut latency and protect a struggling database. It is also the easiest component to get subtly wrong, because every cache is a second copy of the truth.
Caching pays off when data is read far more often than it changes and when many requests ask for the same things (skewed, "hot" access). If every request is unique, or the data changes constantly, a cache adds cost and complexity for little gain.
A quick way to see the effect is average latency:
average = hit_ratio x cache_time
+ (1 - hit_ratio) x (cache_time + database_time)With illustrative numbers, a 1 ms cache in front of a 20 ms database at a 90% hit ratio averages about 3 ms, instead of 20 ms. Moving from a 90% to a 99% hit ratio cuts the average from about 3 ms to about 1.2 ms, and cuts database load by a factor of ten. This is why hit ratio is the number to watch.
Caches exist at every layer, and each one adds another place for stale data to hide:
- Browser and client. Instant, but you do not control it. Use HTTP cache headers.
- CDN. Caches static files and sometimes API responses near users around the world. Its hit ratio, cache keys, shields and invalidation have a lesson of their own.
- Application or in-process. Fastest, but each instance has its own copy, so instances disagree and memory is duplicated.
- Distributed cache (such as Redis or Memcached). A shared service in front of the database. Slower than in-process, but every instance sees the same copy (which can still be stale relative to the database).
- Database internals. Buffer pools and the operating system's page cache. Useful, but not something you design; storage engines and indexes shows how a buffer pool decides what stays in memory. (The MySQL query cache was removed in version 8.0, and PostgreSQL has none.)
Cache-aside (lazy loading). The application checks the cache; on a miss it reads the database and writes the result to the cache. This is the most common pattern. Only data that is actually requested gets cached, and a cache outage degrades performance but not correctness. The cost is that the first request is slow and data can go stale.
Read-through. Like cache-aside, but the cache itself loads from the database on a miss. Simpler application code, more logic in the cache layer.
Write-through. Every write goes to the cache and the database together. Reads are fresh, but writes are slower and you cache data that may never be read.
Write-behind (write-back). Writes go to the cache and are flushed to the database later. Very fast writes, but if the cache dies before flushing, data is lost. Use it only when losing recent writes is acceptable, or the cache is itself durable.
Memory is finite, so a full cache must choose what to drop.
- LRU (least recently used): evict what has gone longest without being touched. A strong general-purpose choice. (Real caches often approximate it: Redis samples a few keys instead of tracking exact recency, and its default policy is to evict nothing and return errors when memory is full, so check the setting.)
- LFU (least frequently used): evict what is used least often. Better for stable popularity, slower to adapt when popularity shifts.
- TTL (time to live): every entry expires after a fixed time. This bounds how stale data can get and is usually combined with LRU or LFU.
No policy wins on every kind of traffic. A scan that reads many keys once flushes an LRU cache and leaves LFU alone; a shifting trend leaves LFU holding yesterday's favourites while LRU adapts; and a loop slightly larger than the cache defeats FIFO, LRU and LFU alike, because each key is evicted just before it is needed again. You can replay the same requests through all of them in the cache eviction lab.
When the underlying data changes, the cached copy is wrong. Your options:
- Wait for the TTL. Simple; accepts bounded staleness. Often the right answer.
- Delete the key on write. Common with cache-aside: update the database, then delete the cached entry so the next read repopulates it. Deleting is safer than updating the cached value because it avoids races between concurrent writers. One race remains: a reader can fetch the old row, lose a race with the writer, and put the stale value back into the cache just after the delete. Short TTLs bound the damage, and some systems version the cached value or delete again after a short delay.
- Publish invalidation events. Needed when many caches hold the same data. More machinery, more failure modes.
Always say aloud what staleness is acceptable. A product description that is a minute out of date is fine. An account balance is not. The key matters as much as the policy: a cache keyed by a user's exact coordinates almost never hits, and one keyed by a map cell hits more than nine times in ten (see the proximity service).
The common pattern is easy to draw and easy to get subtly wrong. Here is the read path, then the race that leaves stale data behind even when every step looks correct.
A TTL puts a ceiling on how long the damage lasts, which is one reason every cached entry should have one.
The next lesson, cache consistency, stampedes and hot keys, checks the stale-set race over every interleaving and compares the stampede defences by measured database load. The cache cluster itself (placement, nodes, failure) is the distributed cache case study.
Cache stampede (thundering herd). A popular entry expires and thousands of requests miss at once, all hitting the database. Mitigations: coalesce requests so that one rebuilds while the others wait (often called single-flight) or serve the stale value; add random jitter to TTLs so keys do not all expire together; refresh hot keys before they expire.
Hot key. One key gets so much traffic that the single cache node holding it is overloaded, even though the cluster as a whole is fine. Mitigations: replicate the hot key across nodes, add a small in-process cache in front, or split it into several keys.
Cache penetration. Requests for keys that do not exist miss every time and always reach the database, whether by accident or by an attacker. Mitigations: cache the "not found" result for a short time, or put a Bloom filter of the keys that do exist in front of the cache. It never wrongly rejects a real key, but it must be kept up to date, and a small fraction of absent keys still gets through (sizing is in probabilistic data structures).
Cold start. A new or restarted cache is empty, so the database takes the full load until it warms up. Mitigations: pre-warm with known hot data, and bring cache nodes in gradually.
When you add a cache to a design, say five things: what you cache, where, which pattern, how entries expire or are invalidated, and what happens on a miss and during an outage. That one sentence covers most follow-up questions before they are asked.
The classic low-level design question. A dictionary alone finds entries fast but knows nothing about the order of use. A list alone knows the order but finds entries slowly. Together they give O(1) TryGet and Put: the dictionary maps a key to its node in a doubly linked list, and the list keeps entries from most to least recently used.
C# · LruCache
using System;
using System.Collections.Generic;
public sealed class LruCache<TKey, TValue>
{
private readonly int _capacity;
private readonly Dictionary<TKey, LinkedListNode<KeyValuePair<TKey, TValue>>> _map = new Dictionary<TKey, LinkedListNode<KeyValuePair<TKey, TValue>>>();
private readonly LinkedList<KeyValuePair<TKey, TValue>> _order = new LinkedList<KeyValuePair<TKey, TValue>>(); // first = most recently used
public LruCache(int capacity)
{
if (capacity < 1) throw new ArgumentOutOfRangeException(nameof(capacity));
_capacity = capacity;
}
public int Count => _map.Count;
public bool TryGet(TKey key, out TValue value)
{
if (_map.TryGetValue(key, out var node))
{
_order.Remove(node);
_order.AddFirst(node); // touched: now the most recently used
value = node.Value.Value;
return true;
}
value = default(TValue);
return false;
}
public void Put(TKey key, TValue value)
{
if (_map.TryGetValue(key, out var existing))
{
existing.Value = new KeyValuePair<TKey, TValue>(key, value);
_order.Remove(existing);
_order.AddFirst(existing);
return;
}
if (_map.Count == _capacity)
{
var oldest = _order.Last; // the least recently used
_order.RemoveLast();
_map.Remove(oldest.Value.Key);
}
_map[key] = _order.AddFirst(new KeyValuePair<TKey, TValue>(key, value));
}
}C#
using System.Diagnostics;
var cache = new LruCache<string, int>(2);
cache.Put("a", 1);
cache.Put("b", 2);
cache.TryGet("a", out int touched); // reading "a" makes it the most recent, so "b" is now the oldest
cache.Put("c", 3); // full: evicts "b", not "a"
bool hasB = cache.TryGet("b", out int bValue);
bool hasA = cache.TryGet("a", out int aValue);
Debug.Assert(!hasB && hasA && aValue == 1 && cache.Count == 2);
cache.Put("a", 10); // an update replaces the value and counts as a use
cache.Put("d", 4); // evicts "c" (the oldest), not "a"
bool hasC = cache.TryGet("c", out int cValue);
cache.TryGet("a", out int updated);
Debug.Assert(!hasC && updated == 10);Holding the node in the dictionary is the whole trick: moving it to the front and dropping the tail are constant-time because no search is needed. This version is not thread-safe, and that is the interesting follow-up below.
Interviewer follow-upL6A very popular key expires and ten thousand requests miss at once. What happens, and how do you prevent it?How to answer
A cache stampede: every request goes to the database to rebuild the same value. Coalesce so only one request rebuilds while the others wait or receive the stale value (single flight, or a short lock or lease). Add jitter to TTLs so keys do not expire together, refresh popular keys before they expire, and consider serving stale data while revalidating in the background.
Interviewer follow-upL6Show how a cache-aside cache can stay wrong after the database has been updated.How to answer
A reader misses, reads the old row, and is delayed. A writer then updates the database and deletes the key. The reader finally sets the old value. Nothing fails, and the cache is stale until the TTL expires. Mitigations: a TTL on everything, leases or versioned values so a stale set is rejected, and avoiding "update the cache on write" for concurrently written keys, since two writers can interleave.
Interviewer follow-upL7The hit rate is 99% but one Redis node is overloaded. Why, and how do you fix it?How to answer
A hot key. All requests for it land on the node that owns it, however good the overall hit rate. Add a small in-process cache with a short TTL in front, replicate the hot key across several nodes or split it into suffixed copies and pick one at random, and serve it from the CDN if it is cacheable. Detect hot keys with sampling rather than guessing.
Interviewer follow-upL5Why does an LRU cache need both a dictionary and a linked list?How to answer
Lookup by key needs the dictionary. Knowing which entry was used least recently, and updating that order on every read, needs a structure where you can move an element to the front and remove from the back in constant time. A doubly linked list gives that when the dictionary stores each key's node, so nothing is searched. Either structure alone makes one of the two operations O(n).
Interviewer follow-upL6Your LRU cache is hit by thousands of threads. What breaks, and what do you change?How to answer
Every read reorders the list, so even reads write, and one lock around the whole cache serialises everything. Split the cache into segments chosen by key hash, each with its own lock and list, so threads rarely collide. Or avoid reordering on every read: record accesses in a buffer and apply them in batches, or use an approximate policy such as sampling, as Redis does. A single very hot key still serialises on its segment, so a small front cache per process can help.
Cache read-heavy, skewed data. Prefer cache-aside with a TTL. Evict with LRU. Delete on write. Watch hit ratio, and plan for stampedes, hot keys and a cold cache.
Try answering out loud before you reveal each answer.
QuestionDescribe the cache-aside read path.Reveal answer
Check the cache. On a miss, read the database, write the result into the cache with a TTL, and return it. Only data that is actually requested gets cached.
QuestionWhat is a cache stampede, and how do you reduce it?Reveal answer
A popular entry expires and many requests miss at once, all hitting the database. Coalesce rebuilds so one request refills the entry (or serve the stale value), add random jitter to TTLs, and refresh hot keys before they expire.
QuestionA 1 ms cache sits in front of a 20 ms database. What changes when the hit ratio goes from 90% to 99%?Reveal answer
The average falls from about 3 ms to about 1.2 ms, and database load falls tenfold, because 10% of requests reach it at first and only 1% afterwards.