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.

Advanced 3 min readLesson 20 of 20

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.

LRU cache with TTL
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));
    }
}

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?

OptionHowTrade-off
Client-sideClients know the ring and connect directlyFastest; clients need cluster awareness
ProxyClients talk to a proxy (twemproxy, Envoy)Simple clients; extra hop
Server redirectAny node answers "MOVED to node 3"Redis Cluster; smart clients cache the map

4. Architecture

App + cache clienthash ringConfig / membershipZooKeeper / gossipShard A primaryShard B primaryShard C primaryA replicaB replicaC replica

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

ProblemMitigation
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 valuesCap value size; compress; split large objects
Thundering herd on expiryRequest coalescing, early refresh, TTL jitter (Caching)
Cold start after failureWarm 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.

Key takeaways
  • 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.