System design interview: design a distributed cache

A distributed cache is a cluster of memory servers that behaves like one big key-value map with sub-millisecond reads. Designing one means deciding how a client finds the node that owns a key, what each node does when memory runs out, how membership changes without a flood of misses, and whether a node's data is replicated or simply lost and refilled when it dies.

By Published 9 min read

1. Clarify the requirements

This prompt is about the cache service, not about using one. Make that explicit, then pin down the operations and the guarantees the users of the cache expect.

  • Functional: get, set with an optional TTL, delete, and a batched multi-get; values up to about 1 MB; many applications (tenants) share the cluster.
  • Non-functional: reads well under a millisecond inside a data center; throughput that grows by adding nodes; losing a node must not take the cluster down; data loss is acceptable, because the source of truth is elsewhere.
  • Out of scope unless asked: persistence to disk, rich data types (lists, sorted sets), transactions, cross-region replication.

2. Estimate the scale

These are illustrative assumptions for a large shared cache, chosen to make the arithmetic easy.

Back-of-envelope sizing for a shared cache cluster (assumed figures)
QuantityAssumptionResult
Traffic1 million reads and 100,000 writes a second at peaka 10 to 1 read ratio
Data2 billion keys, about 1 KB per key and valueabout 2 TB of payload
Overheadx 1.5 for metadata, pointers and fragmentationabout 3 TB of memory
Nodes64 GB of usable memory per node3 TB / 64 GB is about 47, so about 50 nodes
Load per node1 million reads / 47 nodesabout 21,000 reads a second each, well within one node's ability
With one replicax 2about 100 nodes
Back-of-envelope sizing for a shared cache cluster (assumed figures). Scroll sideways on a small screen.

Memory, not throughput, sets the node count here. That is common for caches, and it means the interesting work is in using memory well and keeping the cluster balanced, not in squeezing more requests out of each node.

3. Define the API

GET    key                     -> value | MISS
MGET   key1 key2 ... keyN      -> values in order, MISS where absent
SET    key value [ttl_seconds] -> OK
ADD    key value [ttl]         -> OK | EXISTS   (set only if absent: used for locks and leases)
DELETE key                     -> OK | NOT_FOUND

keys are namespaced per tenant:  checkout:cart:81723
A small binary or text protocol over long-lived TCP connections; no HTTP on the hot path.

4. Inside one node

The per-node data structure is a hash table for lookups plus a doubly linked list for recency, so get, set and eviction are all O(1). Real caches add a memory allocator that hands out fixed-size chunks (to limit fragmentation) and often approximate LRU by sampling a few keys and evicting the oldest, which avoids touching a shared list on every read. The idea fits in a few lines:

import time
from collections import OrderedDict

class LRUCache:
    def __init__(self, max_bytes, clock=time.monotonic):
        self.max_bytes, self.used, self.clock = max_bytes, 0, clock
        self.items = OrderedDict()  # key -> (value, expires_at); oldest first

    def get(self, key):
        entry = self.items.get(key)
        if entry is None:
            return None
        value, expires_at = entry
        if expires_at is not None and expires_at <= self.clock():
            self._remove(key)  # lazy expiry on read
            return None
        self.items.move_to_end(key)  # now the most recently used
        return value

    def set(self, key, value, ttl=None):
        if key in self.items:
            self._remove(key)
        size = len(key) + len(value)
        if size > self.max_bytes:
            return False  # never store an item bigger than the whole cache
        while self.used + size > self.max_bytes:
            self._remove(next(iter(self.items)))  # evict least recently used
        expires_at = None if ttl is None else self.clock() + ttl
        self.items[key] = (value, expires_at)
        self.used += size
        return True

    def _remove(self, key):
        value, _ = self.items.pop(key)
        self.used -= len(key) + len(value)
Byte-budgeted LRU with lazy TTL expiry (tested against a slow reference in 300 random runs)

Lazy expiry alone leaves expired keys that nobody reads taking up memory, so a background task also samples keys with TTLs and removes the expired ones. Concurrency is the other node-level choice: one event loop per core with keys split between them, or a shared table with fine-grained locks. Either way, keep the work per request tiny and avoid commands that scan large structures.

5. The core decision: routing keys to nodes

hash(key) mod N is the obvious answer and the wrong one: changing N remaps almost every key, which empties the cache and sends the full read load to the database at once. Consistent hashing with many virtual points per node moves only the keys that land on the new node's points. The sharding guide explains the ring; here is the experiment worth quoting in an interview:

import bisect, hashlib

def h(s):
    return int.from_bytes(hashlib.md5(s.encode()).digest()[:8], "big")

class Ring:
    def __init__(self, nodes, vnodes=150):
        self.points = sorted((h(f"{n}#{i}"), n) for n in nodes for i in range(vnodes))
        self.hashes = [p for p, _ in self.points]

    def owner(self, key):
        i = bisect.bisect(self.hashes, h(key)) % len(self.points)
        return self.points[i][1]

keys = [f"user:{i}" for i in range(200_000)]
before = Ring([f"cache-{i}" for i in range(10)])
after = Ring([f"cache-{i}" for i in range(11)])
moved = sum(before.owner(k) != after.owner(k) for k in keys)
print(f"moved {moved / len(keys):.1%} of keys")  # ideal is 1/11, about 9.1%
Going from 10 to 11 nodes with 150 points per node. Output when run: moved 10.4% of keys. Plain mod-N moved about 91% of the same keys.
Where the routing logic can live
OptionHow it worksGoodCostly
Smart clientA client library holds the ring and talks to nodes directlyOne network hop, no extra tierEvery language needs the library; map updates must reach every client
Proxy tierClients send everything to a stateless proxy that forwardsThin clients, one place for routing and metricsAn extra hop and a tier to scale and keep healthy
Node redirectsAny node accepts a request and redirects if it does not own the keyClients learn the map lazilyExtra round trips while maps are stale
Where the routing logic can live. Scroll sideways on a small screen.

6. The architecture

  1. Callers
    • Application servers
    • Cache client or sidecar proxy
  2. Control plane
    • Configuration service (cluster map)
    • Health checker
    • Consensus store
  3. Cache nodes
    • Primary nodes (owners of ring segments)
    • Replica nodes in another zone
  4. Source of truth
    • Databases and services the cache fronts
A shared cache cluster with a configuration service and optional replicas. Application servers use a cache client library or a local proxy that holds the cluster map. The map comes from a small configuration service backed by a consensus store, which also receives health reports. Requests go straight to the owning cache node; each primary node may stream its writes to a replica in another availability zone. On a miss the application reads the database and sets the value.
  1. StartupA client fetches the cluster map (nodes, their ring points, which are primaries) from the configuration service and keeps a connection pool to each node.
  2. ReadHash the key, find the owner, send GET. For MGET, group keys by owner and send one request per node in parallel.
  3. WriteApplications usually delete the key after updating the database and let the next read refill it. The cache does not know about the database at all.
  4. Membership changeThe health checker marks a node down after several missed checks. The configuration service publishes a new map version; clients pick it up by watch or on their next refresh.

7. Scale it

  • Add nodes gradually. A new node takes over a slice of keys that are all misses at first. Adding several nodes at once, or giving a new node only part of its points and raising them over minutes, spreads the extra database load.
  • Warm a replacement node. When a node is replaced on purpose, copy its hot keys first, or let the new node read through from the old one for a while, so its slice is not cold.
  • Isolate tenants. Give each tenant a memory quota or its own pool, so one application's huge keys do not evict everyone else's working set.
  • Watch the big keys. Values near the size limit and very hot keys distort a node's memory and network. Track the top keys per node; the app-side fixes (local caches, key splitting) are in the caching guide.
  • Keep connections under control. Thousands of app servers times dozens of nodes is a lot of TCP connections; a local proxy per host multiplexes them.

Replicate or not

Without replicas, a dead node's keys miss until refilled, and the database briefly absorbs that node's share of reads (about 2% of traffic with 50 nodes). If the database can take that, skip replication and keep the cluster simple. If not, give each primary a replica in another zone that receives writes asynchronously; on failure, the configuration service promotes it. Asynchronous replication can lose the last few writes, which is acceptable for a cache. Some designs instead write each key to two nodes on the ring and read from either, trading memory for availability.

8. What breaks, and what you do about it

Failure modes worth naming
FailureEffectMitigation
Node crashIts keys miss; database load risesReplica promotion if replicated; otherwise ring rebalance and per-key request coalescing in clients
Network partition hides a healthy nodeClients with different maps write to different ownersMap versions from one configuration service; short TTLs on cached values bound any stale reads
Flapping nodeKeys bounce between owners and lose their warmthRequire several failed checks before removal and a quiet period before re-adding
Whole-cluster restartEvery key is a miss at onceRestart in waves; rate-limit database reads in the callers; pre-warm from a key dump if the database cannot take it
Memory fragmentationNode evicts even though usage looks lowFixed-size chunk allocator; restart nodes one at a time in quiet hours if fragmentation builds up
Failure modes worth naming. Scroll sideways on a small screen.

9. Trade-offs to discuss

  • Exact LRU or sampled. Exact LRU needs a shared list updated on every read; sampling a handful of keys and evicting the oldest gets close to LRU's hit rate with far less locking. LFU-style policies help when a burst of one-off reads would otherwise push out steady hot keys.
  • Client-side routing or proxies. Fewer hops and fewer servers versus simpler clients and central control. Large polyglot fleets lean toward proxies or sidecars.
  • Replicas or not. Twice the memory buys protection against miss storms; whether that is worth it depends on how much load the database can take.
  • Consistency with the database. The cache is eventually consistent by design. Delete-after-write plus TTLs bound the staleness; anything that needs a current value should read the database. Consistency and CAP gives the vocabulary.

10. How to talk through it in the interview

Fictional example

The rebalancing question
Interviewer
Traffic doubled. You add ten nodes to your fifty. What happens to the database?
Candidate
With mod-N routing, almost every key would move and the database would take nearly the full read load at once. With consistent hashing, roughly a sixth of the keys change owner, and those start as misses. I would add the nodes one or two at a time, or ramp their ring points up gradually, and make sure clients coalesce concurrent misses on the same key.
Interviewer
And while some clients still have the old map?
Candidate
They read and write the old owner for a few seconds. Values there are at worst a little stale and expire by TTL; deletes after database writes go to both owners during the transition.

Budget the 45 minutes roughly like this: 5 minutes to agree that losing keys is acceptable and to list the operations, 5 on sizing (memory sets the node count), 5 on the protocol, 5 on node internals, 15 on routing, membership and rebalancing, and 10 on replication, failures and trade-offs. If the interviewer is more interested in how applications use the cache, switch to the patterns in the caching guide.

  • Explain why mod-N routing fails before proposing the ring.
  • Separate the data plane (nodes) from the control plane (the cluster map).
  • State the replication choice in terms of database load, not as a default.

Practicing this design with Natively

This prompt rewards precise explanations, so rehearse it out loud. On a practice call, Natively transcribes both speakers and can surface suggested points when the interviewer asks a question, such as what happens to a dead node's keys; afterwards you can compare those with what you actually said. A screenshot of your ring or cluster sketch can be captured and explained, and the session's transcript and notes stay on your computer to review later.

Questions people ask

How do you design a distributed cache in a system design interview?

Agree that lost keys are acceptable, size the cluster from memory, then explain one node (a hash table plus an eviction order with TTLs) and how clients route keys with consistent hashing. Add a configuration service for the cluster map, decide whether to replicate, and cover rebalancing and node failures.

Why not use hash(key) mod N to pick a cache node?

Changing N remaps almost every key. In a quick test going from 10 to 11 nodes, mod-N moved about 91% of keys while a consistent hash ring with 150 points per node moved about 10%. Mass remapping turns into a burst of misses that lands on the database.

Should a distributed cache replicate its data?

Only if the database cannot absorb a dead node's share of reads. Without replicas, a failed node's keys simply miss and refill. With an asynchronous replica in another zone, the cluster promotes it on failure and avoids the miss spike, at the cost of double the memory.

What eviction policy should a cache node use?

LRU is the usual default. Many caches approximate it by sampling a few keys and evicting the least recently used of them, which avoids updating a shared list on every read. LFU-style policies help when bursts of one-off reads would otherwise push out steady hot keys.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP