Book a 30-min callBook a call

Sharding and consistent hashing: how data is split across many servers

When to shard, how to pick a shard key, and how consistent hashing, virtual nodes, rendezvous and jump hash keep keys in place when servers are added.

A ring with five server dots and small key squares around its edge, an arrow to the next server, beside a database cylinder split into four colored parts.
Written by
BYD Tech
Published
Topic
Deep dives
Reading time
13 min read

Questions people ask

When should I shard a database?

When one primary can no longer handle the write rate or hold the data, after indexing, a larger machine, read replicas, caching and in-database partitioning have run out. Sharding adds lasting complexity to queries, transactions and operations, so it should solve a problem you have measured.

What makes a good shard key?

High cardinality, an even spread of rows and traffic, and the property that most queries and transactions name a single key value. In multi-tenant software that is usually the tenant id. Avoid timestamps and auto-increment ids as range keys, since every new write lands on the last shard.

Is consistent hashing the same as sharding?

No. Sharding is the decision to split data across servers by a key. Consistent hashing is one way to map keys to servers so that adding or removing a server moves only a small share of the keys. Range sharding and directory-based sharding do not use it at all.

How many virtual nodes should a server have?

Enough for even balance, few enough to keep metadata and repair work small. In the test above, with 10 nodes, 100 points per node put the busiest node at 1.18 times the mean and 1,000 at 1.05. Cassandra moved from 256 random tokens per node to a token allocator that balances well with fewer.

Does PostgreSQL partitioning spread data across servers?

Not by itself. Declarative partitioning splits a table into partitions inside one PostgreSQL server, which helps with big tables and data retention. Partitions can be foreign tables on other servers, with care, and extensions such as Citus distribute tables across nodes.

Building something like this?