Database Sharding
Splitting one database across many machines: choosing a shard key, hash vs range sharding, and the costs you take on.
When one database server can no longer hold your data or handle your writes — even after indexes, caching and read replicas — you can shard: split the rows across several independent databases, each holding a slice of the data.
Choosing the shard key
The shard key decides which shard owns a row. A good key spreads load evenly and keeps the data a request needs on one shard. For a SaaS app, tenant_id is often ideal; for a social app, user_id.
High cardinality — many distinct values, so data can spread out.
Even access — avoid keys where one value is red hot (a celebrity account).
Query locality — most queries should include the key.
Strategies
Hash sharding
shard = hash(user_id) % N spreads data evenly, but range queries hit every shard and changing N moves almost every row. Consistent hashing (or many virtual shards mapped to fewer machines) limits how much data moves when you add capacity.
Range sharding
Shard by ranges of the key (A–F, G–M…) or by time. Range scans stay on one shard, but sequential keys like timestamps send all new writes to the last shard — a hotspot.
Directory-based sharding
A lookup service maps each key to its shard. It is the most flexible — you can move a single tenant — but the directory must be fast and highly available.
What you give up
Cross-shard joins and transactions become application work (or sagas).
Global uniqueness needs distributed IDs such as Snowflake-style IDs.
Resharding is an operational project: double-writes, backfills, cut-over.
Operations multiply — backups, migrations and monitoring per shard.
Shard last, not first: exhaust vertical scaling, read replicas, caching and archiving before paying the complexity tax.