SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
  • Indexing
  • Partitioning
  • Replication
  • Sharding
  • Query Optimization
  • Denormalization
  • Materialized Views
  • Connection Pooling
  • Replication Models
  • Replication Lag
  • Quorum (R + W > N)
  • Shard Keys, Hot Shards and Resharding
  • Cross-Shard Joins
  • Backups, RPO, RTO and Disaster Recovery
  • Point-in-Time Recovery
  • Data Archiving and TTL
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Data and Storage/Database Scaling

Sharding

Split the data across many databases, so no single one holds everything.

⏱ 16 min readAdvancedMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

Sharding means splitting one big dataset into smaller pieces, and putting each piece on its own database. Each piece is a shard. No single machine has to hold or serve everything.

  • A shard key (like user_id) decides which shard owns each row.
  • Sharding scales writes and storage. Replication only scales reads and safety.
  • It is powerful but costly: cross-shard queries, hot shards and moving data are hard. Try simpler fixes first.

02Concept: What is it?

One database server has limits: disk size, memory, and how many writes per second it can take. You can buy a bigger server (vertical scaling), but that gets very expensive and then stops. The other way is to use many servers and give each one a part of the data. This is horizontal scaling, and for databases it is called sharding.

One database becomes many shards
📱App
→↓user 42
🧭Routershard key to shard
→↓42 is on shard 2
🗄️Shard 1users 1 to 100
🗄️Shard 2users 101 to 200
🗄️Shard 3users 201 to 300
A router looks at the shard key and sends each request to the one shard that owns that row.

The router can be a library in your app, a separate proxy, or part of the database itself. The important thing is that every request carries the shard key, so it can go to one shard.

🧠Sharding vs replication vs partitioning
Replication copies the same data to many machines. Sharding splits different data across machines. Partitioning is the general word for splitting data (sharding is partitioning across separate servers). Real systems usually do both: each shard is replicated.

03Real-Life Example

🍵The Library with Many Buildings
A city has one huge library. Too many people come, the shelves are full, and the lift is always busy. So the city builds four libraries. Books A to F go to building 1, G to L to building 2, and so on. A reader who knows the author's name walks to exactly one building. But if someone asks "which are the 10 most borrowed books in the city?", a helper must visit all four buildings and add up the answers.
Library buildings
Sharding
One building per letter group
One shard per range of keys
The author's first letter
The shard key
The sign at the city gate
The router or directory
A reader goes to one building
A single-shard query (fast)
The helper visits every building
A scatter-gather query (slow)
Everyone wants the same new book
A hot key and a hot shard
Moving books to a new building
Resharding
Fast query vs scatter-gather
Has the shard key
🧭Router
↓1 shard
🗄️S1
🗄️S2
🗄️S3
No shard key
🧭Router
↓all shards, then merge
🗄️S1
🗄️S2
🗄️S3
With the shard key you ask one shard. Without it, you ask all of them and merge.

04Why Do We Need It?

✍️Scale writes
Each shard takes only a part of the writes. Replicas cannot do this.
💾Scale storage
The data no longer has to fit on one machine or one disk.
⚡Smaller, faster indexes
Each shard has a smaller table and smaller indexes, which fit in memory better.
🧱Isolate failures
If one shard is down, only its users are affected, not everyone.
🌍Data near users
Geo sharding keeps EU users on EU servers (speed and data-law rules).
💸Use cheaper machines
Many ordinary machines cost less than one giant one.
Shard when one database can no longer keep up with writes or size, and replicas, caching and indexes are not enough.

05Where Do We Use It?

👥Multi-tenant SaaS
Shard by customer (tenant) id. Each customer's data stays together.
💬Social and chat apps
Messages, posts and feeds by user id or conversation id.
🛒E-commerce
Orders by customer id. Products often live in a separate, read-heavy store.
📈Event and log storage
Huge append-only data, split by time or by device id.
🎮Gaming
Player data by player id, game worlds by world id.
🧰NoSQL by default
MongoDB, Cassandra and DynamoDB shard automatically. Many SQL systems (Vitess, Citus, CockroachDB) do too.

06Types / Parts / How It Works

Ways to decide which shard owns a row

StrategyHow it worksGood and bad
Range-basedEach shard owns a block of keys (ids 1 to 1M, 1M to 2M...).Range queries are fast. New data piles on the last shard, so it gets hot.
Hash-basedshard = hash(key) mod N. The hash spreads keys evenly.Even spread. Range queries hit every shard. Changing N moves almost everything.
Consistent hashingShards and keys sit on a ring. A key goes to the next shard clockwise.Adding a shard moves only about 1/N of the keys. Needs more design.
Directory-basedA lookup table says which shard has which key (or tenant).Most flexible. The lookup service must be fast, small and always up.
Geo-basedThe shard is chosen by the user's region.Low latency and legal control. Uneven sizes, only a few shards.
Range vs hash
Range
1 to 3S1
4 to 6S2
7 to 10S3, new users
Neighbours stay together. The newest shard is busiest.
Hash
1, 4, 8S1
2, 6, 9S2
3, 5, 7, 10S3
Spread out. A range query must ask every shard.
Same ten users, two layouts.

A good shard key

Good key
high cardinality, even, in your queries
  • Many different values (user id, tenant id)
  • Spreads data and traffic evenly
  • Appears in your most common queries
  • Does not change after the row is created
Bad key
low variety or skewed
  • Country, status or plan type (few values)
  • A timestamp (all new writes hit one shard)
  • A celebrity or a huge customer id
  • A value that you must update often
VisualizerPick a shard key, add shards, run queriesSwitch strategy, then set traffic to one celebrity user. Move the shard slider from 4 to 5 and watch how much data moves. Then run the no-shard-key query.
Sharding strategy (the shard key is the user id, or the region for geo)

shard = hash(user id) mod N. Spreads users evenly. But when N changes, almost every user gets a new shard.

Traffic pattern
Each column is a shard. Cyan = how many of the 200 users it stores. Amber = share of the traffic it must handle. A red outline means a hot shard.
S1
54u, 27%
S2
36u, 18%
S3
55u, 28%
S4
55u, 28%
Skew (busiest / fair)
1.10x
1.00x is perfect
Moved: 3 to 4 shards
71%
141 of 200 users change shard
Hot shard
S3
28% of traffic
Now run a query
Shards asked
1 of 4
single-shard query
Estimated latency
12 ms
10 ms parallel + 2 ms merge per shard
Which shards
S3
Well balanced: the busiest shard carries 1.10 times its fair share.

A simplified model with a fixed, deterministic data set (no random numbers). Users are numbered 1 to 200. Latency is a rough guide: the point is that a query without the shard key must visit every shard, and that adding a shard moves very different amounts of data depending on the method.

07How to Use It / Steps / Implementation

Sharding step by step

  1. 1
    Try simpler things first
    Add indexes, tune queries, add a cache, add read replicas, archive old data, upgrade the machine. Sharding comes last.
  2. 2
    Choose the shard key
    Look at your top queries and your hot data. Pick the field that appears in most of them and spreads evenly.
  3. 3
    Choose a strategy
    Hash or consistent hashing for even spread. Range if range queries matter. Directory if you need to move tenants freely.
  4. 4
    Add a router
    A library, a proxy (like Vitess) or the database itself maps the key to a shard.
  5. 5
    Design for single-shard work
    Keep data that is used together on the same shard. For example, all rows of one user.
  6. 6
    Plan for resharding
    Start with more logical shards than machines (say 256 logical shards on 8 machines). Moving a logical shard is then easier than re-splitting data.
  7. 7
    Replicate each shard
    Each shard needs its own followers and failover.
  8. 8
    Monitor skew
    Watch size, QPS and latency per shard. A hot shard needs action before it becomes an outage.
💡Handling cross-shard work
Avoid cross-shard transactions if you can. When you must, use a saga (a chain of local steps with undo steps) or a two-phase commit. For global queries like top-10, keep a separate summary table, or send data to a search or analytics store.
Skew goal: busiest shard vs averageclose to 1.0x, not 3x

08Key Terms to Know

TermMeaning in easy words
ShardOne piece of the data, stored on its own database
Shard keyThe field that decides which shard owns a row
Router / proxyThe part that sends a request to the right shard
Hot shard / hot keyA shard or key with much more traffic than the rest
CardinalityHow many different values a field can have
ReshardingMoving data when the number of shards changes
Scatter-gatherAsk every shard, then merge the answers
Consistent hashingA hashing method where adding a node moves little data
DirectoryA lookup table from key to shard
Cross-shard transactionA change that touches rows on more than one shard
SagaA sequence of local transactions, with undo steps if one fails

09Pros, Cons and Trade-offs

✅ Pros
  • Scales writes, storage and connections
  • Smaller indexes and faster queries per shard
  • A failure affects only part of the users
  • Can place data near users
  • Uses commodity machines
⚠️ Cons
  • Much more complexity everywhere
  • Cross-shard joins, transactions and queries are slow or hard
  • Hot shards and uneven data
  • Resharding is a big, risky job
  • Harder schema changes, backups and debugging
  • A bad shard key is very costly to change

Trade-offs

ChoiceWe gainWe lose
Hash shardingEven spreadRange queries touch all shards
Range shardingFast range queriesHot spots on the newest range
Directory shardingTotal flexibilityA new critical dependency
More shardsMore total capacity, smaller failuresMore machines, more scatter-gather cost
Fewer, bigger shardsSimpler operationsHarder to grow later
Shard by tenantEasy isolation and single-shard queriesOne huge tenant can be a hot shard

10Common Problems and Mistakes

Common mistakes

  1. Sharding too early. Many apps never need it. Indexes, caches and replicas go a long way.
  2. A low-cardinality key. Sharding by country or status gives a few huge shards.
  3. A timestamp as the shard key. All new writes go to the last shard.
  4. Plain hash mod N with no plan. Going from 4 to 5 shards moves about 80 percent of the data.
  5. Ignoring the query patterns. If most queries lack the shard key, every query becomes scatter-gather.
  6. Forgetting to replicate each shard. Now you have many single points of failure.

Things to watch

🔥Hot keys
One celebrity or one big customer overloads a shard. Split that key or give it its own shard.
🔗Joins across shards
Join in the app, copy small tables to every shard, or denormalize.
🆔Unique ids
Auto-increment no longer works across shards. Use UUIDs or Snowflake-style ids.
🚚Live resharding
Copy data, keep writes in sync, switch over, and clean up. Do it slowly and test it.

11Real-World Examples

📺YouTube and Vitess
Vitess was built to shard MySQL behind a proxy. Slack and others run on it too (general idea).
🍃MongoDB
Built-in sharded clusters with hashed or ranged shard keys and an automatic balancer.
🪐Cassandra and DynamoDB
Data is placed by a partition key using hashing. Hot partitions are a known issue.
🐘Citus (PostgreSQL)
Shards PostgreSQL tables by a distribution column, often the tenant id.
🪪Instagram
Famously sharded PostgreSQL by user id, with ids that embed the shard number (general idea).
🌐CockroachDB and Spanner
Automatically split data into ranges and move them between nodes.
📝Note
These are general ideas. Each system has its own tools and numbers.
Mini case: a SaaS app with 3 shards
🏢Tenants
→↓tenant id
🧭Router
→↓
Shard A
👑Leader
📋Follower
Shard B
👑Leader
📋Follower
Shard C
👑Leader
📋Follower
Shard A Shard B Shard C
The tenant id is the shard key. Each shard has a leader and a follower.

12Related Topics to Read Next

Partitioning→

The wider idea of splitting data. Sharding is partitioning across servers.

Replication→

Each shard is also replicated for safety.

Consistent Hashing→

The best way to add shards without moving everything.

Indexing→

Try this before you shard.

Denormalization→

Copy data to avoid cross-shard joins.

CAP Theorem→

Cross-shard transactions meet its trade-offs.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔What: split data across many databases using a shard key.
  • ✔Why: scale writes and storage beyond one machine.
  • ✔Key: high cardinality, even, in your queries, stable.
  • ✔Strategies: range, hash, consistent hash, directory, geo.
  • ✔Pain: hot shards, cross-shard queries and transactions, resharding.
  • ✔Fixes: consistent hashing, logical shards, sagas, denormalize, cache hot keys.
  • ✔Order: index, cache, replicate, upgrade, and only then shard.
  • ✔One line: “Sharding splits the data so no machine holds it all, and the shard key decides whether life is easy or painful.”
← Previous
Replication
Next →
Query Optimization