Skip to content
Visual explainer 3h to learn 4 steps

Partitioning, sharding & consistent hashing

Pick a shard key, avoid hot spots and rebalance with consistent hashing.

By Invicly Tech, , in System Design Deep Dive. About 12 minutes to read.

Topic 13 of 33

In short

Partitioning, or sharding, splits data across nodes so each holds only part of it. A good shard key spreads load evenly, and consistent hashing lets you add nodes while moving only a small slice of data.

Think of it like this: Splitting a phone book into volumes so several people can search at once.

Explained simply

When data grows too big for one machine, or one machine cannot keep up with the writes, you split it into pieces. Each piece is called a partition or shard, and each lives on a different machine. Together they hold everything, but each machine only handles its own part.

The key question is how to decide which row goes where. You pick a field called the shard key, like user ID, and use a rule to map it to a shard. A good rule spreads the data and the traffic evenly. A bad one sends most of the work to one unlucky machine, called a hot spot.

There are two common rules. Range partitioning gives each shard a range of keys, like names A to F, which keeps nearby keys together. Hash partitioning runs the key through a hash function, which scrambles it into a number, and uses that number to pick the shard. That spreads keys evenly but scatters nearby keys.

Data keeps growing, so you will add machines later. Moving data around is slow and risky, so good designs make it cheap: consistent hashing, a fixed number of small partitions, or automatic splitting of big ones. You also need a way for every request to find the right shard.

Press Play on a diagram to walk through it one step at a time.

CompareRange vs hash partitioning
Range
  • Keys split into ordered ranges
  • Efficient range scans
  • Risk of hot spots
  • Example: by date or name
Hash
  • hash(key) picks the shard
  • Even distribution
  • Range queries hit all shards
  • Example: by user ID
SequenceConsistent hashing lookup
Client
Router
Hash ring
Node B
  1. 1GET key user:42
    Client to Router: GET key user:42
  2. 2hash(user:42) gives ring position
    Router to Hash ring: hash(user:42) gives ring position
  3. 3Next node clockwise is Node B
    Hash ring to Router: Next node clockwise is Node B
  4. 4Forward read to Node B
    Router to Node B: Forward read to Node B
  5. 5Return value
    Node B to Client: Return value
LayersAnatomy of a sharded database
  1. 1
    Application

    Sends queries with the shard key

  2. 2
    Router or smart client

    Looks up which shard owns the key

  3. 3
    Shard map

    Kept in etcd, ZooKeeper or config servers

  4. 4
    Shards

    Each holds one slice of the data

  5. 5
    Replicas per shard

    Copies for failover and reads

In depth

Range partitioning in practice

With range partitioning each shard owns a continuous slice of the sorted keys. HBase and Google Bigtable call these slices regions or tablets, and they split a slice in two automatically when it grows too big. Because keys stay sorted, a query like all orders from 1 to 7 March, or all keys starting with user42:, reads one or two shards instead of all of them.

The danger is sequential keys. If the key is a timestamp or an auto-increment ID, every new write lands at the end of the range, on one shard, while the others sit idle. The usual fix is a compound key that puts a well-spread field first, such as sensor_id then timestamp. Writes then spread across sensors, and one sensor's history is still a cheap range scan.

  • Good for range scans and ordered reads
  • Splits automatically as ranges grow (HBase, Bigtable)
  • Never lead the key with a timestamp

Choosing a shard key

A good shard key has three properties. High cardinality: many distinct values, so data can be spread across many shards (country has maybe 200 values; user ID has millions). Even frequency: no single value owns a large share of rows or traffic. Query alignment: your most common queries include the key, so each one goes to a single shard.

The third property is the one people forget. If you shard orders by order_id but the main screen is a customer's order history, every page view must ask all shards and merge results, which is called scatter-gather. Sharding by customer_id keeps one customer's orders together.

Multi-tenant SaaS apps usually shard by tenant_id for this reason, and move very large tenants to their own dedicated shards.

Hot spots and how to cool them

Even a well-spread key can have one very hot value: a celebrity's post, a viral product, a huge customer. That value lives on one shard, so that shard overloads while others are quiet.

For read-heavy hot keys, caching is the first answer: put the value in a cache, replicate it to several cache nodes, or keep a small in-memory copy on each app server for a few seconds. For write-heavy hot keys, split the key itself. Instead of writing to likes:post9, write to likes:post9:0 through likes:post9:9, chosen at random. Ten shards now share the writes. To read the total, read all ten and add them up.

This trade, called key salting or write sharding, makes reads ten times more expensive, so only apply it to keys you know are hot. Detect them with per-key metrics, not guesses.

FlowSplitting one hot counter across shards
  1. 1
    Like arrives

    For post 9

  2. 2
    Add random suffix

    likes:post9:0 to :9

  3. 3
    Write lands on 1 of 10 keys

    Spread over several shards

  4. 4
    Reader fetches all 10

    One batched request

  5. 5
    Sum and cache

    Total served for a few seconds

Three ways to rebalance

When you add a machine, some data must move to it. Plain hash mod N moves almost everything, so real systems use one of three approaches.

Fixed number of partitions: create many more partitions than machines up front, and move whole partitions when machines join. Redis Cluster uses 16,384 hash slots (slot = CRC16(key) mod 16384) and moves slots between nodes. Elasticsearch fixes the number of primary shards when an index is created.

Dynamic splitting: start with few partitions and split any that grow too large, then move halves to other machines. HBase and Bigtable work this way.

Consistent hashing with virtual nodes: each machine takes many positions on a hash ring, so a new machine takes small slices from all the others. Cassandra and DynamoDB-style systems use this; Cassandra 4.0 and later default to 16 tokens per node.

CompareRebalancing strategies
Fixed partitions
  • Many slots created up front
  • Move whole slots to new nodes
  • Simple mapping table
  • Redis Cluster, Elasticsearch
Dynamic splitting
  • Split partitions that grow
  • Adapts to data size
  • Starts on few nodes
  • HBase, Bigtable
Consistent hashing
  • Nodes take many ring positions
  • New node takes small slices
  • No central size tracking
  • Cassandra, Dynamo-style

Routing requests and cross-shard queries

Every request must find the shard holding its key. There are three common designs. A routing tier: clients talk to a proxy that knows the shard map, like mongos in MongoDB or Vitess's vtgate for MySQL. Smart clients: the client library caches the map and talks to the right node directly, as Redis Cluster clients do, following a MOVED reply when slots change. Any-node: the client talks to any node, which forwards the request, as in Cassandra, where nodes learn the ring through gossip.

The shard map itself usually lives in a small, strongly consistent store such as ZooKeeper or etcd.

Queries without the shard key must ask every shard. Secondary indexes make this sharper: a local index lives on each shard (cheap writes, scatter-gather reads), while a global index is partitioned by the indexed field (one-shard reads, but every write may touch another shard).

Learn it in 4 short steps

About 45m each. Track them with a timer in your plan.

  1. 1
    Compare range and hash partitioning~45m
  2. 2
    Pick a good shard key~45m
  3. 3
    Avoid hot spots~45m
  4. 4
    Rebalance with consistent hashing~45m

Key points

  • Choose a shard key with high cardinality that matches your main query.
  • Plain hash mod N reshuffles almost all keys when N changes.
  • Consistent hashing moves only about 1/N of keys when a node joins.
  • Virtual nodes smooth out uneven load across physical servers.
  • Hot keys may need splitting or extra caching.

Key terms

Tap a card to flip it. 0/5 known

Examples

text
Naive: shard = hash(key) % N
  N goes 4 -> 5: about 80% of keys move

Consistent hashing:
  nodes placed at hash(nodeId) on ring [0, 2^32)
  key goes to first node clockwise from hash(key)
  add node E: only keys between D and E move
  -> about 1/5 of keys move

Why consistent hashing makes rebalancing cheap.

Keeping related keys together in Redis Cluster

You store a user's cart and profile as two keys and want to update both in one MULTI transaction. Redis Cluster only allows multi-key commands when all keys are in the same hash slot. Step 1: check the slots; different keys usually land in different slots. Step 2: wrap the shared part in braces, called a hash tag. Redis then hashes only the text inside the braces, so both keys share a slot. Step 3: use this sparingly, because putting too much under one tag creates a hot slot.

bash
redis-cli -c CLUSTER KEYSLOT cart:42
redis-cli -c CLUSTER KEYSLOT profile:42
# usually two different slots

redis-cli -c CLUSTER KEYSLOT {user:42}:cart
redis-cli -c CLUSTER KEYSLOT {user:42}:profile
# same slot: only 'user:42' is hashed

Sharding a multi-tenant SaaS database

A project tool has 20,000 customer companies and almost every query filters by company. Step 1: choose tenant_id as the shard key, so each query hits one shard and a tenant's data can be joined locally. Step 2: hash tenant_id into 1,024 logical partitions and map them onto 8 database servers, 128 each. Step 3: when growing to 16 servers, move 64 partitions from each old server to a new one; no row needs re-hashing. Step 4: the three largest tenants, which make up 15% of traffic, get their own dedicated servers so they cannot overload neighbours.

Quick reference

  • Good shard key: high cardinality, even traffic, and present in your main query
  • Range partitioning: fast range scans, but sequential keys create one hot shard
  • Hash partitioning: even spread, but range queries must ask every shard
  • Redis Cluster: 16,384 slots, slot = CRC16(key) mod 16384; {tag} keeps keys together
  • Create many more logical partitions than servers, then move partitions, not rows
  • Hot write key: add a random suffix (key:0..9) and sum on read
  • Local secondary index: cheap writes, scatter-gather reads; global index: the reverse

Common mistakes

  • Sharding by timestamp so all new writes land on one shard.
  • Picking a low-cardinality key like country.
  • Needing cross-shard joins for the most common query.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Orders are sharded by order_id, but the busiest page lists one customer's orders. What happens?

Question 2

2Why is a timestamp a poor leading shard key for range partitioning?

Question 3

3How many hash slots does Redis Cluster use?

Question 4

4A like counter for one viral post overloads its shard with writes. What is a standard fix?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Rate each shard key for a ride app's trips table (good or bad, and why): (a) city, (b) trip_id, (c) rider_id, (d) created_at.

  2. Exercise 2medium

    An IoT table stores readings(device_id, ts, value) with 50,000 writes per second. The main query is: readings for one device over the last 24 hours. Choose a partitioning scheme and key.

  3. Exercise 3hard

    Implement a consistent hash ring with virtual nodes in Python. Show that adding a fourth node moves roughly a quarter of 10,000 keys.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

What is the difference between partitioning and sharding?
They mean the same thing: splitting data into pieces held by different machines. Sharding is the common word for databases; partitioning is used more generally, and PostgreSQL also uses it for splitting one table on a single server.
When should I start sharding?
As late as you reasonably can. Try indexes, caching, read replicas and a bigger server first, since sharding makes joins, transactions and operations harder. Shard when writes or data size truly outgrow one primary.
Can I change the shard key later?
Usually only by copying all data into a new layout, which is slow and risky. Some systems help (MongoDB can reshard a collection online since version 5.0), but it is still expensive, so choose carefully at the start.

Go deeper

ShareXLinkedInWhatsApp