Module 5 · Distributed systemsLesson 59 of 887 minAdvanced

Data partitioning and rebalancing

Distributed databases split data into partitions spread over nodes, and move them as nodes come and go, ideally moving as little as possible.

Try it

With "Hash ring", add and remove nodes and count the keys that move. Switch to "hash mod N" and compare. Turn on the hot key to see why even spreads aren't enough.

Distributed databases like Cassandra, DynamoDB, Kafka and Elasticsearch store more data than one machine can hold. They split it into partitions (also called shards, vnodes, or tablets) spread across nodes.

Partitioning + replication

These go together:

  • Partitioning decides which node owns each piece, so load and data are spread.
  • Replication keeps copies of each partition on several nodes, so a node failure loses nothing.

A typical cluster: data split into many partitions, each replicated 3 times across different nodes and zones.

Choosing where keys go

  • Hash partitioning spreads keys evenly; range queries must hit every partition.
  • Range partitioning keeps nearby keys together (good for scans by time or name) but risks hot spots.
  • Compound keys: Cassandra uses a partition key (where) plus a clustering key (sort order within the partition), for example partition by user_id, sort by timestamp.

Rebalancing

Nodes join (scaling up) and leave (failures, scaling down). Data must move, while the system keeps serving. Approaches:

  • Hash mod N: avoid it. Changing N moves almost everything.
  • Consistent hashing with virtual nodes: each node owns many small slices of the ring. A new node takes a few slices from many nodes.
  • Fixed number of partitions: create many more partitions than nodes (say 1,000 for 10 nodes). Adding a node just moves some whole partitions to it. Used by Elasticsearch, Kafka and Riak.
  • Dynamic splitting: partitions split when they grow too big (HBase, Bigtable, CockroachDB).

Hot spots still happen

Even perfect hashing can't spread one extremely hot key. Watch per-partition load, and use the hot-key techniques from the caching module: split keys, add a random suffix for writes, or cache reads.

Quick check

Why do consistent hashing systems give each node many virtual nodes on the ring?