Design a distributed cache: sharding, replication, hot keys and multi-level caching

"Design a distributed cache" asks for the thing behind Memcached and Redis Cluster: many nodes that hold hot data in memory so the database does not have to serve it. The cache-aside pattern, eviction and stampedes are in the caching lesson, and the data structures are in the Redis lesson. This lesson is about the cluster: how a key finds its node, what happens when a node dies or the cluster grows, how one hot key is handled, and how a local cache fits in front. It includes the placement code, tested.

1. Requirements and Scope

  • Functional: get, set and delete by key, with a time to live (TTL). Values are blobs up to 1 MB.
  • Speed and scale: under 1 ms inside the cluster at the 99th percentile, 1 million reads and 100,000 writes a second at peak, a hot data set of 500 GB.
  • Availability: losing a node must not take the application down. The cache is not the source of truth, so a lost entry is a miss, never lost data. Say this first. It is what lets us choose speed over durability.
  • Out of scope: persistence, transactions and queries (an in-memory data grid such as Apache Ignite adds them), and cache invalidation logic (see the caching lesson).

2. Estimation

  • The database sets the target. The database can serve 50,000 reads a second. Reads that miss the cache go to it: (1 - hit rate) x 1,000,000. A 95% hit rate sends exactly 50,000, at the limit. At 90% it is 100,000, double what the database can take. Every point of hit rate is 10,000 database reads a second.
  • Memory: 500 GB of 1 KB entries is 500 million entries. A 64 GB node gives about 48 GB for data, so 500 / 48 is about 11 nodes.
  • Throughput: 1.1 million operations a second at about 100,000 a node (a conservative figure once network cost is included) is also 11 nodes.
  • Headroom: add 30% and round up to 15 nodes. With one replica of every key, memory doubles to 1 TB and the cluster to about 30 nodes.
  • Network: 1 KB at 1 million reads a second is 1 GB a second in total, or about 70 MB a second per node. A 10 Gbit link is enough.

3. API and Where Routing Lives

The API is three calls. The real decision is which component maps a key to a node.

Approach How it works Trade-off
Smart client A library in every application holds the node list and hashes the key (Memcached clients work this way) No extra hop, fastest. Every client needs the library and the current membership
Proxy Clients talk to a proxy tier that routes (twemproxy, mcrouter, Envoy's Redis proxy) Simple clients and central control, at the price of one more network hop and a tier to run
Cluster redirect Any node accepts a request and answers "ask node B" if the key is not its own (Redis Cluster, with 16,384 fixed hash slots) No separate tier. Clients cache the slot map, so a redirect is only needed when the map is stale

I would choose the smart client for a latency-critical path and a proxy where many languages and teams share the cache.

4. High-Level Design

flowchart LR
    A[Application with cache library] --> L1[(Local L1 cache)]
    A -->|hash ring| N1[Cache node 1]
    A -->|hash ring| N2[Cache node 2]
    A -->|hash ring| N3[Cache node 3]
    N1 -.replica.-> N2
    N2 -.replica.-> N3
    A -->|miss| DB[(Database)]
    M[Membership service] -.node list.-> A
  • The application library checks its local cache, then the node the ring names, and only then the database (cache-aside). On a miss it fills the cache.
  • A membership service (a configuration store, or gossip between nodes) tells clients which nodes are alive. Clients refresh the list often and also react when a node stops answering.
  • Each node is plain: a hash table, an eviction policy and TTLs. Nodes do not know about each other, which keeps them fast and simple. Replication and routing are decided by the client or proxy.

5. Placement: Consistent Hashing

The obvious rule is node = hash(key) % N. When N changes from 10 to 11, a key keeps its node only if hash mod 10 equals hash mod 11, so about 91% of keys move. Almost the whole cache becomes cold in one moment, and the database receives most of the traffic.

Consistent hashing places the nodes on a ring of hash values, and a key belongs to the first node clockwise from its hash. Adding a node takes over only the keys between it and the previous node, about 1/(N+1) of the total. Each node appears at many points on the ring, as virtual nodes, so the load evens out and a leaving node's keys spread over all the others. Imports are omitted.

class HashRing {
    private final int virtualNodes;
    private final TreeMap<Long, String> ring = new TreeMap<>();

    HashRing(int virtualNodes) {
        if (virtualNodes < 1) throw new IllegalArgumentException("need at least one virtual node");
        this.virtualNodes = virtualNodes;
    }

    void addNode(String node) {
        for (int i = 0; i < virtualNodes; i++) ring.put(hash(node + "#" + i), node);
    }

    void removeNode(String node) {
        ring.values().removeIf(node::equals);
    }

    String nodeFor(String key) {
        return nodesFor(key, 1).get(0);
    }

    /** The first {@code count} distinct nodes clockwise from the key: the primary, then its replicas. */
    List<String> nodesFor(String key, int count) {
        if (ring.isEmpty()) throw new IllegalStateException("no nodes");
        List<String> result = new ArrayList<>();
        long h = hash(key);
        for (var part : List.of(ring.tailMap(h), ring.headMap(h)))
            for (String node : part.values()) {
                if (!result.contains(node)) result.add(node);
                if (result.size() == count) return result;
            }
        return result;                          // fewer nodes than requested
    }

    private static long hash(String s) {
        try {
            byte[] md5 = MessageDigest.getInstance("MD5").digest(s.getBytes(StandardCharsets.UTF_8));
            return ByteBuffer.wrap(md5).getLong();
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }
}

The numbers are measured on 100,000 keys and 10 nodes, where the mean is 10,000 keys a node:

  • With 1 virtual node each, the busiest node holds 22,960 keys and the quietest 1,278. With 10, the range is 6,735 to 14,653. With 100, it is 8,893 to 10,710, and with 200, 9,101 to 11,046. A hundred or more virtual nodes a server is the usual choice.
  • Adding an 11th node moved 8,992 keys (9.0%, against the expected 9.1%), and every moved key went to the new node. Modulo hashing moved 90,925.
class HashRingTest {
    private static HashRing ring(int virtualNodes, int nodes) {
        HashRing r = new HashRing(virtualNodes);
        for (int i = 0; i < nodes; i++) r.addNode("cache-" + i);
        return r;
    }

    @Test
    void addingANodeMovesAboutOneInElevenKeysAllToTheNewNode() {
        HashRing r = ring(200, 10);
        Map<String, String> before = new HashMap<>();
        for (int k = 0; k < 100_000; k++) before.put("user:" + k, r.nodeFor("user:" + k));
        r.addNode("cache-10");
        int moved = 0;
        for (var e : before.entrySet()) {
            String now = r.nodeFor(e.getKey());
            if (!now.equals(e.getValue())) { moved++; assertEquals("cache-10", now); }
        }
        assertTrue(moved > 6_000 && moved < 12_000, "moved " + moved);          // about 9,091
    }

    @Test
    void moduloHashingMovesAlmostEverything() {
        int moved = 0;
        for (int k = 0; k < 100_000; k++) {
            int h = ("user:" + k).hashCode();
            if (Math.floorMod(h, 10) != Math.floorMod(h, 11)) moved++;
        }
        assertTrue(moved > 85_000, "moved " + moved);
    }

    @Test
    void replicasAreDistinctNodesAndTheFirstIsThePrimary() {
        HashRing r = ring(200, 5);
        for (int k = 0; k < 1_000; k++) {
            List<String> nodes = r.nodesFor("user:" + k, 3);
            assertEquals(3, new HashSet<>(nodes).size());
            assertEquals(r.nodeFor("user:" + k), nodes.get(0));
        }
    }
}

The tests catch real bugs. With a single virtual node the balance test fails. If removeNode does nothing, the removal test fails. If replicas may repeat a node, the replica test fails, and without the wrap-around past the end of the ring, the tests fail too. Redis Cluster uses a fixed slot map instead of a ring: keys hash to one of 16,384 slots, and resizing moves whole slots. The effect is the same, and the map is easier to inspect.

6. Replication and Node Failure

Start with the arithmetic of losing a node in the 15-node cluster, with no replicas. One node holds 1/15 of the keys, so 6.7% of the hits become misses. The hit rate falls from 95% to about 88.7%, and the database receives 113,000 reads a second against a capacity of 50,000. One failed cache node can take down the database, so replication is a protection for the database more than for the cache.

Option Memory When a node dies
No replicas 1x 1/N of the keys go cold. Safe only if the database can absorb the spike, or load is shed
One replica, written asynchronously 2x Reads move to the replica, which is warm. It may lag the primary by a moment, so a stale value can be served until the TTL
Replicas serve reads too 2x or more Reads spread over copies and survive failures, but values can differ between copies. Use it for hot keys

The replicas of a key are the next distinct nodes on the ring, which is what nodesFor(key, 2) returns, so they are on different machines. Put them in different racks or zones too. If memory is tight, replicate only the hottest keys. If the database can absorb the loss, skip replicas and protect it instead, with request coalescing (one database call per missing key, see the stampede section of the caching lesson) and a limit on the rate of database reads.

7. Resizing and Warm-Up

  • Adding a node makes a 16th node a cold owner of 1/16 of the keys, about 6.25%. That adds about 59,000 database reads a second (95% of 6.25% of the reads), taking the total to about 109,000. Add nodes off-peak and one at a time.
  • Warm it first. Copy the hot keys to the new node, or have clients read from the old owner and write to the new one for a while, before the new node takes traffic.
  • Use a fixed ramp for rolling restarts. Restart one node, wait until its hit rate recovers, then continue, so the cache is never mostly cold.
  • Failure detection must be calm. A client that removes a node from its ring after one slow response sees a sharp drop in hit rate. Use several failures in a row, and let the membership service decide.

8. Hot Keys

Consistent hashing balances keys, not traffic. One celebrity profile read 150,000 times a second sits on one node that can do 100,000, and adding nodes does not help. The answers, from cheapest up:

  • A short local cache in each application server. With 200 servers and a 1-second TTL, each fetches the key at most once a second, so the node sees 200 reads a second instead of 150,000. The cost is up to 1 second of staleness.
  • Replicate the hot key under several names, profile:42#0 to #9. Readers pick one at random, so the load spreads over about 10 nodes. A write must update or delete all 10 copies, so use it only for keys that are read far more than written.
  • Find hot keys automatically. Clients keep sampled counters, or the server reports them (Redis can list its most frequently used keys). Apply the two measures above to the top few keys, not to everything.

9. Multi-Level Caching

Level Typical latency Size Freshness
L1: in the application process Under a microsecond Hundreds of MB, a few thousand to a million entries Per server. Stale up to its TTL, unless invalidated
L2: the distributed cache About 0.3 to 1 ms in the same zone Terabytes Shared by all servers. Invalidated by writers
Database 5 to 20 ms Everything The truth

A small L1 in front of L2 gives most of the benefit: it takes the repeated reads for the hottest keys off the network completely, and it protects hot nodes. The price is that each server has its own copy, so an update must reach all of them. Choose one of three ways, in rising order of effort:

  • TTL only. A few seconds of staleness, no machinery. Right for most data.
  • Broadcast invalidation. The writer publishes the key on a pub/sub channel or a Kafka topic, and every server removes it from L1. A server that misses the message keeps the old value until the TTL, so keep the TTL as a safety net.
  • Versioned keys. Put the version in the key, product:42:v17, and read the current version number from L2. Old versions simply expire. Safest, and one extra lookup.

10. Eviction and Memory

  • Sampled LRU. Maintaining an exact least-recently-used list costs memory and locking for every read. Redis instead samples a few keys (5 by default) and evicts the oldest of them, which is cheap and close to exact LRU.
  • Memory layout. Memcached stores values in slab classes of fixed chunk sizes, which avoids fragmentation and wastes some space when a value does not fill its chunk. Size values with that in mind.
  • TTL with jitter. Add a random few percent to every TTL so keys loaded together do not expire together and send a wave of misses to the database.
  • Write path. Update the database first, then delete the key from the cache. Deleting is safer than setting, because a racing reader cannot overwrite a newer value with an older one as easily, and the caching lesson covers the rest of that race.

11. Common Pitfalls

  • hash % N for placement. Every resize empties the cache.
  • Too few virtual nodes, so one node holds twice the data of another.
  • Sizing the cache without sizing the database. The hit rate you need comes from the database's capacity, and so does what you survive when a node dies.
  • Scaling out at peak. New nodes start cold exactly when the database has no spare capacity.
  • Treating the cache as the source of truth. Anything that must not be lost belongs in a database.
  • Replicas on the same machine or rack, so one failure takes both.
  • Ignoring hot keys. Adding nodes does not help one overloaded key.
  • An L1 without an invalidation plan, so every server shows a different version.

12. Interview Questions and Answers

  • How do you decide which node holds a key? Consistent hashing with around 100 virtual nodes per server, in a smart client or a proxy. Adding or removing a node moves about 1/N of the keys, not nearly all of them as modulo does.
  • What happens when a cache node fails? Its keys become misses, and the database receives the extra load. With replicas on the next ring nodes, reads move to a warm copy. Without them, coalesce requests and cap database reads so the spike does not cascade.
  • How do you handle a hot key? A short local cache in each application server, or copies of the key under several names, and find the keys from counters rather than guessing.
  • How do you keep L1 and L2 consistent? Short TTLs for most data. For data that must be fresher, broadcast invalidations with the TTL as a backstop, or version the keys.
  • How would you grow the cluster from 15 to 16 nodes? Off-peak, with the new node warmed first, so that 6% of the keys do not all miss at once.
  • Why not replicate synchronously? It adds latency to every write and makes writes fail when a replica is down. A cache can tolerate a slightly stale replica, and the TTL bounds how long.