Design a Distributed Cache

Design a Memcached or Redis Cluster style cache: partitioning with consistent hashing, replication, eviction, hot keys and client behaviour.

Advanced · about 4 hours · difficulty 4/5

Learn first: Consistent Hashing, Redis in Practice

Here you design the cache itself rather than just using one. It ties together hashing, replication and memory management.

Requirements

  • get(key), set(key, value, ttl), delete(key) with sub-millisecond latency.
  • Hundreds of GB to TB of data across many nodes, millions of operations per second.
  • Highly available; losing some cached data is acceptable, losing the whole cache is not.

Single node design

A hash map plus a doubly linked list gives O(1) LRU. Add TTL handling (lazy expiry on read plus a background sweeper), a memory limit with eviction, and slab or arena allocation to reduce fragmentation. An event loop (as in Redis) or a multi-threaded design with lock striping (as in Memcached) handles concurrency.

Partitioning

Spread keys across nodes with consistent hashing and virtual nodes (or Redis-style fixed hash slots). Routing can live in:

  • the client library (knows the ring, talks to nodes directly; fastest),
  • a proxy layer (twemproxy, Envoy; simpler clients),
  • or the nodes themselves redirecting clients (Redis Cluster MOVED replies).

Cluster membership comes from a config service or gossip.

Replication and availability

Give each shard a primary and one or more replicas with asynchronous replication. On primary failure, promote a replica (via a coordinator or Sentinel-style voting). Reads can go to replicas if slight staleness is fine.

Hot keys and big keys

A viral product key can overload one node. Options: client-side local caching for very hot keys, replicating hot keys to several nodes with a random suffix, and splitting big values.

Pitfalls

  • Using naive mod N hashing so adding a node flushes almost the whole cache.
  • Treating the cache as durable storage.
  • No protection against stampedes when a node restarts empty.

You are ready to move on when you can explain how a get request finds its node, what happens when a node dies or is added, and how you would handle a key receiving 1 lakh requests per second.

Key concepts

  • O(1) LRU with hash map and list
  • TTL expiry strategies
  • Consistent hashing or hash slots
  • Client vs proxy vs server routing
  • Replication and failover
  • Hot key mitigation
  • Gossip membership

Mini project

Build a mini distributed cache: 3 node processes each running an LRU with TTL over a simple TCP or HTTP protocol, and a client library using a consistent hash ring. Add a fourth node live and measure the hit ratio drop and recovery.

Check yourself

When a cache node is added to the cluster, which keys miss, and how does consistent hashing limit the damage compared with mod N hashing?

Free resources