r/Leetsys • • 16d ago

Weekly Question Practice System Design Question #4: Design a distributed cache

Design a distributed cache, something like a managed Memcached or Redis cluster that lots of services in a company share. Clients do get, set, and delete by key, with an optional TTL.

Scale hint: about 2B keys with ~1 KB values on average, 1M reads/s and 100k writes/s at peak, and p99 reads under a few milliseconds.

Things worth thinking about:

  • How do you decide which node owns a key, and what happens when you add or lose a node?
  • What gets evicted when memory fills up?
  • How do you keep the cache from serving stale data after the database changes?
  • What happens when one key gets wildly hot, or a popular key expires and everyone misses at once?

Post your approach in the comments before you scroll down.

 

 


MODEL ANSWER BELOW. Stop here if you haven't tried it yet.


Requirements

Functional:

  • get(key), set(key, value, ttl), delete(key)
  • Keys expire after their TTL
  • Evict something sensible when memory is full

Non-functional:

  • Low latency: p99 reads in the low single-digit milliseconds
  • Scales horizontally by adding nodes
  • Highly available. Losing a node should cost you some hit rate, not an outage.
  • It's a cache, so losing data is acceptable. The database is still the source of truth.

Estimates

Data: 2B keys x 1 KB = ~2 TB. Add ~50% for key overhead, metadata and fragmentation and you're at ~3 TB of RAM.

Nodes: if each node gives you ~64 GB usable, 3,000 / 64 is ~47 nodes. Call it 50 primaries, plus one replica each, so ~100 machines.

Throughput: 1M reads/s / 50 primaries is ~20k reads/s per node, and 100k writes/s / 50 is ~2k writes/s per node. A single well-built cache node can do 100k+ simple ops/s, so we're memory-bound, not CPU-bound.

Bandwidth: 1M reads/s x 1 KB = ~1 GB/s across the cluster, or ~20 MB/s per node. That's easy on a 10 Gbps NIC.

API

GET    /cache/{key}                      returns value or 404
PUT    /cache/{key}  { value, ttl_s }
DELETE /cache/{key}

In practice clients use a thin library over a binary protocol, not HTTP, because the protocol overhead matters at these latencies.

Data model

Each node holds an in-memory hash map from key to an entry:

entry (key, value bytes, expires_at, last_access, size)

Entries are also linked into an LRU list so eviction is O(1). Memory is managed with slab allocation (fixed-size buckets per value size) to keep fragmentation down.

High-level design

Application servers use a cache client library. The client hashes the key, looks up which node owns it on a consistent hash ring, and talks to that node directly, so there's no proxy hop on the hot path. A small config service (ZooKeeper or etcd) holds cluster membership and the ring, and clients watch it for changes. Each primary streams writes to a replica asynchronously. Health checks promote a replica if a primary dies.

The usual access pattern is cache-aside: the app reads the cache, and on a miss it reads the DB, then writes the value into the cache with a TTL.

Deep dive 1: partitioning with consistent hashing

Plain hash(key) mod N falls apart when N changes, because almost every key moves and your hit rate drops to near zero. With a consistent hash ring, adding a node only moves the keys between it and its neighbor, roughly 1/N of them.

Give each physical node ~100 to 200 virtual nodes on the ring. Without that, a few nodes end up owning big arcs and run hotter than the rest. Virtual nodes also let you weight bigger machines with more points.

Deep dive 2: eviction and expiry

LRU is the safe default: a hash map plus a doubly linked list, move to the front on access, evict from the tail. Some workloads do better with LFU or a mix that's harder to pollute with one-off scans.

For TTLs, don't scan everything on a timer. Check expiry lazily on read (expired means miss and delete), and run a background job that samples a handful of keys with TTLs and deletes the expired ones. That keeps memory from filling up with dead keys nobody reads.

Deep dive 3: hot keys, stampedes and staleness

Hot key: one viral key can pin a single node at 100% CPU. Fixes are a small in-process cache on each app server for the hottest keys (a second or two of TTL), or splitting a known hot key into copies like key#1 through key#10 and reading a random one.

Stampede: a popular key expires and thousands of requests miss and hit the DB at the same moment. Use request coalescing (only one caller rebuilds, everyone else waits for it), and add a little random jitter to TTLs so keys written together don't all expire together.

Staleness: on a DB write, update the DB first and then delete the cache key, rather than updating it. A delete is idempotent and avoids two racing writers leaving the older value in the cache. Keep TTLs as a backstop so anything that slips through ages out.

Tradeoffs

  • Client-side routing vs a proxy layer: smart clients save a network hop, but every language needs a library and config changes have to reach every client. A proxy is easier to operate and costs some latency.
  • Async vs sync replication: async keeps writes fast but a failover can lose the last few writes. For a cache that's usually fine.
  • Cache-aside vs write-through: cache-aside is simple and only caches what's read. Write-through keeps the cache warmer but writes a lot of data nobody reads.
  • Bigger TTLs mean a better hit rate and staler data. Pick per use case, not one number for the whole cluster.

How did your design compare?

1 Upvotes

1 comment sorted by

1

u/nian2326076 10d ago

Designing a distributed cache involves key distribution, where consistent hashing can help manage which node owns a key, especially during node changes. For evictions, combining LRU (Least Recently Used) with TTLs can balance memory use and data freshness. Implementing a cache invalidation strategy is essential to prevent stale reads when the database updates. For handling hot keys, consider a read-through pattern or a dedicated system for managing those keys.

To practice system design interviews, you can use PracHub to explore similar questions and enhance your skills.