Case Study 17 β€” Distributed Cache (Redis Cluster–like)

Design a horizontally scalable in-memory cache that many application servers share β€” similar in spirit to Redis Cluster or Memcached at a high level.

1. Problem

A single Redis instance runs out of memory and becomes a bottleneck. You need a cluster that:

  • Stores key-value pairs with optional TTL
  • Routes each key to the correct node automatically
  • Survives node failures with replication
  • Scales by adding machines

2. Requirements

Functional (MVP)

  • GET key, SET key value, DELETE key
  • Optional TTL on keys
  • Cluster-aware client OR proxy that hides shard routing

Out of scope (initially)

  • Rich data types (lists, sorted sets, pub/sub) β€” treat values as opaque blobs for learning
  • Lua scripting, transactions across keys
  • Auto resharding with zero downtime (advanced ops)
  • Persistence to disk (AOF/RDB) β€” mention but don’t fully design

Non-functional

  • Sub-millisecond reads on hot keys (in-memory)
  • Horizontal scale: add nodes to increase total memory and throughput
  • High availability: tolerate single node failure without total outage
  • Tunable consistency: prefer availability + eventual consistency for cache (stale OK)

3. Back-of-the-envelope estimates

These numbers are rough order-of-magnitude math β€” not a capacity plan. In interviews, the goal is to show you know what to count and which resource breaks first. A useful shortcut: 1 QPS sustained β‰ˆ 86,400 operations/day. Cache clusters measure ops/sec, not just bytes β€” 95% reads at 200k ops/s is a very different design target than a write-heavy database.

Why we estimate

A distributed cache is not a database β€” it is an optional acceleration layer. Estimates tell us:

  • Total RAM needed including replication overhead
  • Whether single-node Redis suffices vs sharding into slots
  • Per-node ops/s vs network bandwidth
  • When replication (3Γ—) dominates cost

Assumptions

AssumptionValueWhy it matters
Total cached data500 GBWorking set size
Average value size1 KBKey count derivation
Cluster-wide ops/sec200,000/sThroughput target
Read ratio95% reads / 5% writesTypical cache pattern
Replication factor3Γ—HA β€” each primary + replicas
Cluster nodes10 primaries (+ replicas)Per-node math

Step A β€” Traffic (QPS) with labeled arithmetic

Cluster-wide operations:

Total ops/sec       = 200,000/s
Read ops            = 200,000 Γ— 95% = 190,000 reads/s
Write ops           = 200,000 Γ— 5%  = 10,000 writes/s

Per primary node (10 shards, ignoring replicas for throughput split):

Reads per node      = 190,000 Γ· 10 = 19,000 reads/s
Writes per node     = 10,000 Γ· 10  = 1,000 writes/s
Total per node      = 20,000 ops/s

Single Redis node handles ~100k+ ops/s for simple GET/SET β€” 20k/node is comfortable; headroom for hot keys and replication lag.

Keys in cluster:

Total data          = 500 GB
Avg value           = 1 KB

Key count           = 500 GB Γ· 1 KB = 500,000,000 keys (~500M keys)
Keys per node       = 500M Γ· 10 β‰ˆ 50M keys/node

Step B β€” Storage

Raw data:

Cached payload      = 500 GB

With 3Γ— replication (primary + 2 replicas per shard):

Total RAM           = 500 GB Γ— 3 = 1,500 GB = 1.5 TB cluster-wide
Per node (10 nodes) = 1.5 TB Γ· 10 β‰ˆ 150 GB RAM/node (+ ~20% overhead for metadata, replication buffers)
                    β†’ plan ~180 GB RAM machines

Overhead beyond raw values:

Key names, TTL structures, hash table overhead β‰ˆ 10–30% extra
Slot map + cluster gossip metadata is small (KB per node)

Step C β€” Bandwidth

Write payload at cluster level:

Write ops           = 10,000/s
Avg value           = 1 KB

Write bandwidth     = 10,000 Γ— 1 KB = 10 MB/s (primary β†’ replication adds ~2Γ— internal)

Read payload (client-facing):

Read ops            = 190,000/s
Avg value           = 1 KB

Read egress         β‰ˆ 190 MB/s cluster-wide (~19 MB/s per node)

Network is not the bottleneck at these sizes β€” RAM capacity and hot key skew are.

Step D β€” Read:write ratio table

OperationTypeCluster QPSPer-node QPS (10 shards)
GETRead190,000/s19,000/s
SETWrite10,000/s1,000/s
DELETEWriteIncluded in 5%~500/s
Replication streamInternal write~10,000/s Γ— replicasAsync copy
Slot migrationInternalRareBurst during rebalance

Ratio: 95:5 read:write β€” optimize for read latency; accept brief replication lag on writes.

What the numbers tell us

  • 500 GB exceeds single-node RAM β†’ shard into 10+ primaries using fixed 16,384 slots
  • 3Γ— replication triples RAM cost (1.5 TB total) β€” non-negotiable for HA unless you accept data loss on crash
  • 200k ops/s is modest per node (19k/s) β€” cluster scales horizontally by adding shards, not bigger CPUs
  • Smart clients must handle MOVED/ASK redirects during slot migration
  • Async replication keeps writes fast; accept tiny loss window or use sync for critical keys only
  • Cache-aside pattern in app layer β€” on miss, load from DB and populate with TTL
  • Hot keys (celebrity user profile) need app-level splitting or local L1 cache β€” hashing won't help one key

Common mistake for this problem

Treating the cache as source of truth β€” if a node dies with async replication, un-replicated writes can vanish. The app must tolerate cache miss and always fall back to DB. Another mistake: consistent hashing without fixed slots β€” Redis Cluster's 16k slots enable incremental migration; naive ring rebalance moves too many keys at once.

4. High-Level Design (HLD)

Components

ComponentRole
Cache nodeIn-memory hash table + TTL heap/timer wheel
Smart client / proxyComputes slot = hash(key), maps slot β†’ node, retries on MOVED/ASK
ReplicationEach primary has β‰₯1 replica; async replication
Gossip protocolNodes exchange membership, slot ownership, health
Slot mapFixed 16,384 slots (Redis Cluster model) assigned to primaries
Cluster manager (optional)Operator tool for add/remove node, rebalance slots

Flows

GET

  1. Client hashes key β†’ slot β†’ primary node
  2. Primary serves from memory; on miss return NULL (cache miss β€” app loads from DB)
  3. If primary down, client tries replica (read-your-replicas policy)

SET

  1. Route to primary for key’s slot
  2. Primary writes locally, responds OK to client
  3. Async replicate to replica(s)

Node failure

  1. Gossip detects primary timeout
  2. Replica promoted (manual or automatic with quorum)
  3. Slot map updated; clients refresh topology

Add node (scale out)

  1. Join empty node to cluster
  2. Migrate subset of slots from existing primaries (live migration, key by key)
  3. Update slot β†’ node mapping

Trade-offs

ChoiceProsCons
Consistent hashing vs fixed slotsSlots allow incremental migration (Redis model)More metadata to manage
Client-side vs proxy routingNo extra hop; lower latencyEvery language needs cluster-aware client
Async replicationFast writesBrief window of loss on primary crash
1 vs 3 replicasCheaperLess fault tolerance
Cache vs source of truthSimple, fastMust handle invalidation in app layer

5. Low-Level Design (LLD)

API (single-node view; cluster adds routing)

GET    /cache/{key}           β†’ 200 value | 404 miss
PUT    /cache/{key}           body: bytes, Header: X-TTL-Seconds: 300
DELETE /cache/{key}           β†’ 204

Cluster protocol (conceptual):
MOVED 5798 192.168.1.12:6379   // permanent redirect β€” slot moved
ASK 5798 192.168.1.99:6379     // temporary redirect during migration

Slot assignment

SLOT_COUNT = 16384

function slotForKey(key):
  // Redis uses CRC16(key) mod 16384; simplified:
  return crc16(key) % SLOT_COUNT

function primaryForSlot(slot, topology):
  return topology.slotToPrimary[slot]

On-node storage

// In-memory structures per node
HashMap<String, Entry> store

Entry {
  value: byte[]
  expiresAt: epochMs | null
}

// Periodic or lazy expiry
on GET: if entry.expired: delete and return miss

Modules

CacheNode (network IO, command parser)
StorageEngine (get/set/del, TTL)
ReplicationLog (append entries, ship to replicas)
GossipAgent (heartbeat, failure detection)
SlotMigrator (key-by-key move during rebalance)
ClusterClient (slot cache, MOVED handling, pipelining)

Algorithm β€” cluster GET (smart client)

function clusterGet(key):
  slot = slotForKey(key)
  node = slotCache.primaryFor(slot)

  for attempt in 1..3:
    resp = node.send("GET " + key)
    if resp.ok: return resp.value
    if resp.type == MOVED:
      node = connect(resp.newHost)
      slotCache.update(slot, node)
      continue
    if resp.type == ASK:
      temp = connect(resp.migrateHost)
      return temp.send("GET " + key)   // one-off during migration
    if resp.type == CONNECTION_ERROR:
      node = pickReplica(slot)
      continue
  fail("cluster unavailable")

Algorithm β€” replication (primary β†’ replica)

// Primary
function set(key, value, ttl):
  store.put(key, Entry(value, now()+ttl))
  replLog.append(SET, key, value, ttl)
  return OK

// Replica
function applyReplEntry(entry):
  if entry.op == SET: store.put(...)
  if entry.op == DEL: store.delete(...)
  // replication offset tracked for partial resync

Algorithm β€” slot migration (simplified)

function migrateSlot(slot, fromNode, toNode):
  toNode.prepareImport(slot)          // target marks slot IMPORTING
  fromNode.prepareExport(slot)        // source marks slot MIGRATING
  for key in fromNode.keysInSlot(slot):
    value = fromNode.dump(key)
    toNode.restore(key, value)
    fromNode.delete(key)
  cluster.assignSlot(slot, toNode)
  broadcastNewTopology()

Concurrency notes

  • Single-threaded event loop per node (Redis model) avoids lock contention on hot keys
  • Hot keys: optional local read replica on app server OR duplicate key with {hashTag} sharding:
// Same hash tag β†’ same slot; use for intentional co-location
key = "{user:42}:profile"
key = "{user:42}:settings"
  • Splitting hot key: key β†’ key:1, key:2 … key:N with random read choice (application-level)
  • During migration, ASK redirects prevent stale reads from wrong node

6. Scale evolution

StageSizeChanges
MVP< 32 GBSingle Redis instance + app-side cache
Vertical limitMemory boundRedis primary + read replicas (no sharding yet)
Sharded100s GB3–6 primaries, 16k slots, smart client
Large cluster1 TB+20+ shards, proxy layer (Envoy/Twemproxy) for non-smart clients
Multi-DCGlobal appsActive-active is hard; prefer cache per region + async invalidation
Ops maturityFrequent reshardingAutomated slot balancer, monitoring per-slot heat

7. Recap

  • Shard by key hash into fixed slots β€” enables incremental migration
  • Replicate asynchronously for speed; accept tiny loss window or use sync for critical keys only
  • Smart clients must handle topology changes (MOVED, ASK)
  • A distributed cache is not your database β€” always design cache-aside with TTL and invalidation

Practice: explain consistent hashing vs 16,384 slots to a friend, then sketch what happens when a primary dies mid-write.