Consistent hashing

Master consistent hashing, the elegant algorithm that powers distributed caches, databases, and load balancers by minimizing data movement when scaling.

intermediate12 min readBy CureBugs EditorialUpdated 5 Nov 2026

Imagine you are building a high-performance distributed cache for a rapidly growing application. You start with a few servers, but as traffic spikes, you need to add more. If you use standard hashing to distribute your data, adding just one new server will invalidate almost your entire cache, bringing your database to its knees. Consistent hashing is the elegant algorithmic solution to this exact problem. It is a foundational concept in distributed systems, powering technologies like Amazon DynamoDB, Apache Cassandra, and Discord's real-time messaging routing. In this article, we will explore why standard hashing fails at scale, how consistent hashing works, how to implement it, and the real-world trade-offs you need to discuss in system design interviews.

The Problem with Simple Modulo Hashing

When distributing data across multiple servers, the most intuitive approach is modulo hashing. You take a key (like a user_id), hash it to get a number, and take the modulo of the total number of servers ($N$).

server_index = hash(key) % N

This works perfectly, until $N$ changes.

Suppose you have 4 cache servers ($N=4$) and 100 keys distributed evenly among them. Suddenly, Server 3 crashes. Now you have 3 servers ($N=3$).

When a request comes in for a key that previously hashed to 10, the calculation changes from 10 % 4 = 2 (Server 2) to 10 % 3 = 1 (Server 1). The key is now looking for data on the wrong server.

Mathematically, when the number of servers changes from $N$ to $N-1$ or $N+1$, the probability that a key maps to the same server is roughly $\frac{1}{N}$. If you have 100 servers and one crashes, 99% of your keys will map to a different server. This triggers a massive "cache miss storm," flooding your primary database with requests and likely causing a system-wide outage.

How Consistent Hashing Works

Consistent hashing solves the reshuffling problem by mapping both the servers and the keys onto a conceptual circle, known as a Hash Ring.

  1. The Hash Space: We choose a hash function with a large output range, such as SHA-256 or MD5. If the output is 32-bit, the hash space ranges from $0$ to $2^{32}-1$. We wrap this space into a ring, where the largest value wraps around to $0$.
  2. Placing Servers: We hash the identifiers of our servers (e.g., their IP addresses or hostnames) and place them on the ring at their respective hash values.
  3. Placing Keys: When a request comes in for a key, we hash the key using the same hash function and place it on the ring.
  4. Routing: To find which server owns the key, we move clockwise around the ring starting from the key's position until we encounter the first server.

Scaling Up and Down

If Node C crashes, only the keys that were assigned to Node C (the keys between Node B and Node C) need to be reassigned. By walking clockwise, these keys will now naturally fall to Node A. The keys assigned to Node A and Node B are completely unaffected.

Similarly, if we add a new Node D between Node A and Node B, Node D will take over a portion of Node B's keys. The rest of the ring remains untouched. This guarantees that only $\frac{1}{N}$ of the data moves when the cluster size changes.

Virtual Nodes (VNodes): Solving Uneven Distribution

Basic consistent hashing has a critical flaw: uneven data distribution.

Because we are hashing server IPs, there is no guarantee they will be evenly spaced around the ring. Node A and Node B might end up right next to each other, meaning Node B gets almost no traffic, while Node C handles half the ring. Furthermore, if Node C crashes, its entire massive workload is dumped onto the next node, potentially causing a cascading failure.

To solve this, we introduce Virtual Nodes (VNodes). Instead of mapping a physical server to a single point on the ring, we map it to multiple points.

For example, instead of hashing NodeA, we hash NodeA#01, NodeA#02, ..., NodeA#100.

  • A single physical server now represents 100 virtual nodes scattered randomly across the ring.
  • If a physical server crashes, its 100 virtual nodes disappear, and its workload is evenly distributed among the remaining physical servers on the ring, preventing cascading failures.
  • As a bonus, you can assign more virtual nodes to powerful servers and fewer to weaker ones, enabling heterogeneous clusters.

Implementation

Here is how you can implement a consistent hash ring with virtual nodes. We use binary search to efficiently find the next node on the ring in $O(\log V)$ time, where $V$ is the total number of virtual nodes.

import hashlib
import bisect

class ConsistentHash:
    def __init__(self, num_vnodes=100):
        self.num_vnodes = num_vnodes
        self.ring = []
        self.node_map = {}

    def _hash(self, key):
        # Use MD5 for a good distribution, taking the first 8 hex chars as an integer
        return int(hashlib.md5(key.encode('utf-8')).hexdigest()[:8], 16)

    def add_node(self, node_name):
        for i in range(self.num_vnodes):
            vnode_key = f"{node_name}#{i}"
            h = self._hash(vnode_key)
            bisect.insort(self.ring, h)
            self.node_map[h] = node_name

    def remove_node(self, node_name):
        for i in range(self.num_vnodes):
            vnode_key = f"{node_name}#{i}"
            h = self._hash(vnode_key)
            self.ring.remove(h)
            del self.node_map[h]

    def get_node(self, key):
        if not self.ring:
            return None
        h = self._hash(key)
        idx = bisect.bisect(self.ring, h)
        # If the hash is greater than the largest ring value, wrap around to 0
        if idx == len(self.ring):
            idx = 0
        return self.node_map[self.ring[idx]]

Comparison of Partitioning Strategies

StrategyData Movement on ScalingLoad DistributionLookup Complexity
Modulo HashingHigh ($O(K)$)Good (if hash is uniform)$O(1)$
Basic Consistent HashingLow ($O(K/N)$)Poor (uneven spacing)$O(\log N)$
Consistent Hashing with VNodesLow ($O(K/N)$)Excellent$O(\log(N \times V))$
Rendezvous HashingLow ($O(K/N)$)Good$O(N)$ (without optimizations)

Trade-offs and Failure Modes

While consistent hashing is powerful, it is not a silver bullet. You must be prepared to discuss its limitations in a system design interview.

1. The "Hot Key" (Celebrity) Problem

Consistent hashing guarantees that keys are distributed evenly across servers. However, it does not guarantee that traffic is distributed evenly. If you are building a social network and Justin Bieber posts a photo, millions of users will request that specific photo (a single key). Consistent hashing will faithfully route all millions of requests to the exact same server, melting it down.

2. Memory Overhead

Maintaining a ring with thousands of virtual nodes requires memory. While a few megabytes is trivial for a backend service, if you are pushing the routing logic to lightweight edge clients, the memory footprint and the cost of syncing the ring state can become a bottleneck.

3. Data Migration Lag

In a stateless caching layer, adding a node simply results in a few cache misses until the new node warms up. However, in a stateful database (like Cassandra), adding a node requires physically migrating gigabytes of data from the successor node to the new node over the network. The ring tells you where the data should go, but the system still has to do the heavy lifting of moving it safely.

Real-World Examples

  • Amazon Dynamo & Apache Cassandra: Both use consistent hashing with virtual nodes to partition data across clusters. They also use the ring for replication: to store 3 copies of a piece of data, the system finds the primary node on the ring, then walks clockwise to find the next 2 distinct physical nodes to store the replicas.
  • Discord: Uses consistent hashing to route real-time WebSocket messages to the specific server hosting a chat channel.
  • Content Delivery Networks (CDNs): CDNs like Akamai use consistent hashing to map video segments to specific edge servers, maximizing cache hit rates.

Interview Questions

1. How does consistent hashing handle data replication?

Model Answer: Instead of stopping at the first node found on the ring, the algorithm continues walking clockwise to select the next $R$ (replication factor) distinct physical nodes. It is crucial to ensure that virtual nodes mapping to the same physical machine are skipped during this walk, so replicas end up on isolated hardware to survive single-machine failures.

2. What happens to the system when a node goes down?

Model Answer: The virtual nodes belonging to the crashed physical node are removed from the ring. The keys that previously mapped to those vnodes will now map to their immediate clockwise successors. If this is a cache, those keys will experience cache misses and be re-fetched from the database. If it's a database, the system will rely on replica nodes to serve the data while background processes (like hinted handoff or read repair) restore the desired replication factor.

3. How do you determine the optimal number of virtual nodes?

Model Answer: It is a trade-off between load balance and state overhead. More vnodes result in a lower standard deviation of load across servers, but increase the size of the routing table and slightly slow down the $O(\log V)$ lookup time. In practice, systems usually configure between 100 and 256 virtual nodes per physical server.

4. How does Rendezvous Hashing compare to Consistent Hashing?

Model Answer: Rendezvous hashing (Highest Random Weight) computes a hash for every node combined with the key: hash(key, node_id). The node with the highest hash value wins. It achieves the same minimal disruption as consistent hashing and naturally handles uneven load without needing virtual nodes. However, basic Rendezvous hashing requires $O(N)$ time to route a request, making it less suitable for systems with thousands of nodes compared to consistent hashing's $O(\log V)$ time.

5. Can consistent hashing be used for databases, or is it just for caches?

Model Answer: It is heavily used for databases (like database sharding in Cassandra). However, unlike caches where a missing key is just a cache miss, a database must guarantee data durability. Therefore, when the ring topology changes, the database must orchestrate a physical data migration process before the new node can start serving reads for its assigned token ranges.

Common Mistakes

  • Confusing Consistent Hashing with CAP Theorem Consistency: They share a word but are completely unrelated. Consistent hashing is a partitioning algorithm. CAP theorem consistency refers to all nodes seeing the same data at the same time.
  • Forgetting the Physical Node Mapping: Candidates often explain virtual nodes but forget to mention that the routing layer must maintain a map resolving virtual nodes back to physical IP addresses.
  • Assuming the Ring is Stored Centrally: In highly distributed systems, there is no "central ring." Every client or router maintains its own copy of the ring. Changes to cluster membership are gossiped (via protocols like ZooKeeper or Gossip) and clients eventually update their local rings.

Mock interview

Can you explain it when someone pushes back?

Interviewers rarely ask for a definition. They ask why you'd pick this over that, and what breaks at ten times the load. A mock round finds those gaps before the real one does.

  • A question on your own project, then a design problem
  • The interviewer probes the parts you skim over
  • A scored report that quotes your answers and says what to fix
Start a mock design round Voice or text. Pause whenever you need to.

Applying somewhere? Start with the company filled in

Go deeper elsewhere

The best material we've found on these topics.

Practise this

Reading builds understanding. Practice makes it stick.

Keep reading

All articles
System design•beginner

Scaling a web app from one server to millions

11 min read
System design•beginner

Load balancing: algorithms, layers and health checks

10 min read
System design•intermediate

CAP theorem and consistency models

10 min read
System design•intermediate

Caching strategies and cache invalidation

12 min read