> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Consistent Hashing

> Explains consistent hashing as a scalable alternative to modulo sharding to minimize data movement when adding or removing database shards, using ring hashing and virtual nodes.

When your application grows beyond a single database machine, you need to split data across multiple shards. A common but fragile approach is modulo sharding.

* Compute `user_id % N` where `N` is the number of shards.
* The remainder determines the shard number.

Example with 4 shards (`N = 4`):

* Alan (user ID 10): `10 % 4 = 2` → shard 2
* John (user ID 13): `13 % 4 = 1` → shard 1

This rule is fast and deterministic, so you can route requests to shards using only the user ID.

However, when you change the number of shards (for example, adding capacity), almost every mapping can change because the divisor changed.

Example switching from 4 to 5 shards:

* Alan (user ID 10): `10 % 5 = 0` → now shard 0 (previously shard 2)
* John (user ID 13): `13 % 5 = 3` → now shard 3 (previously shard 1)

Because the modulo base changed, most data must be moved. Moving large volumes of photos or user records every time capacity changes is impractical.

```text theme={null}
// Simple illustration (pseudocode)
mapShard(user_id, N) {
  return user_id % N
}

// Change N -> major remapping
```

![A system-design diagram explaining database sharding: a single full database split into multiple colored shard databases with arrows showing data movement. It includes example user-to-shard mappings and remainder calculations (user id ÷ N) for sample users.](https://mintcdn.com/kodekloud-c4ac6d9a/IK4ISE2GFis3psR1/images/DevOps-Interview-Questions-and-Answers-Scenario-Based-Prep/Databases/Consistent-Hashing/database-sharding-user-modulo-mapping.jpg?fit=max\&auto=format\&n=IK4ISE2GFis3psR1\&q=85\&s=994ae5851d6e2929e22d600c51ff6ff3)

The industry solution to this problem is consistent hashing.

How consistent hashing solves the rebalancing problem:

* Place both shards (physical nodes) and keys (user IDs) on the same circular hash space (imagine a clock).
* Hash a key to a point on the circle. Walk clockwise until you find the first shard — that shard is responsible for the key.
* When a shard is added or removed, only the keys that map between the previous clockwise neighbor and the new shard need to move.

Example intuition: If four shards are at 12, 3, 6, and 9 o'clock and you hash each user ID onto the clock, a user whose hash lands at 2 o'clock will be assigned to the shard at 3 o'clock. If a new shard is added at 10:30, only users whose hashes fall between 9 o'clock and 10:30 will move to the new shard. All other users remain on their original shards.

Pseudocode for a typical consistent hashing lookup:

```text theme={null}
// Pseudocode for consistent hashing lookup
position = hash(key)                    // map key onto circle
node = ring.findFirstNodeAfter(position)
return node
```

To reduce load variance across shards, systems usually use multiple virtual nodes (multiple points per physical shard) on the circle. Virtual nodes smooth out distribution and make the ring more balanced.

![A dark-themed diagram explaining consistent hashing: a circular "clock" with labeled shards and a highlighted pink arc showing the range affected by adding a new shard. Text annotations read things like "Who moves?" and "Almost nobody moves."](https://mintcdn.com/kodekloud-c4ac6d9a/IK4ISE2GFis3psR1/images/DevOps-Interview-Questions-and-Answers-Scenario-Based-Prep/Databases/Consistent-Hashing/consistent-hashing-diagram-almost-nobody-moves.jpg?fit=max\&auto=format\&n=IK4ISE2GFis3psR1\&q=85\&s=f396440b165f1656792a434862dd2899)

Consistent hashing drastically reduces data movement during topology changes: adding one node moves only about `1/(N+1)` of the keys (those that fall into the new node's arc). For better uniformity, assign multiple virtual nodes per physical shard to reduce variance in load distribution.

Comparison: modulo sharding vs. consistent hashing

| Aspect | Modulo sharding (`user_id % N`) | Consistent hashing |
| - | - | - |
| Rebalancing cost when adding a node | High — most keys remap | Low — only keys in the new node's arc move |
| Deterministic routing | Yes (depends on `N`) | Yes (depends on ring and hash) |
| Ease of implementation | Very simple | Moderate (requires ring data structure) |
| Load variance | Can be uneven unless keys are well-distributed | Lower with virtual nodes |
| Typical use case | Small, fixed cluster sizes | Dynamic clusters, scalable distributed systems |

Further reading and references

* [Consistent hashing — Wikipedia](https://en.wikipedia.org/wiki/Consistent_hashing)
* [A thorough blog explanation of consistent hashing and virtual nodes](https://blog.serverfault.com/consistent-hashing) (search for up-to-date posts on consistent hashing and distributed hash tables)

> [card] [Watch Video](https://learn.kodekloud.com/user/courses/devops-interview-prep/module/1ee75c71-d566-42df-8cc2-7aa8e79b0f04/lesson/365f25e3-65a6-49c2-a125-24b6b5c5dbda)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.