Nguyen Le Phong

Database Sharding: When It's Worth It and What It Costs

Sharding splits one database across many.

On an ordinary Tuesday afternoon, the dashboard starts timing out. No launch, no marketing campaign, no strange incident. Just more orders, more tenants and more writes than one database can comfortably carry. Someone opens the slow query log, someone else checks disk growth, and then the word lands in the architecture channel: sharding.

Sharding can be the right answer. It's also one of the most expensive answers you can pick, and one of the hardest to undo. This post covers what actually changes when you shard, the cheaper fixes to try first, how to choose a shard key, what gets harder afterwards, and how one well-documented migration (Notion's, in 2021) went in practice.

Engineers gather around production dashboards after an ordinary weekday surge starts pushing the main database into timeouts.
Sharding usually comes up after months of ordinary growth, not after one big launch.

What sharding actually changes

Sharding splits one logical dataset across several physical databases. Every row gets an owner shard, picked from a value in the row called the shard key: a customer ID, a tenant ID, a region. To users it's still one product. Underneath, a routing layer (in your app, in a proxy or in the database itself) decides which shard each query goes to.

It helps to keep three ideas apart. Read replicas copy the same data to more machines, which helps reads and does nothing for writes. Partitioning a table inside one server splits the table, but one machine still does all the work. Sharding spreads both storage and writes across machines, and that's why teams reach for it when writes or data size are the bottleneck.

Try the cheaper fixes first

A single database runs out of something eventually: storage, write throughput, connections, index size, or the time a backup or schema migration takes. Many of those limits can be pushed back a long way before you split anything:

  • Fix the queries. Read the slow query log, add the missing indexes, put limits on unbounded reports.
  • Scale up. A bigger machine is boring, and boring works.
  • Add read replicas and caching if the load is mostly reads.
  • Archive cold data that nobody queries any more.
  • Move analytics off the primary into a warehouse or a separate read model.

Scaling the database walks through that ladder step by step. Shard a database that's slow because of bad queries, and you get several databases that are slow because of bad queries.

So when is it worth it? Usually in one of three cases. Write volume or data size has outgrown the biggest machine you can sensibly run, even after the fixes above. You need hard isolation between tenants, so one big customer can't slow down everyone else. Or data has to live in a specific region. Maintenance pain can also force the decision before raw load does. Notion's engineers write that Postgres VACUUM kept stalling and that transaction ID wraparound "would pose an existential threat to the product" (Herding elephants: lessons learned from sharding Postgres at Notion).

The shard key is the decision that sticks

A good shard key does three jobs. It spreads data and traffic evenly, it keeps the common queries on one shard, and its value almost never changes for a given row. The ways it goes wrong are well documented:

  • Too few distinct values. MongoDB's docs point out that a key's cardinality caps how many chunks the data can be split into, and that if most rows share a few key values, the chunks holding those values become the bottleneck (Choose a shard key).
  • Keys that only go up. Timestamps and auto-increment IDs send every new insert to the same place. In MongoDB's words, a shard key that increases or decreases monotonically "is more likely to distribute inserts to a single chunk", and that shard becomes the write bottleneck. Their suggestion for such keys is hashed sharding.
  • Keys that break locality. If a page needs data from ten shards, every page load fans out to ten databases.

For multi-tenant SaaS, the usual answer is the tenant. The Citus docs recommend distributing tables by a common tenant_id column, so rows with the same value always sit on the same machine and joins inside one tenant run on one node (Choosing distribution column). Notion made the same call with workspace ID, because every block belongs to exactly one workspace and users mostly work inside one workspace at a time.

-- Citus on Postgres: shard by tenant and keep each tenant's rows together
SELECT create_distributed_table('orders', 'tenant_id');
SELECT create_distributed_table('order_items', 'tenant_id', colocate_with => 'orders');

The trade-off is real. Sharding by tenant makes per-tenant queries cheap and cross-tenant reports expensive, and one very large tenant can still turn its shard into a hot spot. That's why the key is a product decision as much as a database one. "Which questions will we ask across many customers at once?" is a question for the PM too.

A product and platform team reviews partition diagrams and hot spots while weighing which shard key spreads traffic evenly.
A key that follows how people use the product spreads growth out. A key that follows the clock stacks every new write onto one shard.

Changing the key later is possible in some databases (MongoDB has had reshardCollection since 5.0), but it still means moving every row. Pick it as if you'll live with it for years.

What gets harder after the split

You buy scale by giving up the comfort of one database that sees everything. Concretely:

  • Joins across shards. A query that touches several shards has to fan out and merge the results in the app or a proxy.
  • Transactions across shards. A write that spans two shards can't commit atomically in one database any more. You'll need a saga, the outbox pattern or both, plus an honest conversation about eventual consistency.
  • Uniqueness. A unique constraint only holds inside one shard. A rule like "one email across all tenants" needs its own mechanism.
  • Keys in app code. Notion's composite primary key (id plus space_id) meant passing space_id through much of the application, and they list a single combined key as something they'd do differently.
  • Everything operational, times N: schema migrations, backups, monitoring, admin tools, search and analytics that used to read one database.

Plan to move data before you have to

Data never grows evenly. A few tenants outgrow everyone else, or one region takes off faster than planned. Sooner or later you'll move data between machines while the product keeps running.

The move that makes this bearable is separating logical shards from physical hosts. Notion split its data into 480 logical shards (each one a Postgres schema) across 32 physical databases, 15 per database. They chose 480 because it has many factors, so they can add hosts in even steps, from 32 to 40 to 48. With 512 shards, the next even step would have been a jump from 32 hosts to 64. The plan paid off in 2023, when Notion tripled the fleet from 32 to 96 machines and each database went from 15 schemas to 5 (The Great Re-shard).

// Row to shard never changes. Shard to host can.
const LOGICAL_SHARDS = 480
const shardFor = (workspaceId) => hashToInt(workspaceId) % LOGICAL_SHARDS
const hostFor = (shard) => shardMap[shard]   // edit the map to rebalance

Compare that with hashing straight to hosts (hash % 32): add a 33rd host and almost every row changes its home.

The migration itself followed a pattern worth copying. Notion double-wrote new data through an audit log, backfilled the existing data (about three days on one large instance), and checked the result by sampling records and running "dark reads" against both the old and new databases. Then they switched over in about five minutes of scheduled downtime, with a reverse audit log ready in case they had to roll back. First on their list of lessons was to shard earlier: by waiting until the old database was badly strained, they had fewer migration options left.

Engineers watch shard health and replication lag together while preparing a rebalancing step and its rollback plan.
A rebalancing plan needs two things on the screen: how hot each shard is, and how you get back if the move goes wrong.

Make every shard visible

After the split, "the database is slow" stops being a useful sentence. You need to know which shard. Put the shard ID on every log line, trace span and slow-query record. Chart CPU, storage, replication lag and the top tenants by load for each shard, so a hot tenant shows up as a line on a graph instead of a hunch during an incident. Start every database runbook with the same first step: find the shard.

Before you shard

  • Name the resource that's running out (writes, storage, connections, maintenance time) and write down the number.
  • Try the cheaper fixes and note how much room each one bought.
  • List your ten most common queries and check which ones would cross shards under each candidate key.
  • Plan for more logical shards than hosts from day one.
  • Build per-shard dashboards before the first migration, not during it.

Sharding is a well-worn path, and Notion's write-up shows that a careful migration can go smoothly. It does ask the team to know its data and its queries better than before. If you're not there yet, the next rung on the scaling ladder is usually the better move this quarter.

What did you think?

Frequently asked questions

What is database sharding?
Sharding splits one logical dataset across several physical databases. Each row belongs to one shard, chosen by a value in the row called the shard key, such as a tenant ID or customer ID. It spreads both storage and writes across machines, which read replicas and single-server table partitioning don't do.
When should I shard my database?
After the cheaper fixes stop buying room: query and index fixes, a bigger machine, read replicas, caching, archiving and moving analytics elsewhere. The usual reasons are write volume or data size beyond one machine, hard isolation between tenants, or data that must live in a specific region. Maintenance trouble can also force it, as with Notion's stalled VACUUM and transaction ID wraparound risk.
How do I choose a shard key?
Pick a key with many distinct values that spreads traffic evenly, keeps common queries on one shard and rarely changes. Avoid keys that only increase, like timestamps or auto-increment IDs, since MongoDB's docs note they send new inserts to a single chunk. For multi-tenant SaaS, the tenant ID is the common choice.
How do you rebalance shards without moving everything?
Create more logical shards than physical hosts and keep a map from shard to host. A row's shard never changes, so rebalancing means moving whole logical shards and updating the map. In 2021 Notion put 480 logical shards on 32 databases, a number chosen so hosts can grow in even steps. In 2023 they moved the same shards onto 96 databases.
What gets harder after sharding?
Joins and transactions that cross shards, unique constraints that only hold within one shard, pagination and admin tools that need data from every shard, and operations like schema migrations and backups, which now run on every shard.