Tech Interview RoomStudy guides

System Design

Design a distributed cache like Redis Cluster or Memcached at scale.

Advanced · 3 min read · Lesson 10 of 36 in System Design

⚡
Design at a glance

Hash every key onto a ring of memory, and keep a hot spare for every shard.

< 1 msper get or set
100K ops/sper node
64 GBmemory per node
16,384hash slots in Redis Cluster
Core building blocks
Smart clients→Consistent hashing / hash slots→Shard primaries→Replicas with failover
Key decision

Consistent hashing (or fixed hash slots) so adding a node moves only about 1/N of the keys.

Trade-off
Async replication: fast writes, may lose the last writes on failover
vs
Sync replication: no loss, slower writes
Remember
  • Partition with consistent hashing
  • Replicate each shard and fail over automatically
  • Protect the DB: TTL jitter, request coalescing, hot-key copies

1. Requirements

  • get, set with TTL, delete; sub-millisecond latency; millions of operations per second; terabytes of data in memory.
  • Horizontal scaling by adding nodes with minimal data movement; tolerate node failures.
  • Consistency: cache semantics (stale reads acceptable within TTL), but replicas should converge.

2. Build it step by step

Stage 1: a single cache node

Stage 1: one cache server
Clients
Application instances
↓1. GET / SET key
Cache
Redis cache (single node)

Flow:

  1. Applications send GET key; on a miss they load from the database and SET key value EX ttl. Memory is bounded with LRU eviction.

Problem: one node limits memory (say 64 GB) and throughput (about 100K ops/s), and if it dies every request falls through to the database at once.

Stage 2: partition keys across many nodes

Stage 2: consistent hashing across shards
Clients
Application instances (hash ring in client)
↓1. hash(key) picks the node
Shards
Cache node A+Cache node B+Cache node C

Flow:

  1. The client hashes the key onto a ring with virtual nodes and sends the request to the owning node. Adding node D moves only about a quarter of the keys instead of nearly all of them (which hash mod N would do).

Problem: losing a node still loses its share of data and sends a spike to the database; clients must agree on the ring.

Stage 3: replicas, failover and a cluster map

Stage 3: primary/replica per shard with automatic failover
Clients
Smart clients (cached slot map)
↓1. route by hash slot (16,384 slots)
Primaries
Shard A primaryShard B primaryShard C primary
↓2. async replication
Replicas
+Shard A replica+Shard B replica+Shard C replica
↓3. gossip and failure detection
Control
+[svc] Cluster manager

Flow:

  1. Clients map key → slot → primary (Redis Cluster style) and are redirected with MOVED if their map is stale.
  2. Each primary replicates to a replica.
  3. If a primary fails, the cluster promotes its replica and clients refresh the map.

Problem: a single extremely hot key still lands on one shard, and mass expiry of a popular key causes a thundering herd on the database.

Final architecture: near cache and stampede protection

Final architecture
Clients
Application instances+Near cache (Caffeine)
↓1. local hit returns in microseconds
Shards
Shard A primaryShard B primaryShard C primary
↓2. async replication
Replicas
Shard A replicaShard B replicaShard C replica
↓health and membership
Control
⚙️ Cluster manager (gossip or coordinator)
↓3. single-flight load on miss
Database
🗄️ Source database

End-to-end read:

  1. The app checks a small local cache for the hottest keys.
  2. Then the owning shard (replicas can serve reads for hot keys).
  3. On a miss, only one caller loads from the database (request coalescing or a short lock) while others wait; TTLs have jitter so popular keys do not expire together.

End-to-end write: the database is updated first, then the cache key is deleted (or invalidated via a change stream).

3. Deep dives

  • Partitioning: simple hash(key) mod N remaps almost every key when N changes. Use consistent hashing with virtual nodes (each physical node owns many points on a ring), so adding a node moves only about 1/N of keys and load stays even. Redis Cluster uses a variant: 16,384 hash slots assigned to nodes; resharding moves slots.
  • Routing: smart clients cache the slot map and talk directly to the right node (Redis Cluster returns MOVED when the map is stale), or a proxy layer (Twemproxy, Envoy) routes for dumb clients.
  • Replication and failover: each primary has replicas with asynchronous replication; the cluster detects failure by gossip and promotes a replica. Asynchronous replication means acknowledged writes can be lost on failover, which is acceptable for a cache.
  • Eviction: when memory is full, evict by LRU or LFU approximations (Redis samples keys rather than keeping an exact LRU list); TTL expiry is done lazily on access plus by an active sampling sweep.
  • Memory efficiency: compact encodings for small hashes and lists, avoid huge keys and values, monitor fragmentation.
  • Hot keys: a single key that receives a flood of reads is bounded by one shard. Mitigate with a local in-process cache in front (near cache), replicating the key under several names (key#1..#n) and reading a random copy, or reading from replicas.
  • Cache patterns: cache-aside (application loads on miss), read-through and write-through (cache library loads and writes), write-behind (asynchronous writes to the DB, risky).
  • Thundering herd: on a popular key's expiry, many requests miss together. Use request coalescing (single flight), a short lock key, or early probabilistic refresh, and add TTL jitter.

4. Trade-offs

Asynchronous replication gives speed but possible lost writes; synchronous replication (WAIT) costs latency. Smart clients avoid a proxy hop but complicate clients.

Follow-up questions interviewers ask

Try answering each one before you open it.

How does consistent hashing reduce data movement?

Nodes and keys are mapped onto the same hash ring; a key belongs to the first node clockwise from its position. Adding a node only takes over keys between it and its predecessor, about 1/N of the total, and removing a node hands its keys to the next node. Virtual nodes (many ring positions per node) spread each node's share across the ring, which evens out load and lets more powerful nodes take more virtual nodes.

How do you keep the cache consistent with the database?

Use cache-aside: read from cache, on miss read the DB and populate; on write, update the DB and then delete (not update) the cache key, ideally after commit. To close the race where a reader repopulates a stale value between the DB write and the delete, use short TTLs, a delayed second delete, versioned values (only write if newer), or invalidate from the database's change stream (CDC) so invalidation follows commit order.