Databases & Storage
Database Sharding Explained: When to Split Your Data and How
By NileVPS Team · Published · 5 min read
اقرأ المقال بالعربيSharding means splitting one logical database into several independent databases, called shards, each holding part of the data. Instead of one server storing every customer, server A might store customers 1 to 1,000,000 and server B the rest. It is one of the few ways to scale writes and storage beyond what a single machine can handle, but it also adds lasting complexity to your application and operations. This article explains how sharding works, how to choose a shard key, what it costs you, and the simpler options that are usually worth trying first.
Sharding versus related ideas
These terms are often mixed up:
| Technique | What it does | Main benefit |
|---|---|---|
| Vertical scaling | Move to a bigger server | No code changes |
| Read replicas | Copies of the whole database that serve reads | Scales reads, adds redundancy |
| Partitioning | Splits a table into parts on the same server | Faster maintenance and pruning |
| Sharding | Splits data across separate servers | Scales writes and storage |
Replication copies all the data; sharding divides it. Many large systems use both: each shard has its own replicas. If replication is new to you, read our guide on data replication first.
How sharding works
Every sharded design answers one question: given a record, which shard holds it? The answer comes from a shard key, a column such as customer_id or tenant_id, and a rule that maps key values to shards.
Range-based sharding
Keys are split into ranges: IDs 1 to 999,999 go to shard 1, the next range to shard 2, and so on. It is easy to understand and makes range queries efficient. The risk is hotspots: if new IDs always increase, all new writes land on the last shard.
Hash-based sharding
The application hashes the key and uses the result to pick a shard, for example hash(customer_id) % 4. This spreads data evenly but makes range queries touch every shard. Plain modulo also has a painful flaw: changing the number of shards moves most of the keys. Consistent hashing, or a fixed large number of virtual buckets mapped to physical servers, reduces how much data must move.
Directory-based sharding
A lookup table records which shard owns each key or tenant. It is the most flexible, because you can move one large tenant to its own server, but the directory becomes a critical component that must be fast, cached and highly available.
Choosing a shard key
The shard key is the most important and hardest to change decision. A good key:
- Appears in most queries. If nearly every query filters by
tenant_id, each request goes to exactly one shard. - Spreads load evenly. Avoid keys where one value dominates, such as a country column when most users are in one country.
- Keeps related data together. A customer's orders, invoices and addresses should live on the same shard so they can be joined locally.
- Does not change. Moving a record because its key changed is expensive and error-prone.
For SaaS products, tenant_id (the customer organization) is often a natural fit. For consumer apps, user_id is common.
What sharding costs you
Sharding solves a capacity problem by creating several others:
- Cross-shard queries. Joins and aggregations across shards must be done in the application or by a coordinating layer, and they are slower.
- Transactions. A transaction that touches two shards needs distributed coordination or a redesign, such as sagas with compensating actions.
- Unique IDs. Auto-increment columns collide across shards. You need UUIDs, ULIDs or an ID scheme that encodes the shard.
- Rebalancing. Growth is rarely even. Moving data between shards while staying online needs careful tooling.
- Operations. Backups, migrations, monitoring and upgrades are multiplied by the number of shards. A schema change must succeed everywhere.
- Reporting. Analytics often need a separate pipeline that gathers data from all shards into one warehouse.
Try these before sharding
Most applications never need sharding. Work through this list first:
- Fix queries and indexes. Use
EXPLAIN ANALYZEin PostgreSQL orEXPLAINin MySQL to find full table scans. Missing indexes are the most common cause of database load. - Add memory. A working set that fits in RAM changes everything.
- Cache hot reads with Redis or application-level caching.
- Add read replicas and send reporting and read-heavy endpoints to them.
- Partition large tables on one server. PostgreSQL declarative partitioning, for example:
```sql CREATE TABLE events ( id bigint, created_at timestamptz NOT NULL, payload jsonb ) PARTITION BY RANGE (created_at);
CREATE TABLE events_2026_11 PARTITION OF events FOR VALUES FROM ('2026-11-01') TO ('2026-12-01'); ```
Old partitions can be detached or dropped quickly instead of running huge DELETE statements.
- Archive old data to cheaper storage.
- Scale up the server. A larger VPS is far simpler than a distributed database.
Only when writes or total data size truly exceed one well-tuned server does sharding become the right tool.
Tools that help
You do not have to build everything from scratch. Citus extends PostgreSQL with distributed tables. Vitess provides sharding for MySQL. Several databases, such as MongoDB and CockroachDB, include sharding or automatic data distribution natively. Each has its own trade-offs, so test with your real query patterns.
A practical path
Design for sharding early even if you never do it: include tenant_id in your main tables, avoid relying on global auto-increment IDs in public URLs, and keep cross-tenant queries out of hot paths. Then scale one server as far as it goes. On NileVPS you can start with a modest server and move to a larger plan as your database grows; see the options on the pricing page.
FAQ
At what size should I shard my database?
There is no fixed number. Shard when a single well-indexed, well-provisioned server cannot keep up with writes or cannot hold the data, and after caching, replicas and partitioning have been tried.
Is partitioning the same as sharding?
No. Partitioning splits a table into pieces on the same server. Sharding places pieces on different servers. Partitioning is much simpler and is often enough.
Can I undo sharding later?
It is possible but difficult, because the application, IDs and operations are built around it. That is why sharding should be a deliberate decision, not an early optimisation.