Your restaurant is a hit. Every evening the queue goes round the block, and the kitchen can’t keep up. You have two choices:
- Get a bigger kitchen. More stoves, more chefs, same building.
- Open more branches. Several kitchens, each serving part of the city.
Databases face the same choice. One day the dashboard shows CPU at 100%, memory nearly full, disk I/O maxed out. The single server that ran everything has hit its ceiling.
Making the server bigger is vertical scaling (scaling up). Spreading the data across many servers is horizontal scaling (scaling out). This article opens the Partitioning, sharding & distribution thread, and it starts with the most important question: when to stop doing the first and start doing the second.
Scale up or scale out?
| Scale up (vertical) | Scale out (horizontal) | |
|---|---|---|
| How | Bigger CPU, more RAM, faster disks | More machines, each with part of the data |
| Limit | The biggest machine you can buy | Practically none |
| Cost curve | Rises steeply at the top end | Grows roughly in step with load |
| Transactions and joins | Work as before | Hard across machines |
| If it fails | Everything is down | Only part of the data is affected |
| Upgrades | Often need downtime | Add machines while running |
| Complexity | Low | High: routing, rebalancing, more to monitor |
Vertical scaling is underrated. A modern database server with dozens of cores, hundreds of gigabytes of RAM and fast NVMe disks handles far more than most products ever need. It keeps ACID transactions, joins and simple operations. Its problems are real but arrive late: a hard ceiling, steep prices at the top end, and one machine whose failure takes everything with it.
Horizontal scaling removes the ceiling and the single point of failure, and you pay for it with complexity that never goes away.
Partitioning vs sharding
These two words get mixed up all the time. The difference is where the pieces live.
- Partitioning splits one big table into smaller pieces inside the same database. PostgreSQL can split
ordersby month: a query for March only touches the March partition, and dropping last year’s data is instant. It makes big tables faster to query and easier to manage, but the server’s limits don’t change. - Sharding spreads data across separate database servers, each called a shard. Each shard has the same tables but different rows. This is what raises the ceiling: four shards give roughly four times the storage and write capacity.
-- Partitioning: one PostgreSQL server, one logical table, split by month
CREATE TABLE orders (
order_id BIGINT,
user_id BIGINT,
created_at TIMESTAMP NOT NULL
) PARTITION BY RANGE (created_at);
CREATE TABLE orders_2026_03 PARTITION OF orders
FOR VALUES FROM ('2026-03-01') TO ('2026-04-01');
Every shard can still be partitioned inside. Many systems use both.
The usual path: don’t shard first
Most systems grow through the same steps. Each step is far simpler than the next, so climb only when you must.
- One server. Simple, and fine for a long time.
- A bigger server. Often the cheapest fix there is.
- A cache. If the same data is read again and again, Redis takes most reads off the database.
- Read replicas. Copies of the database that serve reads. Writes go to the primary; reads spread over the replicas. Most apps read far more than they write, so this goes a long way.
- Sharding. Only when writes or total data size outgrow one primary. Replicas don’t help there, because every replica still holds all the data and replays every write.
Read replicas in Spring are a small change: send read-only transactions to a replica and everything else to the primary.
// Java · Spring: route read-only transactions to a replica
public class ReadWriteRouter extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return TransactionSynchronizationManager.isCurrentTransactionReadOnly()
? "replica" : "primary";
}
}
@Transactional(readOnly = true) // goes to the replica
public Order getOrder(long orderId) { ... }
One catch: replicas lag a little behind the primary. A user who saves something and immediately reloads the page might not see it yet. Read your own just-written data from the primary.
How sharding works
Every row needs an answer to “which shard do you live on?” That answer comes from the shard key, a column you pick, such as user_id. A small piece of code, the router, turns the key into a shard:
// Java · the simplest router: hash the key, pick a shard
public DataSource shardFor(long userId) {
int shard = Math.floorMod(Long.hashCode(userId), shards.size());
return shards.get(shard);
}
public Order findOrder(long userId, long orderId) {
JdbcTemplate db = new JdbcTemplate(shardFor(userId)); // one shard, one query
return db.queryForObject(
"SELECT * FROM orders WHERE user_id = ? AND order_id = ?", mapper, userId, orderId);
}
Because the shard key is user_id, everything about one user (their profile, orders, addresses) lives together on one shard. Queries that include the user ID stay fast and simple.
Choosing the shard key is the biggest decision in sharding, and it’s hard to change later. A good key spreads data and traffic evenly, and matches how you query. A plain hash % N like the one above also has a nasty problem when you add shards. Both topics get their own articles next in this thread: sharding strategies, then rebalancing and hotspots.
What you give up when you shard
Sharding doesn’t just add servers. It takes things away that a single database gave you for free.
- Queries without the shard key hit every shard. “All orders since January” must be sent to every shard and the answers merged. This is called scatter-gather. It’s as slow as the slowest shard, and it gets worse as you add shards.
- Joins across shards are gone. If users and products live on different shards, the database can’t join them. Your code has to fetch from both and combine.
- Transactions across shards are hard. Moving money between two users on different shards can’t be one ACID transaction. You need a pattern like the saga from distributed systems basics: a chain of local steps, with an undo step for each if a later one fails.
- Unique IDs need care. Auto-increment counters on each shard would clash. Use IDs that are unique everywhere, like UUIDs or Snowflake-style IDs.
- Operations multiply. Schema changes, backups, upgrades and monitoring now happen on every shard.
A useful habit even before you shard: include the future shard key in your queries and code paths. WHERE user_id = ? AND order_id = ? is ready for sharding. WHERE created_at > ? across all users is not, so move that kind of query to an analytics store.
What breaks, and how to fix it
| What breaks | Why | The fix |
|---|---|---|
| One shard overloaded | A bad shard key, or one very busy user or tenant | A better key, caching, moving the hot tenant to its own shard |
| A shard goes down | Hardware or network failure on one machine | Give every shard its own replicas with automatic failover |
| Shards fill up unevenly | Data or growth not spread evenly by the key | Monitor size and traffic per shard; rebalance |
| A transaction spans two shards | The operation touches data under two shard keys | Saga with undo steps, or pick a key that keeps it on one shard |
| Reports slow everything down | Scatter-gather queries running on the live shards | Run analytics on replicas or a separate analytics store |
That second row matters: sharding alone adds failure points. Four shards with no replicas means four machines, any of which can take a quarter of your users offline. Real setups pair every shard with replicas.
Puzzle 1: “we need to shard”
Don’t shard yet. The load is almost all reads, and 400 GB fits comfortably on one modern server. Climb the ladder instead:
- Find the slow queries and add missing indexes. This alone often halves CPU.
- Add a cache for the hottest reads.
- Add read replicas and send read-only traffic there.
- If needed, move to a bigger instance.
Sharding solves write volume and data size that one primary can’t hold. This system has neither problem, so sharding would add complexity without fixing anything.
Puzzle 2: the count that takes forever
The query has no user_id, so the router can’t pick a shard. It has to scatter the query to all 32 shards, each scans its orders, and the router gathers and adds the results. All 32 live shards do heavy work at once, competing with real customers, and the answer waits for the slowest shard.
Keep this kind of question off the live shards. Run it on replicas, or better, stream orders into an analytics store built for it (see OLTP vs OLAP). For a number people check often, keep a pre-computed daily count that’s updated as orders arrive.
Puzzle 3: one shard dies
About one in eight users can’t log in, see orders or check out. Everyone else is fine, which is the upside of sharding: failures are partial. But for those users it’s a full outage, and if the disk is gone, their data may be too.
Each shard should be a small cluster: a primary plus at least one replica, ideally in another availability zone, with automatic failover. When shard 5’s primary dies, its replica is promoted within seconds. Add regular, tested backups per shard, and the 2 a.m. failure becomes an alert instead of a disaster.
Key takeaways
- Scale up first. One big server keeps transactions, joins and simple operations, and goes further than most people expect.
- Partitioning splits a table inside one database. Sharding splits data across separate servers.
- Climb the ladder: bigger server, cache, read replicas, and only then shards.
- Shard for writes and data size, not for reads. Replicas handle reads.
- The shard key decides everything. Queries with it are fast; queries without it hit every shard.
- Sharding takes things away: cross-shard joins, easy transactions, and simple operations. Every shard also needs its own replicas.
This opens the Partitioning, sharding & distribution thread. Next: sharding strategies, the different ways to decide which shard each row lives on, and how to pick a shard key you won’t regret.
Comments