A distributed cache stores key-value pairs in memory across many machines, so applications can read hot data in a few milliseconds instead of going to a database. Redis and Memcached are the well-known examples. In this problem you design one yourself: the API, the data structure inside each node, how keys expire, and how the data spreads across clusters. This page runs it through the Interview Approach, one step at a time. For when to use a cache, Redis vs Memcached, and consistent hashing in depth, see the concept note Distributed Cache.
1. Functional requirements#
Start with what a user of the cache must be able to do:
- A user can set, get and delete key-value pairs.
- When the cache is full, it evicts entries with an LRU (least recently used) policy.
- A user can set an expiration time (TTL) for each key-value pair.
Out of scope: rich data types like lists and sorted sets, transactions across keys, pub/sub, and persistence to disk beyond the backing database.
2. Non-functional requirements#
These three qualities shape the design. Each one gets a number or a clear rule:
| Quality | Requirement |
|---|---|
| Scalable | Holds 1 TB of data and serves 1 million requests per second |
| Availability over consistency | The cache keeps answering when a node fails. A read may briefly return a value that was just overwritten |
| Low latency | A get or set completes in under 10 ms at p99 |
A quick estimate shows why the cache can't be one machine:
- Memory: 1 TB doesn't fit in one server's RAM. With about 64 GB of usable memory per node, you need about 16 primary nodes, more with headroom.
- Throughput: a single in-memory node handles roughly 100,000 simple operations per second. 1 million requests per second needs at least 10 nodes, so memory and throughput point to the same cluster size.
- Replicas: one read replica per primary doubles the node count to about 32, and gives each shard a standby.
3. Actors#
Two kinds of users touch the cache, and only one of them is on the hot path:
| Actor | What they do | Access |
|---|---|---|
| Application service | Sets, gets and deletes keys on every request it handles | Internal network only, authenticated per service |
| Operator | Adds or removes nodes, sets memory limits and the eviction policy | Admin access, rarely used |
The cache isn't public. Its callers are other backend services, which is why a few milliseconds of network time matter so much.
4. API routing#
Three endpoints cover the application service. The key is part of the path:
| Actor | Endpoint | Response |
|---|---|---|
| Application service | POST /v1/keys/{key} |
200 success |
| Application service | GET /v1/keys/{key} |
200 with the value, or 404 if missing or expired |
| Application service | DELETE /v1/keys/{key} |
200 success |
The set request carries the value and an optional TTL in the body:
{
"value": string,
"ttlSeconds": int (optional)
}
HTTP keeps the interview conversation simple. Real caches use a compact binary or text protocol over long-lived TCP connections, like Redis's RESP, because HTTP headers and connection setup cost time you can't spare under 10 ms.
5. High-level design#
Build the design one functional requirement at a time. Start with one server, one cache and one database, and ignore scale for now.
Set, get and delete (requirement 1). The client talks to a server, which sits in front of the cache and a database that keeps the source of truth:
- Set: the client sends
POST /v1/keys/{key}. The server stores the pair in the database and returns200success. The cache fills on the next read. - Get: the client sends
GET /v1/keys/{key}. If the key exists in the cache, the server fetches it from the cache. If it's not cached, the server fetches it from the database, puts it in the cache, and returns200with the value. - Delete: the client sends
DELETE /v1/keys/{key}. The server deletes the data in the database, then invalidates the key in the cache, and returns200.
This read path is the cache-aside pattern. Writes go around the cache, so a key that's written but never read doesn't use memory.
LRU eviction (requirement 2). Each cache node needs get, set, delete and "evict the least recently used key" in time. No single structure does all four, so combine two:
- A hashmap from each key to its entry, for lookup and delete.
- A doubly linked list of the same entries, ordered by last use. This list implements LRU.
Every entry in the list holds these fields:
| Field | Meaning |
|---|---|
key |
string, also the hashmap key |
value |
string or bytes |
expiresAt |
timestamp, from the TTL |
prev, next |
pointers to the neighbor entries |
The list works like this:
| Operation | What happens |
|---|---|
| Set a new key | Add the entry at the head (most recently used) and to the hashmap |
| Get a key | Find it in the hashmap, then move its entry to the head |
| Delete a key | Find it in the hashmap, unlink it from the list, remove it from the map |
| Cache is full | Evict the entry at the tail (least recently used) and remove it from the map |
The list must be doubly linked. Moving an entry from the middle to the head needs its previous neighbor, and a singly linked list would need to find it.
Expiration (requirement 3). Each entry also stores a TTL, kept as an absolute expiration timestamp. Two mechanisms remove expired keys:
- On read: a get checks the timestamp first. An expired entry is deleted and treated as a miss.
- Janitor: a background janitor process periodically evicts keys based on their timestamps, so expired keys that nobody reads don't hold memory forever.
6. Address the non-functional requirements#
The basic design works on one machine. Now take each quality and find where the design breaks it.
Scalable#
One node can't hold 1 TB or serve 1 million requests per second. Split the key space across many Redis-style key-value clusters (shards). Each server finds the right cluster by consistent hashing: it hashes the key onto a ring and picks the first cluster clockwise. When you add a cluster, only about of keys move, instead of most of them with hash(key) % N. The concept note covers the ring and virtual nodes in Spreading keys across cache nodes.
Two trade-offs come with sharding:
- LRU becomes per node. Each shard evicts its own least recently used key, not the globally oldest one. With an even spread of keys, that's close enough.
- No multi-key operations. Two keys usually live on different shards, so the cache can't update them together atomically.
To avoid an extra hop, the server keeps the ring in memory and connects straight to the right cluster. When the operator adds a node, the new ring is pushed to every server.
Availability over consistency#
If a shard's only node fails, every key on it is gone until the node returns. Inside each cluster, a primary (cache1, cache2, ...) pushes every update asynchronously to a read replica. If the primary fails, the replica is promoted and takes over. Replicas can also serve reads for hot keys. See Replication models.
The trade-off is the "availability over consistency" choice from step 2:
- Lost writes on failover. An update the primary accepted but hadn't pushed yet is lost when the replica takes over. The database still has the value, so the next miss reloads it.
- Stale reads. A read from a replica may return the old value for a few milliseconds after a write.
Synchronous replication would remove both problems, but every write would wait for the replica. That breaks the latency goal and stops writes when the replica is down.
Deletes have a similar gap. The server deletes from the database first, then invalidates the key in the cache. If the invalidation fails, or a concurrent get reloads the old value in between, the cache serves stale data until the key's TTL runs out. Always setting a TTL bounds how long any stale value can live.
Low latency#
Every operation is a hashmap lookup plus a few pointer moves, so the work on a node takes microseconds. What breaks the 10 ms goal is everything around it:
| Risk | Fix | Trade-off |
|---|---|---|
| Network setup on each call | Keep pooled, long-lived TCP connections from each server | More open connections per node |
| Extra routing hop | Route by consistent hashing in the server, straight to the shard | Every server must keep the ring up to date |
| Janitor blocks the node | Check a small random sample of keys with TTLs each cycle, and repeat only if many were expired | Some expired keys linger until sampled or read |
| Locks on the linked list | Run commands on a single thread per node, like Redis, so the list needs no locks | One node uses one core, so you add shards to scale |
| One very hot key | Serve reads from replicas or a small cache inside the application | Those reads can be slightly stale |
The janitor fix is how Redis handles expiry: lazy deletion on read, plus a sampled background sweep. A full scan of every key would pause the node for seconds at 1 TB. To protect the database when a popular key expires, use the stampede fixes in the concept note.
Whiteboard sketch#
The sketch below is the design from steps 5 and 6: the set, get and delete flows between the client, server, cache and database, the janitor, the LRU linked list, and the sharded clusters with read replicas.

Key takeaways#
- Three functional requirements: set, get and delete keys, evict with LRU when full, and expire keys by TTL.
- Each node pairs a hashmap with a doubly linked list: add at the head, evict from the tail, everything in .
- Expire keys two ways: check on every read, and run a janitor that samples keys in the background.
- 1 TB and 1 million requests per second need about 16 or more shards. Route keys to them with consistent hashing.
- Each primary pushes updates asynchronously to a read replica. You trade a few lost or stale writes for availability and low latency.
- Delete from the database, then invalidate the cache, and always set a TTL to bound stale data.