Sharding & Replication

Lab
Easy
Medium
Hard

Range shardingEasy

Each shard owns a slice of the key space.

How are rows assigned to shards?

Cluster and data

Number of shards
Key distribution
1 / 18
Routing
Route key 597. 597 ÷ 250 → range 500–749. Row stored on shard 2.

Shards (4)

routing key 597
Shard 00
Shard 10
Shard 21
597
Shard 30
Load per shard
Shard 0
0
Shard 1
0
Shard 2
1
Shard 3
0
✓ Range sharding
  • Range queries stay on few shards, but new/hot key ranges overload one shard.
  • Easy to reason about and to split a busy range in two.

Learn the theory

Sharding & Replication: how it works

4 min read · Updated

One database server eventually runs out of disk, memory, CPU or write throughput. There are two classic ways out: replication (keep full copies of the data on several servers to scale reads and survive failures) and sharding (split the data so each server holds only a slice, scaling writes and storage). They solve different problems, cost different things, and are almost always used together.

In short

  • Replication copies the same data to many servers: scales reads, adds failover, but not writes or storage.
  • Sharding splits data across servers by a shard key: scales writes and storage, but queries without the key must hit all shards.
  • Range sharding keeps ranges together but creates hot shards; hash sharding spreads load but kills range queries.
  • hash(key) mod N remaps almost everything when N changes; consistent hashing moves only about 1/N of the keys.
  • Asynchronous replication has lag, so reads from replicas can be stale.

Scaling up vs scaling out

Vertical scaling (a bigger server) is simple and should come first, but it has a ceiling and a price curve that bends sharply. Horizontal scaling spreads the load over many commodity servers — which requires deciding where each piece of data lives.

TechniqueData on each nodeScalesMain cost
ReplicationEverything (a full copy)Reads, availabilityLag and consistency questions
ShardingA slice of the dataWrites, storageComplex queries, resharding, operations

Sharding strategies

StrategyHow the shard is chosenGood atWeakness
RangeKey ranges per shard (ids 0–249 → shard 0…)Range queries; easy to split a rangeSequential keys pile onto the last shard (hot shard)
Hashhash(key) mod NEven spread, no hotspotsRange queries hit every shard; changing N remaps almost all keys
Consistent hashingKeys and shards are placed on a ring; a key belongs to the next shard clockwiseAdding/removing a shard moves ~1/N keysMore complex; needs virtual nodes for balance
Directory (lookup)A table maps each key (or tenant) to a shardTotal flexibility, easy rebalancing of single tenantsThe lookup service is a bottleneck and single point of failure

Choosing a shard key

The shard key decides everything. A good key has high cardinality, spreads writes evenly, and appears in most queries so each request touches one shard. Common choices are a user id or tenant id. A bad key (a country, a status, a timestamp) creates hotspots or forces scatter-gather queries.

What gets harder

  • Queries without the shard key become scatter-gather: sent to all shards and merged, as slow as the slowest shard.
  • Cross-shard JOINs and transactions need distributed coordination (two-phase commit, sagas) or must be avoided by design.
  • Global uniqueness and ordering (auto-increment ids) need a different scheme, like UUIDs or Snowflake-style ids.
  • Resharding — adding shards — means migrating data live. With hash mod N almost every row moves.

Replication and lag

In primary–replica replication, every write goes to the primary, which streams its log to replicas. With asynchronous replication the primary doesn't wait, so replicas lag by milliseconds to seconds and a read right after a write may return old data (a stale read). Synchronous replication waits for replicas but makes writes slower and less available.

  • Read-your-writes: after a user writes, serve their reads from the primary for a short while.
  • Monotonic reads: pin a user's session to one replica so time doesn't appear to go backwards.
  • Failover: if the primary dies, promote a replica — and risk losing the writes it hadn't received yet.

Using both

Large systems shard for write capacity and storage, then replicate each shard for read scaling and failover. Before any of that, make sure you've exhausted cheaper options: better indexes, caching, query fixes, a bigger server, and read replicas.

Frequently asked questions

What is database sharding?
Splitting a large dataset into smaller parts (shards), each stored on a separate database server, usually by a shard key such as user id. It scales writes and storage beyond a single machine.
What is the difference between sharding and replication?
Replication stores copies of the same data on multiple servers to scale reads and improve availability. Sharding stores different parts of the data on different servers to scale writes and storage.
What is the difference between range and hash sharding?
Range sharding assigns contiguous key ranges to shards, which keeps range queries local but can create hot shards. Hash sharding spreads keys by hashing, which balances load but makes range queries touch every shard.
What is consistent hashing?
A scheme that places shards and keys on a hash ring so that adding or removing a shard only remaps the keys adjacent to it (about 1/N of them), instead of remapping nearly all keys like hash mod N.
What is replication lag?
The delay between a write being committed on the primary and being applied on a replica. Reads from a replica during that window can return stale data.
When should I shard my database?
Only after cheaper options are exhausted: indexing, query tuning, caching, read replicas and vertical scaling. Sharding adds significant operational and application complexity.

Keep exploring

More interactive labs

All labs

What Happens When 100 Reads Hit the Database

Connection pools, CPU workers, caches and replicas, as 100 requests arrive at once.

Databases12 min · Intermediate

Redis Caching: Cache-Aside, TTL & Eviction

Hit or miss? Watch LRU, LFU, TTLs and a cache stampede decide your database load.

Redis12 min · Intermediate

JS Event Loop Visualizer

See the call stack, microtasks and timers run, frame by frame.

JavaScript10 min · Intermediate

CORS & Preflight Simulator

Edit the request and the server headers, then see exactly why the browser blocks it.

Networking12 min · Intermediate

HTTP Caching Explained

Cache-Control, ETag and 304s, one request at a time.

Networking12 min · Intermediate

What Happens When You Type a URL

DNS, TCP, TLS and HTTP — with a stopwatch.

Networking10 min · Beginner

How Database Indexes Work (B-Tree)

See a B-tree lookup beat a full table scan, and why some queries ignore your index.

Databases12 min · Intermediate

SQL Isolation Levels Lab

Run two transactions side by side and watch dirty reads, phantoms and write skew appear.

Databases15 min · Advanced

Redis Commands & Data Structures

Strings, lists, hashes, sets and sorted sets, one command at a time.

Redis15 min · Beginner

Webhooks: Delivery, Retries & Signatures

Why you get duplicate deliveries, lost events and forged requests — and how to stop them.

Queues & Jobs12 min · Intermediate

Cron Jobs: Schedules, Overlaps & Missed Runs

Write a cron expression and watch what really happens when jobs overlap or the scheduler is down.

Queues & Jobs10 min · Beginner

Job Queues with BullMQ (Redis)

Watch jobs move through waiting, active, delayed, completed and failed — and see what BullMQ stores in Redis.

Queues & Jobs14 min · Intermediate

RabbitMQ: Exchanges, Queues, Acks & Dead Letters

Direct, topic and fanout routing, competing consumers, prefetch, redelivery and dead-letter queues, drawn.

Queues & Jobs14 min · Intermediate

Git Commands, HEAD & Refs (Visual)

Every core git command drawn with arrows: three areas, commits, branches, HEAD and remotes.

Git15 min · Beginner

Git Merge vs Rebase

Watch the commit graph change under merge, rebase and squash.

Git10 min · Beginner