Database Sharding
Split one huge dataset across several databases, so no single database holds all of it.
What is it?
Replication copies the same data many times, which helps reliability and read scaling. But a dataset can grow so large that its writes, or just its storage, outgrow any single server, however good the hardware.
Sharding splits the data itself into pieces (shards), each on a separate database. A rule decides where each piece goes, usually a shard key such as a user id.
Explain like I'm 10
It's like splitting a huge filing system across cabinets by last name: A-M in one, N-Z in another. Neither holds everything, but together they hold it all, and each only needs room for its share.
Examples
Routing to the right shard by user id
function getShardForUser(userId) {
const shardCount = 4;
return userId % shardCount; // simple hash-based routing
}
async function getUser(userId) {
const shard = getShardForUser(userId);
return databases[shard].query("SELECT * FROM users WHERE id = ?", [userId]);
}How it works
The shard key decides which shard a piece of data belongs to, often through a hash function so data spreads roughly evenly.
Every read or write for that data goes to its one shard, so each database only holds and processes a fraction of the total.
Why does it exist?
Some datasets are too large, in size or write traffic, for any single server. Sharding scales a database horizontally (more machines) instead of vertically (a bigger machine), the same idea as scalability in general.
When to use it
Shard once a dataset's size or write throughput has truly outgrown a single (even well-replicated) database. It's usually a late-stage scaling decision.
When not to use it
Don't shard too early. It adds real complexity: queries that need data from several shards get much harder, and re-sharding later is painful. Most apps never reach that scale.
Try simpler options first: a bigger server, replication and caching.
Common mistakes
Choosing a shard key that spreads data unevenly, e.g. sharding by signup date when most users signed up recently, overloading one shard.
Writing queries that join or aggregate across many shards, which sharding makes much more expensive or awkward.
Sharding before it's needed, taking on real operational complexity for scale you haven't reached.
Practice exercises
- Easy:
Explain the difference between sharding and replication.
- Medium:
Describe a bad shard key for a table of orders, and why it would cause uneven load.
- Hard:
Explain why counting all rows across every shard costs more than the same query on an unsharded database.
Interview questions
What is database sharding?
Splitting a dataset into pieces, each on a separate database, based on a shard key, so no single database holds all the data.
What's the difference between sharding and replication?
Replication copies the same data to several databases. Sharding splits different pieces of data across several databases. They solve different scaling problems and are often used together.
What makes a good shard key?
One that spreads data and load roughly evenly across shards, and that most queries can use to go straight to the right shard without needing others.
What's the difference between range-based and hash-based sharding?
Range-based sharding gives each shard a continuous range of the key (e.g. user ids 1–1000 on shard A, 1001–2000 on shard B). Related or sequential data stays together and range queries are efficient. Hash-based sharding hashes the key to pick a shard, spreading data roughly evenly but scattering sequential or related data across unrelated shards.
What's a downside of range-based sharding regarding hotspots — for example, sharding orders by order id or timestamp?
The range holding the newest data (the highest order ids, or today's dates) gets nearly all new writes and recent reads, while older ranges on other shards sit mostly idle. That defeats the point of spreading load.
Scenario: a table is sharded by `userId % 4`. What happens when you need to add a 5th shard?
For almost every user, userId % 5 points to a different shard than userId % 4 did, so nearly all data must be moved. A naive modulo scheme makes adding or removing shards hugely disruptive instead of incremental.
What is consistent hashing, and how does it solve the resharding problem above?
Consistent hashing places keys and shard nodes on the same ring; each key belongs to the next node around it. Adding or removing a node only reassigns the keys near that node, instead of remapping almost every key like plain modulo.
What is a "hot shard," and give a concrete example of a shard key that would create one?
A shard that gets far more traffic or data than the others and becomes a bottleneck, even though the system is "sharded". Example: sharding by country when 80% of users are in one country. That shard carries most of the load however many shards exist.
What is "directory-based" sharding, and what's its tradeoff versus computed (hash or range) sharding?
A directory keeps an explicit lookup table from each key (or range) to its shard instead of computing it. It's more flexible, since individual keys can be moved independently, but the lookup table becomes critical shared infrastructure and a possible bottleneck that computed schemes avoid.
Why is choosing a shard key one of the hardest, most consequential decisions in a sharded system?
It decides how evenly load spreads, whether common queries can go to a single shard, and how costly resharding will be. Get it wrong and you face hot shards, constant cross-shard queries or a painful migration, often found only once real traffic hits.
Why is it hard to change a shard key after a system is already in production?
You must recompute the shard for every row and move the data that changes owner, while serving live traffic. It's a full data migration under production load, not a config change.
What does "resharding" require operationally, and why is it considered risky and expensive?
Moving data between shards under a new scheme, updating routing so queries find it, and doing it without losing writes or serving inconsistent reads mid-migration, usually with careful dual writes or a gradual cutover. A mistake can corrupt or lose data across the whole dataset, not just one shard.
Why do cross-shard joins become expensive or impossible, and what's the usual workaround?
A join compares matching rows, but if they live on different machines the database can't do it locally. Data must be fetched from several shards and joined in the app or a coordinating layer. The usual workaround is denormalizing so data needed together lives on the same shard, or replacing joins with separate queries the app stitches together.
What is a "scatter-gather" query, and why is it slower than a single-shard query?
A query sent to every shard (or many) in parallel, with results combined afterward. It multiplies database round trips, and total response time depends on the slowest shard, not the average.
Scenario: "how many total orders were placed today" across 8 shards — what does this actually require, and why is it more expensive than on an unsharded database?
A scatter-gather: ask all 8 shards for their count and sum the results in the app (or a coordinator). That's 8 queries plus a merge, only as fast as the slowest shard, where an unsharded database does one local count.
What is a distributed transaction across shards, and why is achieving atomicity harder there than within a single database?
A transaction whose writes span several shards (separate databases), which must all commit or all roll back. Each shard can succeed or fail on its own and there's no shared transaction log to decide the outcome, so the shards must explicitly coordinate to agree.
What is two-phase commit (2PC), briefly, and what's its main operational downside?
A coordinator asks every shard to "prepare" (confirm it can commit), and only when all agree tells them to commit. The main downside: if the coordinator crashes after some shards prepared but before telling them to commit, those shards hold locks indefinitely and can't safely commit or abort on their own.
Why do most sharded systems try to avoid needing cross-shard transactions altogether, rather than solve them with 2PC?
2PC adds latency (extra coordination round trips on every transaction) and availability risk (a stuck coordinator can block shards indefinitely). It's usually much cheaper to design the shard key and data model so transactions stay within one shard.
What's the relationship between sharding and replication — are they mutually exclusive?
No, they're usually combined. Each shard is typically replicated too. Sharding solves "too much data or write volume for one machine"; replication solves "each shard's machine shouldn't be a single point of failure".
Scenario: a shard holding a very popular user's data on a social app becomes overloaded while other shards sit idle. What's this called, and how might you fix it without resharding everyone?
A hot shard (also called a hotspot or the "celebrity problem"). A targeted fix is moving that one heavy key to its own dedicated shard, or splitting its data further (e.g. by content id instead of user id for that user), instead of resharding everything for a few outlier keys.
Why can sharding by a monotonically increasing key, like an auto-incrementing id or a timestamp, create a hotspot?
New rows always have the highest key value, so under range-based sharding they all land in the current range on one shard. Every new write hits that shard, however many shards exist.
What's a composite shard key, and why might you use one instead of a single field?
A shard key built from several fields (e.g. tenantId + userId). Useful when one field alone would spread data unevenly or not match your queries. Combining fields can spread load more evenly while keeping related data (like everything for one tenant) groupable.
What is geo-sharding, and what benefit does it offer beyond raw scaling?
Assigning shards by region, so a user's data lives on a shard near them. Besides spreading load, it lowers latency and can help meet data-residency rules that require some users' data to stay in a specific country or region.
Scenario: you need to move a single large tenant's data from an overloaded shard to a new, empty shard, without downtime. What does this actually require?
Typically: dual-write the tenant's new changes to both old and new shards, backfill their existing data into the new shard, verify the copies match, then atomically switch the tenant's routing to the new shard and stop writing to the old one. The tenant keeps working normally throughout.
What's the difference between a "local" secondary index and a "global" secondary index in a sharded system?
A local index lives inside each shard and covers only that shard's data. It's cheap to maintain, but a query using it must still scatter-gather across all shards. A global index covers all shards in one structure, so a query can use it directly, but it needs its own infrastructure and must stay in sync with writes on every shard.
Why is a global secondary index harder to maintain consistently than a local one?
Every write on any shard must also update this shared structure, which sits outside any single shard's transaction. Keeping it exactly in sync under concurrent writes and partial failures is a hard distributed-consistency problem. A local index just updates alongside its own shard's data.
What happens to a unique constraint (like a unique email) when a table is sharded by a different key (like user id)?
The database can no longer enforce it alone: two rows with the same email could land on different shards that know nothing of each other. You need a separate global index or lookup service to check uniqueness, or weaker guarantees (check at write time and reconcile rare conflicts afterward).
Why is capacity planning for shard count inherently an estimate, and what happens if you pick too few or too many?
It depends on data growth and traffic that are hard to predict. Too few shards and you hit the scaling wall sooner than planned. Too many and you pay extra complexity and cross-shard overhead for capacity you don't need yet. Many systems create many logical shards on fewer physical machines up front, so growth means moving logical shards instead of re-sharding the keyspace.
What's a common mistake teams make by sharding too early?
Taking on cross-shard queries, harder transactions and operational overhead before the data or write volume has outgrown a single well-tuned, replicated database. Simpler options (better indexes, caching, a bigger server, read replicas) often would have bought plenty of headroom first.
Scenario: `country` is used as a shard key, but 80% of your users are in one country. What goes wrong, and what would you do differently?
One shard carries about 80% of the load while the rest sit mostly idle, so the bottleneck is still there. Use a key that spreads load more evenly, e.g. a hash of user id, or sub-shard within the dominant country instead of treating it as one unit.
Follow-up: what if you must keep `country` as the shard key for compliance reasons (data residency), despite the imbalance — what other levers do you have?
Shard further within that country (e.g. by a hash of user id, keeping all its shards in the required region), give that region more physical shards than smaller regions, or add caching and read replicas in that region to absorb load the shard key can't rebalance.
Why does adding an index need to be done identically across every shard, and what happens if that gets out of sync?
Each shard is a separate database, so an index created on one isn't created on the others. If indexes differ, the same query can be fast on some shards and slow (or use a different plan) on others, so performance depends on which shard serves the request.
How does sharding interact with a database's referential integrity (foreign keys) across shards?
A foreign key is enforced by checking the referenced row exists in the same database. If the two rows can be on different shards, no single database can check it, so cross-shard referential integrity usually has to be handled by app logic.