Case Study: Distributed Cache
Design a Redis/Memcached-style distributed in-memory cache — the single-node core (hash map + LRU), partitioning with consistent hashing, replication, failure handling and hot keys.
1. Requirements
Functional: get(key), put(key, value, ttl), delete(key); evict when memory is full.
Non-functional: sub-millisecond latency, millions of operations per second, scales horizontally to terabytes, highly available. It's a cache: losing some data on failure is acceptable, but losing all of it at once would overload the database.
2. Single-node design
Each node is an in-memory hash map for O(1) lookup plus an eviction policy. LRU is implemented with a hash map pointing into a doubly linked list: a hit moves the node to the front; eviction removes from the back.
class LruCache<K, V> {
private record Entry<V>(V value, long expiresAt) {}
private final int capacity;
private final LinkedHashMap<K, Entry<V>> map;
LruCache(int capacity) {
this.capacity = capacity;
this.map = new LinkedHashMap<>(16, 0.75f, true) { // access order
protected boolean removeEldestEntry(Map.Entry<K, Entry<V>> e) {
return size() > LruCache.this.capacity;
}
};
}
synchronized V get(K key) {
Entry<V> e = map.get(key);
if (e == null) return null;
if (System.currentTimeMillis() > e.expiresAt()) { map.remove(key); return null; }
return e.value();
}
synchronized void put(K key, V value, long ttlMs) {
map.put(key, new Entry<>(value, System.currentTimeMillis() + ttlMs));
}
}import time
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity: int):
self.capacity, self.data = capacity, OrderedDict()
def get(self, key):
item = self.data.get(key)
if item is None:
return None
value, expires_at = item
if time.monotonic() > expires_at:
del self.data[key] # lazy expiry
return None
self.data.move_to_end(key) # mark most recently used
return value
def put(self, key, value, ttl: float):
self.data[key] = (value, time.monotonic() + ttl)
self.data.move_to_end(key)
if len(self.data) > self.capacity:
self.data.popitem(last=False) # evict least recently usedclass LRUCache<K, V> {
private map = new Map<K, { value: V; expiresAt: number }>(); // Map keeps insertion order
constructor(private capacity: number) {}
get(key: K): V | undefined {
const e = this.map.get(key);
if (!e) return undefined;
if (Date.now() > e.expiresAt) { this.map.delete(key); return undefined; }
this.map.delete(key); // re-insert to mark as most recent
this.map.set(key, e);
return e.value;
}
put(key: K, value: V, ttlMs: number) {
this.map.delete(key);
this.map.set(key, { value, expiresAt: Date.now() + ttlMs });
if (this.map.size > this.capacity) this.map.delete(this.map.keys().next().value!);
}
}Production details:
- Expiry: lazy (check on access) plus periodic sampling of keys with TTLs (Redis's approach).
- Approximate LRU/LFU: Redis samples a few keys and evicts the best candidate, avoiding per-access list maintenance.
- Memory efficiency: slab allocators (Memcached) to limit fragmentation; compact encodings for small values.
- Concurrency: Redis runs commands on a single thread (no locks, predictable latency), using I/O threads for networking; Memcached is multi-threaded with fine-grained locks.
3. Partitioning
One node can't hold everything. Spread keys across nodes with consistent hashing and virtual nodes (Consistent hashing), so adding a node moves only ~1/N of the keys. Redis Cluster instead uses 16,384 hash slots assigned to nodes.
Where does routing happen?
| Option | How | Trade-off |
|---|---|---|
| Client-side | Clients know the ring and connect directly | Fastest; clients need cluster awareness |
| Proxy | Clients talk to a proxy (twemproxy, Envoy) | Simple clients; extra hop |
| Server redirect | Any node answers "MOVED to node 3" | Redis Cluster; smart clients cache the map |
4. Architecture
5. Replication and failure
- Each shard has a primary and one or more replicas, replicated asynchronously (a few writes may be lost on failover — acceptable for a cache).
- Failure detection via heartbeats or gossip; a replica is promoted automatically (Redis Sentinel or Cluster).
- A membership service (or gossip) keeps clients' view of the ring current.
- Replicas can serve reads to spread load, at the cost of slightly stale data.
6. Hot keys and other problems
| Problem | Mitigation |
|---|---|
| Hot key (one key gets massive traffic) | Local in-process cache in front; replicate the key under several suffixes (key#1..#N) and read a random one |
| Big values | Cap value size; compress; split large objects |
| Thundering herd on expiry | Request coalescing, early refresh, TTL jitter (Caching) |
| Cold start after failure | Warm replicas; gradual traffic shift |
| Cache penetration (lookups for keys that don't exist) | Cache negative results briefly, or use a Bloom filter |
7. Consistency with the database
The cache is not the source of truth. Use cache-aside with delete on write (not update), TTLs as a safety net, and accept a small window of staleness. For stronger guarantees, invalidate via change data capture from the database.
- Each node: hash map + LRU (linked list) with lazy and sampled expiry.
- Partition with consistent hashing or hash slots; route in the client, a proxy, or via redirects.
- Async replication with automatic failover; losing a few writes is acceptable for a cache.
- Handle hot keys, thundering herds and penetration explicitly.
- The database remains the source of truth; invalidate on write.