Caching
How caches take read load off a database, the four caching strategies and when to use each, and the failure cases interviewers ask about.
On this page
A cache is a fast store, usually in memory, that holds copies of data which is slow or expensive to fetch from its source. It is used to take read load off a database and to cut response time. The cost is that the copy can be out of date, so most caching decisions are about how stale the data is allowed to be and what happens when the cache is empty or unavailable.
Without a cache, every read reaches the database, even when thousands of requests ask for the same few rows. A database that handles normal traffic can then time out during a spike, although almost all of the extra work is repeated.
Where caches sit
In an interview, "add a cache" usually means the shared cache: a separate in-memory store, such as Redis or Memcached, that every app server reads. The other layer worth knowing is the local cache inside each app server's memory. A local cache is faster because it needs no network call, but each server holds its own copy, so an update on one server does not reach the others, and the memory used grows with the number of servers. Use a shared cache by default, and add a local cache with a TTL of a few seconds in front of it only for a handful of very hot keys. Static files belong on a CDN.
Caching strategies
Two of the four strategies describe how data gets into the cache on a read (cache-aside and read-through), and two describe what a write does (write-through and write-behind). You choose one of each, and they can be combined.
Cache-aside
The application reads the cache first. On a hit it returns the value. On a miss it reads the database, stores the result in the cache with a time to live (TTL), and returns it. On a write, the application updates the database and then deletes the cached key, so the next read loads the new value.
Cache-aside is the default answer because it is simple, it caches only data that is actually read, and the application keeps working, more slowly, if the cache is down. Its weaknesses are that the first read of every key is slow, that every code path which writes the data must remember to delete the key, and that a stale value can still get in through a race (covered below).
The write deletes the key instead of setting the new value because two concurrent writers can set their values in the opposite order to their database commits, which leaves the older value in the cache. A delete cannot go wrong in that way.
Read-through
Read-through has the same read behaviour, but the cache layer loads the missing value from the database itself, so the application only ever talks to the cache. This keeps the loading logic in one place instead of in every service. It needs a cache library or a thin service in front of the cache that knows how to query the database, and its misses and staleness behave exactly like cache-aside. Mention it as "the same as cache-aside, with the loading moved into the cache layer".
Write-through
Every write updates the cache and the database before it is acknowledged. A read that follows a write finds the new value already cached, so there is no miss and no stale read. Pick it for data that is read soon after it is written, such as a user's own profile or settings.
At scale it has three problems:
- Every write pays for two stores, so write latency goes up.
- Every written key is cached whether or not anyone reads it, so the cache fills with cold data unless entries also have a TTL.
- The two writes are not atomic. If the database write fails after the cache was updated, the cache holds a value that was never saved. Write the database first, and treat a failed cache update as a delete.
Write-behind
request and replyasynchronous message
The write goes to the cache and is acknowledged immediately. The cache layer writes to the database later, usually in batches. Writes are very fast, and many updates to the same key collapse into one database write. Pick it for very high write rates where losing a few seconds of data is acceptable, such as view counters or "last seen" timestamps.
The risks are larger than with the other strategies:
- If the cache node dies before it flushes, acknowledged writes are lost. Buffering the writes in a durable queue reduces this, at the cost of handling retries, duplicates and ordering.
- The database lags behind the cache, so anything that reads the database directly, such as reports or other services, sees old data.
- If the database is slow or down, the backlog of unflushed writes grows and needs a limit.
Do not use write-behind for payments, orders or anything that must not be lost.
| Option | Good at | Bad at | Pick it when |
|---|---|---|---|
| Cache-aside Usual default | It is simple, caches only what is read, and survives a cache outage. | The first read of a key is slow, and every write path must delete the key. | Read-heavy data. This is the default answer. |
| Read-through | The application reads from one place, and loading logic is not repeated. | The cache layer has to know how to query the database. | Many services read the same data through a shared library. |
| Write-through | A read after a write is always fresh and never misses. | Writes are slower, and data nobody reads still takes up memory. | Data that is read right after it is written. |
| Write-behind | Writes are very fast and are batched into fewer database writes. | Acknowledged writes are lost if the cache fails before flushing. | Very high write rates where a small loss is acceptable. |
Expiry and eviction
These are two separate mechanisms. Expiry removes an entry when its TTL runs out, which limits how long a stale value can survive. Choose the TTL from how stale the data may be: hours for a list of countries, minutes for a product description, seconds for a trending list. Keep a TTL even when writes delete keys, because it cleans up after any invalidation that was missed.
Eviction removes entries when memory is full. LRU (least recently used) evicts the entry that has gone longest without a read, and it is the usual default. LFU (least frequently used) keeps the entries with the most reads over time, which protects long-term popular keys from a one-off scan but is slower to notice that an old favourite has gone cold.
Problems that come up at scale
A stale value after a correct invalidation
"Write the database, then delete the key" is not free of races. A reader misses the cache and reads the old value from the database. Before the reader stores it, a writer commits a new value and deletes the key. The reader then stores the old value, and it stays in the cache until the TTL ends. Cache-aside therefore gives eventual consistency, not strong consistency. Keep TTLs short enough to bound the damage, store a version number with the value and refuse to overwrite a newer version, and read anything that must be correct, such as the price at checkout, from the database.
Cache stampede
When a very popular key expires, every request that arrives before it is refilled misses and runs the same database query at the same moment. The fix is to let one request rebuild the value while the others wait for it or are served the old value. This is done with a per-key lock or with request coalescing inside each server. Refreshing hot keys shortly before they expire also helps.
Many keys expiring together
If a deploy or a warm-up job fills the cache with thousands of keys that share one TTL, they all expire in the same second and the database receives all the misses at once. Add a random offset to each TTL so that expiries spread out.
Requests for keys that do not exist
A lookup for an id that is not in the database can never be cached as a value, so every such request reaches the database. A buggy client or an attacker can use this to bypass the cache completely. Cache the "not found" result with a short TTL, and validate ids before looking them up.
Hot keys
A single key, such as a celebrity's profile, can receive more traffic than the one cache node that holds it can serve. Adding nodes does not help, because the key still lives on one node. Copy the hot value into each app server's local cache for a few seconds, or spread its reads over replicas of that node.
The cache is down
With cache-aside the application falls back to the database, which then receives the full read load that the cache used to absorb and may fail too. Plan for it: run cache replicas with automatic failover, put short timeouts on cache calls, limit how many misses are allowed through to the database, and refill a new cache gradually before sending it full traffic.
Scaling the cache across nodes
When the data no longer fits on one node, the keys are split across several nodes, and each client hashes the key to find the node that owns it. A plain hash(key) % N moves almost every key when a node is added or removed, which empties the cache in one step. Consistent hashing moves only about 1/N of the keys. Each node normally also has a replica that takes over when it fails. Replication between them is usually asynchronous, so a failover can lose the most recent writes, which is acceptable for a cache-aside cache and is one more reason to avoid write-behind for important data.
In the interview
Add a cache when reads far outnumber writes and the same data is read repeatedly, and say so: "Reads outnumber writes by about 100 to 1 and a small set of products gets most of the traffic, so I'd use cache-aside with a ten-minute TTL and delete the key on every write." State how stale the data may be, and name what is never read from the cache.
Questions to expect:
- "How do you keep the cache consistent with the database?" Write the database first and then delete the key, with a TTL as a backstop. Explain the race above, and say that data which must be correct is read from the database.
- "Why delete the key instead of updating it?" Two concurrent updates can reach the cache in the wrong order and leave the older value. A delete is safe in any order, and the next read loads the current value.
- "What happens when the cache goes down?" All reads fall through to the database. Describe replicas with failover, timeouts, a limit on fall-through reads and a gradual refill.
- "What if one key is extremely hot?" More nodes do not help, because one node owns the key. Use a short-lived local cache on each app server, or read replicas for that node.
- "A popular key just expired and the database is overloaded. Why?" This is a stampede. Let one request rebuild the value while the rest wait or get the old one.
- "When would you not use a cache?" When data changes as often as it is read, when every read must be current, or when the database already handles the load. A cache adds a second copy to keep correct and another component that can fail.
- "How do you size it?" Size it for the working set, meaning the keys that are read often, not for the whole dataset. Multiply that key count by the average entry size and add headroom.
Product pages get slow during sales. What would you change?
Reads far outnumber writes here, and a few hundred products get most of the views, so I'd put a cache-aside cache in front of the product table. The key is the product id, the TTL is ten minutes, and a price change deletes the key.
Can a customer be charged a stale price?
No. The listing page can be a few minutes stale, but checkout reads the price from the database, so the cache never decides what someone pays.
What happens if the cache cluster fails during the sale?
Reads would fall through to the database and overload it. I'd run a replica for each cache node with automatic failover, and cap the number of misses that reach the database so that it slows down instead of failing.
A service counts video views at a very high write rate. Losing a few seconds of counts in a crash is acceptable. Which write strategy fits?
A cache cluster has 10 nodes, and one key receives more reads than a single node can serve. What fixes it?
With cache-aside, a write updates the database and then deletes the key. Can a reader still see a stale value afterwards?
What to practise next
Read Consistent Hashing to see how keys are placed on cache nodes, and Design a Distributed Cache to design the cache itself.