SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
  • Scalability
  • Availability
  • Reliability
  • Single Point of Failure (SPOF)
  • Latency vs Throughput vs Bandwidth
  • Consistent Hashing
  • CAP Theorem
  • Fault Tolerance and Redundancy
  • Failover
  • Stateless vs Stateful
  • Concurrency vs Parallelism
  • Capacity Planning
  • Back Pressure
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Foundations/Core Concepts

Consistent Hashing

Spread data over servers so adding or removing a server moves very little data.

⏱ 15 min readIntermediateInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

Consistent hashing is a way to decide which server stores which data, so that when we add or remove a server, only a small part of the data moves.

  • The simple way, hash(key) % N, breaks badly when N changes. Almost every key moves.
  • Consistent hashing puts servers and keys on a circle (a ring). A key belongs to the next server clockwise.
  • Adding or removing one server moves only about 1/N of the keys.

02Concept: What is it?

We have many servers (for example, many cache servers or database shards). For each key (like a user id) we must pick one server. We need a rule that every machine can compute the same way, without asking a central place.

The simple way and its problem

Pick the server with server = hash(key) % N. With N = 3 servers this works. But if one server dies and N becomes 2, the answer changes for almost every key. All cached data is suddenly in the wrong place. Every request misses the cache and hits the database. This can crash it.

hash % N: what happens when N changes
Before: N = 3
key 77 % 3 = 1
→↓
Server 1
↓add a server
After: N = 4
key 77 % 4 = 3
→↓
Server 3
Old owner New owner (data moved!)
Going from 3 to 4 servers moves most keys. That is a lot of wasted work.

The fix: a hash ring

  1. Imagine a circle with positions from 0 to 2³² − 1. Position 0 is joined to the end of the circle.
  2. Hash each server (for example, its name) to put it on the ring.
  3. Hash each key to put it on the ring too.
  4. Walk clockwise from the key. The first server you meet is the owner.
🧠Why it works
A server only owns the arc between itself and the previous server. If it leaves, only that arc moves to the next server. All other keys stay where they are.

03Real-Life Example

🍵Houses on a circular road
Houses stand on a round road, each with a number. Post offices are built at some places on the road. Every house uses the next post office clockwise. If one post office closes, only the houses that used it go to the next one. Everyone else keeps going to their old post office.
Post offices on a ring
Before
🏠h1
🏤Office A
🏠h2
🏤Office B
🏠h3
🏤Office C
↓B closes
After
🏠h1
🏤Office A
🏠h2moved to C
🏠h3
🏤Office C
Closing office B only affects the houses between A and B. They now go to C.
Round road
Software system
The round road
The hash ring
A house
A key (user id, cache key)
A post office
A server (cache or database node)
Use the next office clockwise
Owner = next server clockwise
Closing or opening an office
Removing or adding a server

04Why Do We Need It?

📦Move less data
Only about 1/N of keys move when the server count changes.
⚡Keep caches warm
Most cached items stay where they were, so the database is safe.
📈Easy scaling
Add a server at peak time without a big reshuffle.
🩹Survive failures
When a server dies, only its keys move to its neighbour.
🧭No central lookup
Any machine can compute the owner by itself.
⚖️Even load
With virtual nodes, keys spread fairly across servers.
Consistent hashing lets a system grow and shrink without a painful reshuffle of data.

05Where Do We Use It?

⚡Distributed caches
Many cache servers (for example, memcached clients) decide where a key lives.
🗄️Distributed databases
Systems like Cassandra and DynamoDB place data on a ring of nodes.
⚖️Load balancers
Send the same client or URL to the same server (sticky routing).
🌍CDNs
Map each file to the cache server that holds it.
💬Chat and gaming
Keep one user's connection or room on the same server.
📦Object storage
Spread files across many storage nodes.
📝Note
Many well-known systems use ideas from consistent hashing. The exact details differ in each product.

06Types / Parts / How It Works

How it works, step by step

The hash ring
🔑Key 4
→↓clockwise
🖥️Server Apos 20
🔑Key 1, 2
→↓clockwise
🖥️Server Bpos 130
🔑Key 3
→↓clockwise
🖥️Server Cpos 250
Keys 1 and 2 go clockwise to Server B. Key 3 goes to Server C. Key 4 wraps around the end to Server A.

Adding and removing a server

Add a server
  • The new server lands on the ring
  • It takes over part of its clockwise neighbour's arc
  • Only those keys move to it
Remove a server
  • The server leaves the ring
  • Its keys go to the next server clockwise
  • All other keys stay where they are

The uneven load problem and virtual nodes

With only a few servers, the random positions may be uneven. One server can get a huge arc, and others a tiny arc. The fix is virtual nodes: each real server is placed on the ring many times (for example, 100 times) with different labels, like S1#0, S1#1, and so on. The arcs become small and well mixed, so the load evens out. A bigger server can get more virtual nodes.

Virtual nodes
S1#0
S2#1
S3#2
S1#3
S3#4
S2#5
S1#6
S2#7
S3#8
Server 1 Server 2 Server 3
Each real server appears at many spots on the ring. When one leaves, its keys spread to many different servers, not just one.

Compare the two ways

Pointhash % NConsistent hashing
Keys moved when a server is addedAlmost allAbout 1/N
Easy to understandVery easyA bit harder
Lookup costInstantSearch the ring (fast, O(log n))
Even loadYes, if the hash is goodNeeds virtual nodes
Good forA fixed number of serversServers that come and go
VisualizerHash ringAdd or remove servers. Compare keys moved with the simple hash % N way.
Servers (click to add or remove)
Virtual nodes per server
hash ring0°S1S3S2key-1 → S3key-2 → S2key-3 → S3key-4 → S2key-5 → S1key-6 → S2key-7 → S1key-8 → S2key-9 → S1key-10 → S3key-11 → S3key-12 → S2key-13 → S1key-14 → S2key-15 → S1key-16 → S3key-17 → S1key-18 → S2key-19 → S2key-20 → S1key-21 → S1key-22 → S3key-23 → S1key-24 → S1key-25 → S1key-26 → S2key-27 → S2key-28 → S1key-29 → S1key-30 → S1key-31 → S1key-32 → S2key-33 → S2key-34 → S2key-35 → S1key-36 → S2key-37 → S2key-38 → S1key-39 → S1key-40 → S1

Each dot is a key, drawn in the colour of the server that owns it (the first server clockwise). A white ring means the key just moved.

Server S119 keys
Server S215 keys
Server S36 keys
Keys moved: consistent hashing
—
Keys moved: hash % N
—
Add or remove a server and watch how few keys move. Every key walks clockwise to the next server.

07How to Use It / Steps / Implementation

Build it in your head

  1. 1
    Choose a hash function
    Use one that spreads values evenly (such as MurmurHash or SHA-1).
  2. 2
    Place each server on the ring
    Hash its name or address. Add many virtual nodes per server.
  3. 3
    Keep the positions sorted
    Use a sorted list or a balanced tree.
  4. 4
    To find a key's owner
    Hash the key, then search for the first position that is equal or larger. If none, wrap to the first position.
  5. 5
    When the server list changes
    Add or remove its positions. Move only the affected keys.
  6. 6
    Add copies for safety
    Store each key on the next 2 or 3 servers clockwise too (replication).

Small code idea

Pseudo-code
ring = sorted list of (position, server)

def owner(key):
    p = hash(key)
    for (pos, server) in ring:      # in real code: binary search
        if pos >= p:
            return server
    return ring[0].server           # wrap around the circle

08Key Terms to Know

TermMeaning in easy words
Hash functionA function that turns any key into a number. The same key always gives the same number.
Hash ringA circle of positions from 0 to the biggest hash value, where the end joins the start.
KeyThe thing we store or look up, like a user id.
Node / serverA machine that stores some keys.
ClockwiseThe direction we walk on the ring to find the owner.
Virtual node (vnode)One of many ring positions that belong to one real server.
RebalancingMoving keys between servers after the server list changes.
Hot spotA server that gets much more load than others.
Replication factorHow many servers keep a copy of each key.
ShardingSplitting data across many servers.

09Pros, Cons and Trade-offs

✅ Pros
  • Very little data moves when servers change
  • No central lookup table needed
  • Works well with growth and failures
  • Virtual nodes give even load and weighted servers
⚠️ Cons
  • More complex than hash % N
  • Needs virtual nodes to balance well
  • A very popular key can still overload one server
  • Extra memory for the ring

Trade-offs

ChoiceWe gainWe lose
More virtual nodesSmoother loadBigger ring, more to update
Fewer virtual nodesSmall and simple ringUneven load
More replicasSafer dataMore storage and write work
Consistent hashing vs a lookup tableNo central tableLess control over exact placement

10Common Problems and Mistakes

Common mistakes

  1. Using hash % N for servers that change. A cache reshuffle can crash the database.
  2. No virtual nodes. One server may get most keys.
  3. A weak hash function. Keys bunch up in one place on the ring.
  4. Forgetting to wrap around. A key past the last server must go to the first one.
  5. Ignoring hot keys. One celebrity user can overload one server, whatever the ring does.
  6. Clients with different server lists. If two clients see different rings, they pick different owners.
⚠️Even with a ring, data still moves
Consistent hashing moves less data. It does not move zero data. You still need to copy the affected keys safely to the new server.

11Real-World Examples

🗄️Cassandra and DynamoDB
Place data on a ring of nodes, using partitioning ideas based on consistent hashing.
⚡Cache clusters
Client libraries pick a cache server for each key with a ring.
🌍CDNs
Map each file to the edge cache that should hold it.
⚖️Load balancers
Hash the client or URL to keep it on the same backend.
📝Note
Each product has its own details (such as fixed token ranges or hash slots). The idea is the same: move as little data as possible.

12Related Topics to Read Next

Scalability→

Adding servers is easy only if data does not reshuffle.

What are Load Balancers?→

They can use hashing to route a client to the same server.

Load Balancing Algorithms→

IP hash and consistent hash are two routing choices.

CAP Theorem→

Replicas on a ring face the consistency vs availability choice.

Single Point of Failure (SPOF)→

A ring removes the central lookup SPOF.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔Problem: hash % N moves almost all keys when N changes.
  • ✔Idea: put servers and keys on a ring. Owner = next server clockwise.
  • ✔Result: only about 1/N of keys move on add or remove.
  • ✔Virtual nodes: many ring spots per server, for even load.
  • ✔Lookup: sorted list plus binary search, wrap around at the end.
  • ✔Replication: copy to the next few servers for safety.
  • ✔Used in: caches, Cassandra, DynamoDB, CDNs, load balancers.
  • ✔One line: "Consistent hashing spreads data over servers so that changing the servers moves very little data."
← Previous
Latency vs Throughput vs Bandwidth
Next →
CAP Theorem