Core Concepts

Database Sharding

Split a growing dataset across servers and choose where each record, query, and transaction belongs.

Free~16 min

When one database cannot commit writes fast enough, sharding divides the records among several databases so each can accept writes for its own share. In an order system where most requests touch one store, keeping a store's orders together gives those requests a single place to go.

Why one database stops being enough

A read replica can take requests such as order-history lookups. It cannot take over some of the primary's order inserts while that primary still owns all the data. The inserts still compete for the primary's CPU, storage, and write-ahead log.

First identify what the database is spending time on. A missing index can force a long scan. An oversized index can add work to each write. If tuning and a larger server give enough headroom, keep the simpler deployment. Consider sharding when one server is still the measured limit and the workload has a way to divide the data.

The shard key: the decision everything follows from

The moment you split data across machines, you pick a shard key - the column whose value determines a row's home shard. That choice decides:

  • which queries are single-shard (one round-trip) and which are cross-shard fan-out (N queries plus a client-side merge),
  • which writes stay a local transaction and which become distributed transactions,
  • how evenly writes distribute (and whether one shard runs hot),
  • how painful resharding is when you outgrow the current count.

Changing the key later can mean moving and rerouting much of the data while the application is serving requests. Pick it from the queries and transactions the system must handle.

A good shard key wants three properties that pull against each other:

  1. High cardinality - many distinct values, so writes spread evenly.
  2. Co-location with the access pattern - rows a query or transaction touches share a key value, so they land on one shard.
  3. Low write skew - no single value draws disproportionate traffic (a celebrity user, the current month).

Check those properties separately. A tenant ID can keep a tenant's writes together and still overload one shard if a single tenant supplies most of the traffic.

Partitioning strategies, and how each one breaks

Compare how each strategy places the data and what changes when traffic grows.

Hash partitioning

Take the remainder of the key's hash divided by the shard count. With many distinct keys and no one key dominating traffic, this can spread writes across shards. The hash scatters consecutive IDs, so a query for users 1000 through 2000 may have to visit every shard.

Hot user. If a popular account drives most requests for posts and reactions, every request routed by that user ID lands on the same shard. Adding shards can change the owner of that key, but the traffic still moves together.

Range partitioning

Assign ordered key ranges to shards. If shard 0 owns 0-999 and shard 1 owns 1000-1999, a query for keys 500 through 900 needs only shard 0. A wider query can find the relevant shards from the bounds.

With an increasing timestamp or ID, new writes keep landing in the newest range. That range can overload one shard even when the others are quiet. If the workload also needs efficient time scans, consider distributing data by tenant first and range-partitioning by date within each tenant's shard.

Directory partitioning

A lookup service maps each key to a shard. The mapping is explicit and arbitrary - put any key on any shard for any reason. You can rebalance individual keys and co-locate specific users with specific regions.

How it breaks. The directory is now a distributed system with its own consistency and availability concerns. Every access pays a lookup (caching helps; invalidation becomes its own problem). Reach for a directory only when the mapping must be arbitrary and mutable. If hash or range would work, you have built a metadata SPOF for no gain.

Geo partitioning

Shard by region, country, or data-residency boundary. Users hit a nearby shard - lower latency, data stays in-region. Usually a layer on top of hash or range, not a standalone scheme.

How it breaks. A query that spans regions fans out across continents. A user who moves has data in the wrong shard. A region that grows faster than the others becomes a hot shard the other regions cannot relieve.

Hot shards

A hot shard receives more work than it can handle while other shards have room. If several busy keys share that shard, moving some can help. If one celebrity's user ID accounts for most of the traffic, moving the key sends all of that traffic to its new owner.

The fixes are at the key or the access pattern:

  • Compound the key so the hot value splits. Shard by (userId, postId) instead of userId, and the celebrity's posts spread. Cost: "all posts by user 42" becomes a cross-shard fan-out.
  • Application-level fan-out for the hot entity: write with a sub-shard suffix (userId=42_shard=3) and read from all sub-shards in parallel. Manual and ugly; the only way to spread a single logical entity that cannot be re-keyed.
  • A separate hot path: route a known small set of celebrities to a dedicated cache or tier outside the sharded store. The store handles the long tail; the hot tier handles the outliers.

Detection matters as much as the fix. A hot shard shows up as one shard with high CPU or disk I/O while siblings are idle, or as one shard whose replication lag spikes while others are flat. Per-shard metrics are not optional - a cluster-level average hides the hot shard completely.

Resharding: the operational tax

The shard count on day one is almost never the count forever. Adding a shard - moving rows, updating routing, under live traffic - is resharding, and the pain tracks the partitioning strategy:

  • Hash modulo (hash(key) % N): going from four to five changes the owner of about 80% of evenly hashed keys if the existing shard numbers stay the same.
  • Consistent hashing: a new shard takes the keys in one or more slices from neighbors. The amount moved depends on the size of those slices.
  • Range: split an existing range. This can separate several busy keys. A single increasing write key can still concentrate traffic in the newest range.
  • Directory: move selected data, then update the directory so applications reach the new owner.

Consistent Hashing explains why changing placement can reduce the number of keys to move. The migration still has to protect live writes.

Suppose we move store 42. Keep the old shard as the source of truth during the copy. Start a change stream from the old shard's durable commit log at the backfill snapshot boundary, so a committed write cannot fall between the two. Copy the snapshot in batches while replaying the newer changes. If a target write fails, the stream can retry it. PostgreSQL logical decoding snapshots

A backfill can arrive after a live update. Give each row a version and apply a copy only when its version is newer than the one at the target. Record a versioned deletion marker when a live change deletes a row. Keep that marker until older copies can no longer arrive, so a slow backfill cannot recreate the row.

Verify the target's data while it catches up. At cutover, make the old shard reject new writes for store 42, even from routers using stale assignments. Let admitted writes finish or abort, then wait for the target to apply through the final committed source position. Enable the target as writer and update routing while the source still rejects writes. A request can wait or retry during the handoff. Vitess Reshard uses this catch-up sequence during its write switch.

Cross-shard queries and transactions

A query and transaction that once stayed on one server may now touch several. The routing key tells us which ones.

Cross-shard queries

A point lookup by the shard key routes directly. If a filter does not tell the router which shards can match, it may send the query to every shard in parallel, wait for responses, and merge them. This is a fan-out.

Pagination and aggregation are the expensive parts. "Top 10 by createdAt across all users" fetches top 10 per shard, then merges 10*N down to 10 - and the next page is worse. A COUNT or SUM is N queries plus a client-side sum. Choose the shard key so the hot path is single-shard; the cold path can afford a fan-out.

A common mitigation is a secondary index in a separate store (Elasticsearch, a denormalized lookup table) that maps non-key columns back to shard keys. Search by email when the shard key is userId: look up email -> userId, then query that shard. Another system to operate, but the query stays single-shard after the lookup.

Cross-shard transactions

When a write touches two shards, a local transaction cannot commit both changes. Two-phase commit can give them a shared commit decision. The isolation you get still depends on the database protocol. A saga commits steps separately and defines compensating actions for failures, so observers can see intermediate changes.

The way out is co-location: put rows that must update together on the same shard key. In a chat app, a channel's messages, membership, and thread metadata all update when a reply is posted. Partition by channelId, and the "insert reply + bump parent replyCount" becomes one local transaction instead of a distributed one.

Co-location constrains the key to the entity that owns the transaction boundary. "List all channels a user belongs to" may become a cross-shard query. Co-locate the writes that must be atomic; accept a fan-out on the reads that can tolerate it.

Built-in vs app-owned sharding

Built into the datastore. The datastore handles placement and routes operations from a partition or shard key. DynamoDB and MongoDB both support transactions that touch multiple items or documents. Check the product's limits and how well its key matches the queries.

Managed by a sharding layer. Vitess routes to MySQL shards. Citus distributes PostgreSQL tables through a cluster. These layers offer different transaction and query support. Understand which operations stay on a shard, which routes fan out, and how you will move data safely.

Choosing built-in routing can mean migrating the data model. A sharding layer may preserve more of an existing relational schema. Either way, test the busiest key and the queries that need more than one shard.

Sources: DynamoDB transactions . MongoDB transactions

When not to shard

Sharding adds routing, rebalancing, fan-out, and distributed transactions. Worth it only when the problem is real:

  • One machine handles the dataset and workload with headroom.
  • The read path is slow, and an index, cache, or replica would address the cause.
  • Most requests scan the whole dataset for analytics. A warehouse designed for those scans may be a better fit.

If sharding is necessary, start with the common request and the rows that must update together. Test the busiest key and write down how you will move it once the original placement runs out of room.

See also

  • Scalability - the ladder that puts vertical and read replicas before sharding the write path.
  • Consistent Hashing - next chapter: the ring math that turns "add a shard" into a small move.
  • Data Replication - sharding splits the write path; replication preserves durability within each shard.
  • SQL vs NoSQL - usually determines whether sharding is built into the engine or app-owned.
  • Latency vs Throughput - sharding raises write throughput; cross-shard work can raise per-request latency.
  • CAP Theorem - explains the choices an operation faces when the shards it needs cannot reach each other.
  • Database Indexes - reach for this before sharding; a missing index tempts a shard that solves nothing.
  • B-Trees vs LSM-Trees - the storage-engine choice each shard inherits.
  • Write-Ahead Log - explains how each shard tracks changes for recovery.
  • Change Data Capture - per-shard CDC into downstream systems.
  • Distributed Transactions (forthcoming) - the cost of a transaction that spans shards.
  • Saga Pattern (forthcoming) - eventual-consistency alternative to cross-shard 2PC.
  • Transactional Outbox - publish events atomically with a shard-local write.

Used in

  • Group Chat with Threads - groups the reply and parent message by channel ID so one transaction can insert the reply and update its parent.
  • URL Shortener - uses one primary for durable short-code mappings. Its redirect path adds a cache so popular reads do not force a database split.
  • Batched Inference Service - Kafka is partitioned by hash(client_id) so all of a client's requests land on one batcher, enabling per-client fairness without cross-batcher coordination; partition count follows the window-timeout math, not raw throughput.
  • Web Crawler (P2P) - URL ownership is partitioned across a DHT by hash(domain), making politeness a local check on the owning node; the consistent-hashing ring is what makes node join/leave a bounded range transfer instead of a full re-migration.

Done reading? Mark it so it sticks in your dashboard.

Discussion