Home›Learn›Consistent hashing
Course · Spread the dataLesson 19 of 330 read

Consistent hashing at the database

When I add a server, how much data has to move?

The ring and hash mod N, animated and compared.

Press Play, or step with the arrows. Compare with hash mod N to see why the ring exists.

Once data is split across servers, every read and write has to know which server holds the key. The obvious answer, hash the key and take the remainder by the number of servers, works until you add a server.

How each engine places keys

Go deeper
EngineHowAdding a node
CassandraMurmur3 token ring; num_tokens ranges per node; replicas are the next nodes, per data centerStreams only the ranges the new node takes
Redis Cluster16,384 fixed hash slots: CRC16(key) mod 16384; each node owns a set of slotsMove slots one at a time; {hash tags} keep related keys in one slot
MongoDBRanged or hashed shard key, split into chunks; the balancer moves chunksThe balancer migrates chunks in the background
DynamoDBPartitions by hash of the partition key, managed for youSplit and moved automatically
Citus, VitessA distribution column hashed into a fixed number of shards placed on nodesMove whole shards

The common idea: never place data with mod of the server count. Either hash onto a ring, or hash into a large fixed number of slots or shards and move those. Then adding a server moves a share of the data, not almost all of it.

# Cassandra: which nodes own a key
nodetool getendpoints shop orders 42
# Redis Cluster: which slot a key is in
CLUSTER KEYSLOT user:42
CLUSTER KEYSLOT {user:42}:cart   # same slot, thanks to the hash tag
Connected

Where this shows up

The same mechanism, sharding and partitioning, hot keys and hot partitions, elsewhere on the site: in real incidents, in measurements, and in designs.

Check yourself · 3 questions

Check yourself

Pick an answer. You will see whether it is right, and why.

1. Going from 3 to 4 servers with hash mod N, about how much data moves?

2. With a token ring and four equal nodes, adding the fourth moves about:

3. How does Redis Cluster place a key?

Part 1 of 4 · Learn · 23 pagesAll pages

How do databases actually work? From one row on disk to transactions: the words you need, PostgreSQL, MySQL and MongoDB from the files up, then Redis, Cassandra and vector search, side by side, and the query and concurrency traps.