Skip to content

Partitioning and Sharding

Intermediate 46 min read Part 6 of 18

Splitting data across machines: vertical vs horizontal, federation, range/hash/directory/geo sharding, shard keys, hot spots, secondary indexes, resharding.

Summary#

Partitioning splits data into pieces; sharding is horizontal partitioning across separate machines, each shard holding a subset of rows. It is how you scale writes and data size beyond one server. Vertical partitioning splits columns or tables; federation splits by function (users DB, orders DB). Shards are assigned by range, hash, a directory lookup or geography. The shard key decides everything: pick one with high cardinality, even load and alignment with your main queries. Watch for hot spots (the celebrity problem), avoid cross-shard queries and joins, choose local vs global secondary indexes deliberately, and plan resharding and shard-aware routing from day one.

Why It Exists#

Replication copies the whole dataset to every node, so it scales reads but not writes or storage: every replica still applies every write and stores every row. When one primary hits its limit (often 5,000-20,000 write transactions per second, or a few TB of data before backups, index builds and failovers become painful), you must split the data so each machine owns only part of it. A system with 50,000 writes per second and 40 TB of data might use 16 shards, each taking about 3,000 writes per second and 2.5 TB. This page builds on Replication; each shard is usually itself replicated.

How It Works#

Vertical vs horizontal partitioning#

  • Vertical partitioning splits a table by columns: keep hot, small columns (id, name, email) in one table and rarely used or large columns (bio, preferences_json, avatar_blob) in another. Rows stay together by primary key. It shrinks the hot table so more of it fits in memory.
  • Horizontal partitioning splits a table by rows: users 1-10M in one piece, 10-20M in another. Inside one database this is table partitioning (see Database Performance); across machines it is sharding.

Partitioning in depth#

Partition versus shard. The two words are often used loosely, so it helps to fix them. A partition is any subset of a dataset that is stored and managed as a unit. A shard is a partition that lives on its own machine (or its own replicated group of machines). Every shard is a partition, but not every partition is a shard: PostgreSQL can split one orders table into twelve monthly partitions that all sit on the same server. That is partitioning without sharding. It still helps, because each partition has its own smaller indexes and can be dropped or vacuumed on its own. It does not add CPU, memory or disk, because everything still runs on one box.

A concrete starting point. Picture an orders table with 500 million rows at about 4 KB each, roughly 2 TB with indexes. One well-tuned PostgreSQL server can hold that. The trouble shows up around the edges. A full backup takes hours. Adding an index takes most of a day. A failover means a replica must replay a large write-ahead log backlog. The hot part of the indexes no longer fits in RAM, so p99 latency climbs. Managed services have hard ceilings too. Amazon Aurora caps one cluster's storage (256 TiB at the time of writing), and a single writer instance caps write throughput no matter how much storage you buy. Splitting rows across machines removes both limits. Each machine stores less, writes less and keeps more of its working set in memory.

Vertical partitioning in practice. Splitting by column is worth doing when a few wide columns are rarely read. Suppose a users row is 300 bytes of hot fields plus a 6 KB profile_json. If the table is stored as one, a page of 8 KB holds about one row. A sequential scan or an index lookup pulls in kilobytes of data it never uses. Move profile_json to a user_profiles table keyed by user_id, and the hot table holds about 25 rows per page, so the buffer cache covers 25 times as many users. PostgreSQL already does a partial version of this automatically. Its TOAST mechanism compresses values larger than about 2 KB and stores them out of line, so wide text columns do not bloat the main heap. A column store (ClickHouse, BigQuery, Redshift, Parquet files) is vertical partitioning taken to the extreme. Each column is stored separately, so an analytical query that reads 3 of 80 columns reads about 4% of the bytes. The cost of vertical partitioning is that a query needing both halves must join them. Writes that touch both halves also become two writes. On one server that is a cheap local join and one transaction. Across servers it becomes the cross-shard problem described later.

Horizontal partitioning inside one database. PostgreSQL has had declarative partitioning since version 10 (range and list) and added hash partitioning in version 11. The planner performs partition pruning: a query with WHERE created_at >= '2026-11-01' skips every partition whose bounds cannot match. MySQL offers similar PARTITION BY RANGE / LIST / HASH / KEY clauses. Keep the partition count moderate, usually tens to a few thousand. Planning time and lock overhead grow with the number of partitions a query might touch, so a design with 100,000 tiny partitions is slower, not faster.

Time-based partitioning. Time-series and event data are a special case where range partitioning on time works very well inside one node. Almost all writes go to the current partition. Its indexes stay small and hot in memory, while older partitions become read-only and can be compressed. Queries usually ask for a recent time window, so pruning keeps them on one or two partitions. Retention becomes trivial: dropping the November 2025 partition is a metadata operation that finishes in milliseconds. A DELETE of 200 million rows, by contrast, would churn the write-ahead log for hours and leave bloat behind. TimescaleDB automates this with chunks: hypertables are split by time interval, and optionally by a space key such as device_id. Prometheus does something similar on disk. It writes samples into two-hour blocks, compacts them into larger blocks, and deletes whole blocks when they pass the retention period.

Be careful when the same idea is applied across machines. If shards are assigned by time range, every write in the system lands on the newest shard. You get one hot server and N-1 idle ones, which is the opposite of what sharding is for. Time ranges are a good partitioning key inside a node, or a second-level key under a well-spread first key. They are a poor top-level shard key for write-heavy data.

Federation (split by function)#

Federation (functional partitioning) gives each domain its own database: users, orders, payments, catalogue. Each is smaller, can be tuned and scaled separately, and failures are isolated. It is often the first split, and it aligns with microservices. The cost is that joins across domains must happen in the application, and there are no transactions across databases (see Distributed Transactions). Federation does not help when one domain alone (say, orders) outgrows a server; then you shard that domain.

Federation in depth#

Federation is usually the first split a growing company makes, because it follows team and service boundaries that already exist. A monolith with one database becomes a users database, a catalogue database, an orders database and a payments database. Each is owned by one team and reached only through that team's service.

What it buys. Each database receives only its own domain's reads and writes, so the load is divided roughly in proportion to traffic per domain. Smaller databases mean smaller working sets, so a larger share of each one fits in its buffer cache and more queries are served from memory. Writes to different domains proceed in parallel on separate machines, with no shared lock manager or write-ahead log. Each store can also be chosen and tuned for its workload. The catalogue might move to a document store with a search index. Payments stay on a strictly configured relational database with synchronous replication. Sessions go to Redis. A failure is contained, too: if the recommendations database falls over, checkout still works.

What it costs. The application, or a thin data access layer, must know which database holds which table. Queries that used to be one SQL join ("orders with the customer's email and the product title") become several calls stitched together in code. The ACID guarantees you had across tables vanish at the domain boundary. Placing an order and reserving stock are now two databases, which leads to sagas and the outbox pattern. Federation also adds hardware and operational surface: four sets of backups, four failover setups and four upgrade schedules.

Where it stops. Federation divides the system into about as many pieces as you have domains, typically 5 to 50. It does nothing for a single domain that alone outgrows a machine. If the orders domain takes 40,000 writes per second, no amount of functional splitting helps; orders themselves must be sharded by row. In practice, mature systems do both. They federate by domain first, then shard the few domains that are big enough to need it, and leave the rest as single replicated databases.

The two decisions of sharding. Once you shard by rows, every design comes down to two questions. They are worth stating explicitly in an interview because they structure the rest of the conversation.

  1. What to shard by: the shard key (also called partition key or distribution column). This decides which rows live together, and therefore which queries are single-shard and which are scatter-gather.
  2. How to distribute key values over shards: the strategy (range, hash, directory or geography). This decides how evenly load spreads and how painful it is to add capacity later.

A third decision is often forgotten until it hurts: how requests find the right shard (routing). The sections that follow take these in order.

Sharding strategies#

StrategyHowStrengthWeaknessUsed by
RangeContiguous key ranges per shardEfficient range scans; easy to split a rangeHot spots on sequential keys (timestamps, auto-increment IDs)HBase, Bigtable, CockroachDB, MongoDB ranged sharding
Hashhash(key) decides the shardEven spread of data and loadRange queries hit every shardCassandra, DynamoDB, Redis Cluster (hash slots)
DirectoryA lookup service maps each key (or tenant) to a shardTotal flexibility; move single tenantsExtra lookup; directory must be fast and highly availableMulti-tenant SaaS, Vitess keyspaces with lookup vindexes
GeoShard by user region or countryLow latency; data residencyUneven region sizes; users who move or travelGlobal apps with EU data rules

Hash sharding with plain hash(key) mod N remaps almost every key when N changes, so real systems use consistent hashing or a fixed number of logical partitions (for example 1,024 hash slots, with Redis Cluster using 16,384) assigned to physical nodes. See Consistent Hashing.

Sharding strategies in depth#

Range sharding. Each shard owns a contiguous interval of the key space, defined by split points. A small metadata table records the split points, for example [min, "g"), ["g", "n") and ["n", max). Range sharding keeps adjacent keys together, so "all events for device 42 between 10:00 and 11:00" or "tenant 7's invoices sorted by date" is one sequential read on one shard. Splitting is natural: when a range grows too large or too busy, pick a midpoint and turn one range into two. Bigtable (Chang et al., OSDI 2006) built its whole design on this idea. Tables are split into tablets of roughly 100-200 MB that a master assigns to tablet servers. HBase regions, CockroachDB ranges (512 MiB by default) and Spanner splits follow the same pattern. Range sharding fits multi-tenant systems well when the key starts with the tenant: one tenant's rows are contiguous, and a very large tenant simply occupies more ranges. Its weakness is skew. If the key increases monotonically (timestamps, auto-increment IDs, ULIDs), every insert hits the last range. Split points chosen on natural values can also be lopsided: last names starting with "S" far outnumber those starting with "X".

Hash sharding. Apply a hash function to the key and map the hash to a shard. A good hash (Murmur3, xxHash, or MD5 when speed is not critical) scatters similar keys uniformly, so even sequential IDs spread perfectly. That makes hash sharding the sensible default when the main access pattern is lookup by key. The price is that order is destroyed. A range query over the key, or a sorted scan, must ask every shard.

The naive mapping is shard = hash(key) mod N. It works until N changes. A key stays put only if h mod N equals h mod (N+1), which is true for about 1 in N+1 keys. Going from 4 to 5 shards moves 80% of the data. Going from 64 to 65 moves 98.5%, which means copying nearly the whole dataset to add 1.5% of capacity. Two standard fixes avoid this:

  • Consistent hashing places shards and keys on a ring, so adding a shard takes over only the keys between it and its neighbour, about 1/N of the data (see Consistent Hashing).
  • Fixed logical partitions: hash into a large, fixed number of buckets (1,024 or 4,096) that never changes, and keep a small table mapping buckets to machines. Adding a machine means reassigning some buckets. Keys never rehash; only whole buckets move.

A useful special case: if both the old and new counts are powers of two, doubling from N to 2N moves exactly half of each shard's data, and only to one new partner. That is why many teams start with a power-of-two number of logical shards.

Directory sharding. A lookup service stores an explicit mapping from key (or tenant, or key group) to shard. It is the most flexible scheme. You can place a whale tenant on dedicated hardware, pack ten thousand tiny tenants onto one shard, or move one customer at a time during a migration. The cost is that every request needs a lookup first. That lookup service is in the critical path, so it must be highly available and fast. In practice the directory is cached aggressively in routers and clients, with versioning to detect stale entries, and backed by a replicated store. Because it adds a moving part and a potential single point of failure, directory sharding is rarely the right default answer in an interview. Bring it up when the problem has heavily skewed tenants or data-residency rules that a formula cannot express.

Geographic sharding. Each region's users live in that region's shards: EU users in Frankfurt, US users in Virginia. Latency drops because reads and writes stay in-region, and data-residency laws (GDPR, India's DPDP Act, China's PIPL) can be met by construction. Region sizes are uneven, though, so geo sharding is normally combined with hash sharding inside each region. You also need rules for users who move country, and for interactions across regions such as a message from a US user to an EU user. See Multi-Region Data.

Compound strategies. Real systems mix these. Cassandra and DynamoDB hash the partition key to choose a node, then store rows sorted by a clustering (sort) key inside the partition. You get hash-level spread across partitions and range scans within one. Discord's message store, for example, used (channel_id, bucket) as the partition key, where the bucket is a fixed time window, and the message ID as the clustering key. That keeps a channel's recent messages together and sorted, while preventing one busy channel from growing a single unbounded partition.

Choosing a shard key#

The shard key is the most important decision; changing it later means moving all the data. A good key has:

  1. High cardinality: many distinct values (user ID, not country), so data can spread over many shards.
  2. Even load: no single value dominates writes or reads.
  3. Query alignment: the most frequent queries include the key, so they touch one shard. "Get a user's orders" wants user_id; "get a conversation's messages" wants conversation_id.
  4. Locality for transactions: data that must change together lives on one shard (a tenant's data under tenant_id).
  5. Stability: the value never changes; changing it means moving the row.

Examples: chat messages by conversation_id; e-commerce orders by user_id (or tenant_id for B2B); a URL shortener by short code (hash); time-series by (device_id, time bucket) so one device's recent data does not land on one shard forever.

Choosing a shard key in depth#

Shard by the primary access pattern. Begin with the two or three queries that dominate traffic, not with the schema. For a chat system that is "load the latest 50 messages of a conversation" and "append a message to a conversation". Both name conversation_id, so that is the key. For an e-commerce order service it is "show my orders" and "create an order for me", so user_id. For a URL shortener it is "resolve short code", so the code itself. If the top queries disagree, shard by the one with the highest volume or the strictest latency target. Then serve the others through a secondary index or a separate read model, accepting that they will be slower or eventually consistent.

Good and bad candidates, evaluated. Consider an orders table and four possible keys:

CandidateCardinalityLoad spreadQuery alignmentVerdict
user_idHundreds of millionsEven, except a few very heavy users"My orders" hits one shardGood default
order_idBillionsPerfectly even with hashingLookups by order hit one shard, but "my orders" scattersGood if most access is by order
is_premium2Two shards at most, badly skewedAlmost noneBad: too few values
created_atHighAll new writes go to the newest rangeTime-range reportsBad as a top-level key: write hot spot

The pattern generalises. Cardinality must be far larger than the number of shards you will ever have, ideally by several orders of magnitude, so that every shard gets thousands of key values and the law of large numbers evens things out. Load must not concentrate on a few values. And the key must appear in the hot queries, or nearly every request becomes scatter-gather.

Measure skew before committing. On the existing single database you can check how a candidate key would distribute, with a query like this:

-- How concentrated is write traffic per candidate key over 7 days?
SELECT user_id, count(*) AS writes,
       round(100.0 * count(*) / sum(count(*)) OVER (), 3) AS pct
FROM   orders
WHERE  created_at > now() - interval '7 days'
GROUP  BY user_id
ORDER  BY writes DESC
LIMIT  20;

If the top key holds 0.01% of writes and you plan 64 shards, the worst shard will be within a few percent of average. If the top key holds 3%, that key alone is twice the average shard's total load at 64 shards, and you need a hot-key plan before you start (see the next section).

Locality for transactions and joins. The best shard keys put everything that must change atomically on the same shard. A tenant's invoices, line items and payments all keyed by tenant_id can be updated in one local ACID transaction. If instead invoices are keyed by invoice_id and payments by payment_id, recording a payment against an invoice becomes a cross-shard write. That pushes you toward two-phase commit or a saga. Systems that shard successfully usually design a hierarchy under one root entity: tenant, then project, then task, all carrying the root's key. Google's F1 and Spanner papers call this interleaving child tables under a parent row. Citus calls it co-location. Vitess achieves it by giving child tables the same primary vindex.

Stability and permanence. The shard key value of a row should never change, because changing it means deleting the row on one shard and inserting it on another. A user's email address is a poor key because people change emails. A user ID is a good one because it is assigned once. The choice of key column is even harder to change. It shapes indexes, IDs, routing code and every query in the application, so in practice the shard key is often permanent for the life of the system. Some databases do allow online changes. MongoDB 4.4 added refining a shard key by adding suffix fields, and MongoDB 5.0 added reshardCollection, which rewrites a whole collection under a new key. Even so, plan as if you will live with the first choice.

Unique constraints. A unique index on the shard key is easy, because each value lives on exactly one shard. A unique constraint on any other column, such as email when sharding by user ID, cannot be checked by one shard alone. Either make that column the key of a separate, globally indexed table (an emails table sharded by email), or accept an asynchronous uniqueness check. This is one of the most common surprises when a team first shards an existing schema.

IDs that carry the shard. If IDs encode their shard, any service holding an ID can route without a lookup. Instagram's well-known scheme packs 41 bits of milliseconds, 13 bits of logical shard ID and 10 bits of per-shard sequence into a 64-bit integer. The ID is time-sortable, and its shard is a bit-shift away. See Unique ID Generation.

Hot spots and the celebrity problem#

A hot spot is a shard receiving far more traffic than others. Causes:

  • Sequential keys with range sharding: all new rows (timestamps, increasing IDs) go to the last range. Fix: hash the key or prefix it.
  • Celebrity (hot key) problem: one key gets huge traffic, such as a celebrity with 100 million followers or a viral product. Hashing cannot help; one key lives on one shard.

Fixes for hot keys:

  • Key splitting (salting): append a suffix (post:123#0 ... post:123#9) to spread writes across 10 shards; readers combine all 10. Use it only for known hot keys.
  • Caching hot reads in front of the shard (see Caching Fundamentals).
  • Special handling: treat celebrity accounts differently, for example pulling their posts at read time instead of pushing to followers.
  • Write buffering: aggregate counter updates in memory or a stream and write in batches.

See Pattern: Scaling Writes.

Hot spots in depth#

The celebrity problem, with numbers. Suppose posts are sharded by post_id across 64 shards, each comfortably handling 10,000 writes per second. A pop star with over 100 million followers posts, and within a minute the post is receiving 150,000 likes per second. Every one of those writes targets one key, so one shard. It is 15 times over capacity while the other 63 shards idle. Adding shards changes nothing, because a single key cannot be divided by any hashing scheme. The same thing happens to reads when the post is the top item in every feed. Hot keys are a property of the workload, not of the partitioning function.

Time-based hot spots. The second family comes from time. With range sharding on a timestamp or monotonic ID, the newest range takes all inserts. Even with hash sharding, time creates bursts. A flash sale makes one product's inventory row the busiest key in the system for ten minutes. A daily batch job that processes "all accounts due today" hammers the shard holding today's partition. A New Year's Eve message spike multiplies load on every shard at once, which is a capacity problem rather than a skew problem, but it is easy to confuse with one.

Detecting hot spots. You cannot fix what you do not see, so track metrics per shard, not just cluster-wide averages:

  • requests per second and bytes per second per shard, with the ratio of the busiest shard to the median (a ratio above 2 deserves attention);
  • p99 latency per shard, because a hot shard shows queueing delay first;
  • CPU, disk IOPS and replication lag per shard primary;
  • the top-k keys by traffic, sampled from the router or the database. Exact counting over millions of keys is expensive, so sample 1 in 100 requests, or use a Count-Min sketch or a heavy-hitters algorithm (see Probabilistic Data Structures).

Managed stores expose this directly. DynamoDB's CloudWatch Contributor Insights lists the most-accessed partition keys, and Redis has redis-cli --hotkeys when an LFU eviction policy is configured.

Isolating hot keys. With directory or range sharding you can move a known hot key onto its own shard, with its own hardware. Multi-tenant SaaS does this routinely for its largest customers. It turns an unpredictable neighbour problem into a predictable capacity plan for one tenant.

Compound keys. If one entity accumulates too much data or traffic over time, add a second field to the key so the entity spreads out. Use hash(user_id + date) for a high-volume activity log instead of hash(user_id). Each day of one user's activity lands on a different shard, so even the busiest account spreads over many shards across a month. The trade-off is on the read side: "a user's activity for the last 30 days" now touches up to 30 shards rather than one. It is still far better than all 64, and the reader knows exactly which 30.

Salting a write-hot key, worked. For the 150,000 likes per second, split the counter into 20 sub-keys, post:123#0 to post:123#19. Each write picks a random suffix, so each sub-key receives about 7,500 writes per second. The sub-keys hash to different shards, so the load spreads across about 20 of them. A read of the total sums 20 values, which is cheap if done every few seconds and cached. Salting is only for keys you know are hot. Applying it to every key multiplies the cost of every read by the salt factor. Systems therefore detect heat first, then salt dynamically, keeping a small table of "currently salted keys" that writers and readers both consult.

Buffering. Many hot writes are increments that commute. Instead of 150,000 row updates per second, an aggregator accumulates increments in memory, or in a stream partition, and flushes one UPDATE likes = likes + 8,412 per second. Durability comes from the stream: Kafka holds the raw events, so a crashed aggregator can replay them. See Pattern: Scaling Writes.

Dynamic splitting. Range-sharded databases can split hot ranges automatically. MongoDB's balancer runs in the background and migrates chunks between shards to even out data distribution, with no operator action. Vitess takes the opposite stance: resharding is operator-driven. A human starts a Reshard workflow and decides when to switch traffic. Automatic splitting reacts faster. Operator-driven splitting is more predictable and avoids surprise data movement during peak hours. DynamoDB splits partitions on its own when they exceed size or throughput limits, and its adaptive capacity lends unused throughput to a busy partition. It still cannot make one key exceed the per-partition ceiling of about 1,000 write units per second.

Cross-shard queries and joins#

Queries that include the shard key go to one shard (fast). Queries without it must scatter-gather: send to all shards and merge the results. With 64 shards, one slow shard sets the latency of every scatter query, and load multiplies by 64.

Ways to cope:

  • Design around the key: put the data a query needs on one shard (co-locate a user's orders and order items under user_id).
  • Denormalize: copy the few fields you need instead of joining across shards.
  • Reference tables: replicate small, rarely changing tables (countries, plans) to every shard so joins stay local.
  • Separate read models: feed shards into a search or analytics system (Elasticsearch, a warehouse) through change data capture for cross-shard queries.
  • Avoid cross-shard transactions; when unavoidable, use sagas or two-phase commit.

Cross-shard queries in depth#

Scatter-gather, step by step. A query without the shard key is sent to every shard, each computes a partial answer, and a coordinator merges them. Take "top 10 best-selling products this week" over 64 shards. If orders are sharded by product_id, each product's sales live on one shard. Each shard can return its local top 10, and the global top 10 must be inside the union of those, so the coordinator merges 640 rows and keeps 10. If orders are sharded by user_id instead, one product's sales are spread across all 64 shards. A product that ranks 11th on every shard can be first overall, so local top-10 lists are no longer enough. Each shard must return per-product totals for every product, or a much deeper list, and the coordinator sums them. Threshold algorithms (Fagin and colleagues) or approximate sketches reduce that cost, but the lesson stands: merging partial results is only cheap when the merge is mathematically valid. Either way, the work multiplies by 64, and that is not even the worst part.

Tail latency compounds. The coordinator waits for the slowest shard. If each shard independently has a 1% chance of answering slower than its p99, the chance that a 64-shard query hits at least one slow shard is 1 - 0.99^64, about 47%. With 100 shards it is about 63%. So the median scatter query experiences the shards' p99 latency. Jeff Dean and Luiz André Barroso described this effect in "The Tail at Scale" (Communications of the ACM, 2013), along with mitigations. Hedged requests send a second copy of a slow sub-request to another replica after a short delay, such as the p95, and use whichever answers first. Tied requests enqueue on two replicas and cancel the loser. Partial results return what arrived by a deadline, which is acceptable for search, not for a bank balance. Load also multiplies: if 10% of 50,000 QPS is scatter-gather over 64 shards, that is 320,000 extra shard queries per second.

Aggregates. Push partial aggregation to the shards. COUNT and SUM combine by adding. AVG needs each shard to return both sum and count, because averaging the averages is wrong when shards differ in size. MIN and MAX combine directly. COUNT(DISTINCT) does not combine at all, because the same user can appear on many shards. Either ship the distinct values, which is expensive, or have each shard return a HyperLogLog sketch and merge the sketches, which gives an error of about 1-2%.

Pagination. ORDER BY created_at LIMIT 20 OFFSET 10000 across shards forces each shard to return 10,020 rows so the coordinator can find the right 20. Use keyset pagination instead ("rows with created_at before the last one seen"). Each shard then returns just 20, and the coordinator merges them.

Joins across shards. Distributed SQL engines name three ways to do them, and they show what you would otherwise build yourself:

  • Co-located join: both tables are sharded by the same key and the join is on that key, so each shard joins locally. This is the cheapest and the reason to share keys across related tables.
  • Broadcast (reference table) join: a small table, such as countries, currencies or plans, is copied to every shard, so any shard can join against it locally. Citus calls these reference tables.
  • Repartition join: rows from one or both sides are re-hashed on the join key and shuffled across the network so matching rows meet. This is what Spark and warehouses do. It is powerful but too heavy for an OLTP request path.

Three practical answers. In interviews and in practice, the remedies for frequent cross-shard reads come down to three:

  1. Cache the result if it tolerates staleness. A "top products" list refreshed every 60 seconds turns 64 shard queries per request into 64 per minute.
  2. Denormalize into a structure keyed the way the query needs. Maintain a separate orders_by_product table sharded by product_id, updated through change data capture, or precompute a leaderboard.
  3. Accept it when the query is rare: a daily admin report that fans out to 64 shards once a day is fine. Scatter-gather is a problem of frequency, not of existence.

Transactions across shards. A write that must atomically change two shards, such as moving money from Alice (shard 3) to Bob (shard 41), cannot use a local transaction. Two-phase commit gives atomicity, but it is fragile under failure. Participants hold locks while waiting for the coordinator, and if the coordinator crashes after "prepare", they stay blocked until it recovers. It also adds at least two extra round trips to every transaction. The preferred options, in order:

  • Avoid it by choosing a key that co-locates data that changes together.
  • Use a saga: debit Alice in one local transaction and publish an event. Bob's shard then credits him in a second local transaction. If the credit fails permanently, a compensating transaction refunds Alice. A ledger table with an idempotency key on each step makes retries safe.
  • Accept eventual consistency where the business allows, for example a follower count that briefly disagrees with the follower list.

Databases built for distributed transactions (Spanner, CockroachDB, YugabyteDB) run 2PC over consensus-replicated groups, which removes the blocking-coordinator problem, but they still pay cross-shard latency. See Distributed Transactions.

Local vs global secondary indexes#

Queries by a non-shard-key column (find orders by product_id when sharded by user_id) need a secondary index. Two designs:

Local index (document-partitioned)Global index (term-partitioned)
Where it livesEach shard indexes only its own rowsThe index is itself sharded by the indexed value
WritesFast: index updated on the same shard, in the same transactionSlower: a write may update an index on another shard, usually asynchronously
Reads by indexed valueScatter-gather to all shardsOne index shard, then fetch rows
ConsistencySame as the dataOften eventually consistent
ExamplesCassandra secondary indexes, MongoDB, Elasticsearch shards, DynamoDB LSIDynamoDB GSI, Vitess lookup vindexes

Use local indexes when such queries are rare or when you always also filter by the shard key; use global indexes for frequent lookups by another attribute, accepting the lag.

Secondary indexes in depth#

A worked case. Orders are sharded by user_id across 64 shards. The warehouse team needs "all open orders containing product 9917", about 300 queries per second. With a local index, each shard has an index on (product_id, status) covering only its own orders. The query fans out to all 64 shards, each does a fast index lookup, and the router merges the results. That is 19,200 index lookups per second spread over the cluster, with p99 set by the slowest shard. With a global index, a separate table orders_by_product(product_id, order_id, user_id, status) is sharded by product_id. The query goes to one index shard, finds the matching order IDs and user IDs, then fetches the orders from the shards those user IDs map to. Because many orders for one product belong to different users, that fetch step can itself touch many shards. Global indexes often store ("project") the columns the query needs, so the second hop can be skipped.

Keeping a global index in sync. Every insert or update of an order now writes to two shards: the order's shard and the index entry's shard. There are three ways to do it.

  1. Synchronously, in a distributed transaction. Spanner and CockroachDB keep secondary indexes transactionally consistent because every write is already a distributed transaction. Reads by index are always correct, but writes pay cross-shard commit latency.
  2. Asynchronously, by the database. DynamoDB global secondary indexes (GSIs) are updated by the service in the background, usually within a fraction of a second. A GSI read is eventually consistent; strongly consistent reads are not offered on GSIs. If a GSI lacks write capacity, DynamoDB throttles writes to the base table to stop the index falling behind, so an under-provisioned index can hurt the main workload. A table can have up to 20 GSIs by default.
  3. Asynchronously, by your pipeline. Change data capture streams base-table changes into an index table or a search engine such as Elasticsearch. This gives the most flexibility (full-text search, faceting, any number of indexes), but you own the lag, the replays and the backfills. See Change Data Capture.

Local index limits. Local indexes are cheap to maintain and always consistent, but they have their own constraints. DynamoDB local secondary indexes (LSIs) must be defined when the table is created. They also cap each partition-key value's "item collection" (base items plus LSI entries) at 10 GB, so a very large customer can hit a hard wall. Elasticsearch is a pure local-index system: each shard is a self-contained Lucene index, and every search fans out to one copy of every shard. That is why Elasticsearch clusters are sized carefully by shard count, with the common guidance of keeping shards in the tens of gigabytes.

Vitess lookup vindexes. Vitess implements global indexes as ordinary sharded tables called lookup vindexes. A lookup vindex maps a column value (an email, an order number) to the keyspace ID of the owning row. VTGate updates the lookup table as part of writes and consults it on reads that filter by that column. A unique lookup vindex is also how you get global uniqueness, such as one account per email, in a database sharded by user ID.

Choosing. Use a local index when the non-key query is rare, when it also filters by the shard key (then it is a single-shard query anyway), or when you need strict consistency without distributed writes. Use a global index when the non-key query is frequent and latency-sensitive and you can tolerate either the write cost (synchronous) or a small lag (asynchronous). Use a separate search or analytics system when the query is ad hoc, full-text or analytical.

Resharding#

Shards fill up and load grows, so data must move. Approaches:

  • Many logical partitions from the start: create, say, 1,024 logical shards mapped to 8 machines; to grow, move whole logical shards to new machines. No rehashing of keys, just reassigning partitions. Used by Vitess-style setups, Elasticsearch (primary shard count fixed at index creation), Cassandra vnodes and Redis Cluster slots.
  • Split ranges: range-sharded systems split a hot or large range in two and move one half (HBase regions, CockroachDB ranges, MongoDB chunks), often automatically.
  • Consistent hashing: adding a node takes over only neighbouring keys.

Moving data online follows a pattern: copy a snapshot, stream ongoing changes (CDC), verify, briefly block writes for the moving partition, switch routing, then delete the old copy. See Data Migration.

Resharding in depth#

When to reshard. Reshard before you must, not after. Typical triggers are a shard primary consistently above about 60-70% CPU at peak, disk above about 70% full, replication lag growing on the busiest shard, or projected growth that will cross one of these within the lead time of a migration (often one to three months for a large dataset). Resharding under pressure is how data gets lost. Moving terabytes is itself a heavy workload, and it competes with production traffic on exactly the shards that are already struggling.

Logical shards make resharding a move, not a rehash. If keys map to a fixed set of logical shards (say 4,096), and logical shards map to physical clusters, growing from 16 clusters to 32 means moving half the logical shards. No row's logical shard ever changes, so application code, IDs and caches keyed by logical shard are untouched. Instagram's design worked this way. Thousands of logical shards were implemented as PostgreSQL schemas, several per physical server, and moving a schema to a new server was the unit of growth. Notion described a similar plan when it first sharded PostgreSQL in 2021: 480 logical shards spread over 32 physical databases, with 480 chosen because it divides evenly into many smaller fleet sizes.

Splitting shards. When the number of logical shards itself must grow, or in range-sharded systems, a shard is split. A range shard picks a split key, often the median of the range or a point chosen by observed load, and becomes two shards that can then live on different machines. Hash-sharded systems that started with too few shards split each one into two by using one more bit of the hash, which is why power-of-two counts are convenient.

The online move, step by step. Whatever the unit (a logical shard, a range, a tenant), the safe procedure is the same:

  1. Provision the target and create the schema.
  2. Snapshot copy: copy a consistent snapshot of the moving data, recording the log position at which it was taken.
  3. Catch up: stream every change after that position (MySQL binlog, PostgreSQL logical replication, MongoDB oplog) and apply it to the target until lag is near zero.
  4. Verify: compare row counts and checksums per key range. Vitess provides VDiff for exactly this.
  5. Cut over reads first, which is low risk, because if something is wrong you switch back.
  6. Cut over writes: briefly block writes for the moving range (typically for a few seconds), wait until the target has applied the last change, then flip the shard map and bump its version so routers pick up the change.
  7. Keep reverse replication from the new location back to the old one for a soak period, so rollback is a routing change rather than a data recovery.
  8. Clean up: delete the moved data from the source once you are confident.

Vitess packages this as a Reshard workflow built on its VReplication engine: copy, catch-up, VDiff, SwitchTraffic (with read and write traffic switchable separately) and ReverseTraffic for rollback. MongoDB moves chunks between shards with the balancer, and since 5.0 can reshard a whole collection onto a new key. Cassandra streams token ranges to a joining node. DynamoDB and Spanner split and move partitions internally with no operator involvement.

Dual writes, and why they are a trap. The tempting shortcut is to have the application write to both old and new locations during the migration. Without a single ordering of writes, the two copies diverge silently. A write can succeed on one and fail on the other, two concurrent updates can arrive in different orders, and retries can double-apply. If you must dual-write, make one side the source of truth, write it first, write the other through an outbox or retry queue with idempotent operations, and run continuous diffing. Log-based copying (CDC) avoids most of these problems, because the source database's own commit order is replayed. See Data Migration.

Throttling. A copy that runs at full speed can saturate the source's disk and network and cause the very outage you are trying to prevent. Production tools throttle on replica lag and on source load, pausing the copy when lag crosses a threshold such as 5 seconds. Budget for the copy to take days for multi-terabyte shards.

Shard-aware routing#

Something must send each request to the right shard:

  • Client-side / library: the app holds the shard map and connects directly (Redis Cluster clients, Cassandra drivers). Fastest, but every client must refresh the map.
  • Proxy / router: a routing tier that clients talk to (Vitess VTGate, MongoDB mongos, ProxySQL, Twemproxy). Simple clients, one extra hop (about 0.5-1 ms).
  • Any node routes: every node knows the map and forwards (Cassandra coordinators, CockroachDB).

The shard map is stored in a strongly consistent store (etcd, ZooKeeper or the database's config servers) and versioned, so routers and clients detect stale maps and retry after a "wrong shard" error.

Routing in depth#

Keeping shard maps fresh. Whatever does the routing caches the shard map, because looking it up on every request would add a network hop and overload the metadata store. Caches go stale during resharding, so every serious design has a redirect or retry path. Redis Cluster is a clean example. A node that receives a key for a slot it does not own replies MOVED with the correct node, and the client updates its slot table. During a slot migration it replies ASK, which tells the client to try the target node for this one request without updating its map. MongoDB routers (mongos) cache chunk metadata from the config servers, and shards reject operations carrying a stale shard version, which makes the router refresh and retry. Vitess VTGate watches the topology service (etcd, ZooKeeper or Consul) for changes. Cassandra drivers are token-aware: they compute the token of the partition key and send the request straight to a replica that owns it, which saves the coordinator hop.

Where to put the router. A smart client (a library inside each service) gives the lowest latency, but every language your company uses needs a correct implementation, and upgrades roll out service by service. A proxy tier (VTGate, mongos, ProxySQL, Envoy-based database proxies) centralises routing logic, connection pooling and query rewriting, at the cost of about 0.5-1 ms and one more fleet to run and scale. When every node can route, as in Cassandra and CockroachDB, no separate tier is needed, but a request can take one extra internal hop when the client contacts a node that is not a replica for the key.

How popular systems shard, in one place:

SystemPartitioningRebalancingRouting
Cassandra / ScyllaDBMurmur3 hash of partition key on a token ring, with virtual nodes (16 tokens per node by default since Cassandra 4.0)Streams token ranges when nodes join or leaveToken-aware drivers, any node can coordinate
DynamoDBHash of partition key, items sorted by sort key inside a partitionAutomatic splits on size (about 10 GB) or throughputRequest router inside the service
MongoDBRanged or hashed shard key over chunksBalancer migrates chunks automatically, reshardCollection since 5.0mongos routers with config server metadata
Vitess (MySQL)Keyspace ID from a vindex (often a hash), ranges of keyspace IDs per shardOperator-run Reshard and MoveTables workflowsVTGate proxies with a topology service
Citus (PostgreSQL)Hash of distribution column into shards (32 per table by default)Shard rebalancer moves shards between workersCoordinator node, or any node in recent versions
Spanner / CockroachDBRange sharding of the key space into splits or rangesAutomatic split, merge and move based on size and loadAny node, with a cached range directory

The trend is clear. Newer systems hide sharding entirely and split ranges automatically based on size and load. Older ones expose the shard key as a first-class concept that you must design. Even in the "automatic" systems, though, the shard key or primary key still determines hot spots and query locality. A Spanner table keyed by a monotonically increasing timestamp gets the same write hot spot as a hand-sharded MySQL fleet. Google's own Spanner documentation tells users to avoid such keys.

When to Use It#

  • Writes or storage exceed what one primary can handle after tuning, vertical scaling and archiving.
  • Data naturally divides by a key with independent access: tenant, user, conversation, device.
  • Data residency rules require keeping some users' data in one region.

When NOT to Use It#

  • Before exhausting cheaper steps: indexes, bigger machines, caching, replicas, table partitioning.
  • When most queries span the whole dataset (analytics); use a warehouse instead.
  • When the workload needs many cross-entity transactions and joins with no natural key; consider distributed SQL (CockroachDB, Spanner, YugabyteDB), which shards for you.

How to Implement It#

  1. Pick the shard key from your top queries and write patterns; check cardinality and skew on real data.
  2. Choose a strategy: hash for even load, range for scans, directory for per-tenant control, geo for residency.
  3. Create many logical shards (hundreds to thousands) mapped to fewer physical nodes.
  4. Add routing: a proxy (Vitess, mongos) or a shard-aware client, with a versioned shard map in a consistent store.
  5. Co-locate related data, replicate small reference tables, and denormalize for cross-shard reads.
  6. Replicate each shard for availability; monitor per-shard load to catch hot spots.
  7. Build resharding tooling before you need it.
-- Hash sharding with logical shards: route in the app or proxy
-- logical_shard = hash(user_id) % 1024 ; physical node from shard_map
CREATE TABLE shard_map (
  logical_shard int PRIMARY KEY,   -- 0..1023
  node          text NOT NULL,     -- e.g. 'pg-orders-07'
  version       bigint NOT NULL    -- bumped on every move
);
TechnologyFits when
VitessSharding MySQL with routing and resharding tools
CitusSharding PostgreSQL by a distribution column
MongoDB sharded clustersDocument data with range or hash shard keys
Cassandra, DynamoDBBuilt-in hash partitioning by partition key
CockroachDB, Spanner, YugabyteDBAutomatic range sharding with SQL and distributed transactions

Trade-offs#

ChoiceGainCostPick when
FederationSimple split, isolated domainsNo cross-domain joins or transactionsDistinct domains outgrow one DB
Range shardingRange scans, easy splitsSequential-key hot spotsTime or ordered data with good key design
Hash shardingEven loadNo efficient range queriesKey lookups at scale
Directory shardingFlexible placementLookup service to runMulti-tenant with uneven tenants
Global indexFast lookups by other attributesAsync lag, write overheadFrequent non-key queries
Geo shardingLow latency, data residency by constructionUneven regions, cross-region interactionsUsers cluster by region and laws require locality
Many logical shardsGrowth by moving shards, no rehashLarger shard map, more small units to operateAlmost always, from day one
Local indexConsistent, cheap writesScatter-gather reads by indexed valueNon-key queries are rare or also filter by shard key
Salting hot keysSpreads one key's writes over many shardsReads must combine all sub-keysA known write-hot key such as a viral counter
Proxy routingThin clients, central controlExtra hop, another fleet to scaleMany languages and services share the data

Common Pitfalls#

  • Sharding too early, adding complexity a single tuned database did not need.
  • A low-cardinality or skewed shard key (country, status) that leaves some shards overloaded.
  • Using mod N hashing and having to move nearly all data when adding a node.
  • Frequent scatter-gather queries that make every request depend on the slowest shard.
  • No plan for hot keys until a viral event takes a shard down.
  • Range sharding on a timestamp or auto-increment ID, sending every insert to one shard.
  • Calculating "top N" by merging local top-N lists when one entity's values are spread over many shards.
  • Forgetting that unique constraints on non-key columns cannot be enforced by one shard.
  • Dual-writing during a migration without a single source of truth and continuous diffing.
  • Running a resharding copy unthrottled during peak traffic and overloading the source shard.

Real-World Examples#

Vitess was built at YouTube to shard MySQL and is used by companies including Slack and GitHub for large MySQL deployments.

Instagram's engineering team described sharding PostgreSQL into thousands of logical shards mapped to fewer physical servers, with IDs that embed the logical shard number.

Notion described sharding its PostgreSQL monolith in 2021 into 480 logical shards over 32 physical databases, keyed by workspace ID so that a workspace's blocks stay together. Discord's message store partitioned by channel and a fixed time bucket to keep partitions bounded, first on Cassandra and later on ScyllaDB.

In the Interview#

Handling sharding in an interview#

Do not shard prematurely. Interviewers watch for candidates who shard a database that a single machine could handle. Justify the decision with numbers from your estimate, and be explicit about which limit forces it:

  • Storage: 500 million orders at 5 KB each is 2.5 TB. One modern server can hold that, so storage alone is not a reason. At 50 TB growing 2 TB a month, it is.
  • Writes: 50,000 writes per second, sustained, exceeds what one primary handles comfortably. That is the most common honest reason to shard.
  • Reads: 200,000 reads per second is usually a caching and read-replica problem, not a sharding problem. Say so.

If none of these limits applies, say: "A single primary with replicas handles this; I'd shard only when writes pass roughly 10,000-20,000 per second or the data passes a few TB." That sentence alone shows judgement.

A four-step script. When sharding is justified, walk through it in this order:

  1. The key: "I'll shard orders by user_id, because the hot queries are 'my orders' and 'place an order', both scoped to one user."
  2. The strategy: "Hash-based, through 1,024 logical shards, to avoid hot spots from sequential IDs and to make adding capacity a move rather than a rehash."
  3. The trade-offs: "Queries by product scatter, so I'll maintain a global index by product through CDC. The cross-user flow is refunds to a merchant, and that's a saga, not a distributed transaction."
  4. Growth: "We start with 64 physical shards at about 800 writes per second each, so we have headroom of 10x. When a shard passes 70% CPU, we move logical shards to new hardware using copy, catch-up and cut-over."

Then name the hot-key plan before the interviewer asks for it: "Large merchants get isolated shards, and celebrity-style counters are buffered or salted."

Deep Dive: Shard key maths and multi-tenant skewShow

Skew estimation. With hash sharding, expected load is even only if no single key carries a large share. If the top key holds 2% of traffic and you have 100 shards, that shard has at least 3x average load. Measure the top-k keys before choosing; keys with heavy tails need splitting or caching.

Compound keys. Combining fields (tenant_id, user_id) keeps a tenant's data together while allowing a huge tenant to be split by the second field. DynamoDB and Cassandra model this as a partition key plus a sort or clustering key.

Multi-tenant skew. In SaaS, tenant sizes follow a power law: a few tenants are thousands of times larger than the median. A directory lets you place small tenants together and give large tenants dedicated shards, and move them independently.

ID generation. Auto-increment IDs do not work across shards. Use IDs that are globally unique and optionally carry the shard (Snowflake-style or embedding the logical shard). See Unique ID Generation.

Deep Dive: The mathematics of balance, and automatic shard managersShow

Balls into bins. Hashing keys to shards is the classic balls-into-bins problem. Throw m keys into n shards uniformly at random. When m equals n, the fullest shard holds about ln n / ln ln n keys, not 1. When m is much larger than n log n, which is the usual case for sharding, the fullest shard holds about m/n + sqrt(2 (m/n) ln n) keys (Raab and Steger, 1998). Put numbers on it: 10 million keys into 64 shards gives 156,250 keys on average, and the fullest shard exceeds that by about sqrt(2 × 156,250 × 4.16), roughly 1,140 keys, or 0.7%. Uniform hashing of many equal keys is therefore very even. Real imbalance comes from keys that are not equal: sizes and request rates follow heavy-tailed distributions, and then the variance is driven by the largest keys, not by the hashing.

The power of two choices. If each item is placed in the less loaded of two randomly chosen bins, the maximum excess load drops from about ln n / ln ln n to about ln ln n / ln 2, an exponential improvement (Azar, Broder, Karlin and Upfal, 1994; Mitzenmacher's 1996 thesis). Shard placement cannot use this for keys, because a key must be findable by its hash. It is used for placing shards onto machines and for load-balancing requests among replicas.

Consistent hashing variance. With one token per node on a hash ring, the arc each node owns varies widely. The largest arc is about ln n times the average, so some nodes own several times more than others. Virtual nodes fix this: with v tokens per node, each node's share is a sum of v arcs, and its relative deviation shrinks roughly as 1/sqrt(v). This is why Cassandra used 256 tokens per node for years, and why it moved to 16 in version 4.0 along with a token allocation algorithm that places tokens deliberately rather than randomly. See Consistent Hashing.

Sizing for skew. A practical rule follows from the hot-key arithmetic. If the largest key carries a fraction f of the load and there are n shards, the hottest shard carries at least f + (1 - f)/n of the total. For that to stay below twice the average 1/n, you need f below roughly 1/n. With 64 shards, any key above about 1.5% of traffic must be handled specially, by caching, salting or isolation. Adding shards lowers the threshold, so bigger clusters are more sensitive to hot keys, not less.

Automatic shard managers. Large companies have built generic services that decide shard placement for many applications. Google's Slicer (Adya et al., OSDI 2016) assigns key ranges of a hashed key space to application servers. It continuously rebalances based on load and handles hot keys by splitting and replicating slices, while clients route through a cached assignment. Meta's Shard Manager (Lee et al., SOSP 2021) manages shard placement, migration and failover for hundreds of applications across regions. The common design separates three things: the mapping (key to shard), the placement (shard to server, decided by a controller from load metrics) and the routing (clients caching placements, with versioning and redirects). The same separation appears in Vitess, CockroachDB and Spanner. Seeing it explicitly makes any sharded design easier to reason about.

Bigtable's lesson on split size. Bigtable keeps tablets around 100-200 MB so that moving one is fast and recovery after a server failure is spread across many servers in parallel. Small units mean fine-grained balancing and fast moves, but more metadata. Large units mean less metadata, but slow moves and lumpy balance. Most systems settle between about 64 MB and a few GB per unit, which is the same trade-off as choosing the number of logical shards.

Key Takeaways#

  • Sharding splits rows across machines to scale writes and storage; federation splits by function first.
  • Range, hash, directory and geo strategies trade range-scan ability, evenness, flexibility and locality.
  • The shard key should have high cardinality, spread load evenly and match the main queries.
  • Hot keys need special handling: caching, salting, or different processing for celebrities.
  • Plan for cross-shard queries, local vs global indexes, resharding with logical shards, and shard-aware routing.
  • Partitioning splits data into units; sharding puts those units on different machines. Time partitioning is great within a node but a write hot spot as a top-level shard key.
  • Decide the key from the top queries, check cardinality and skew on real data, and co-locate data that changes together.
  • Use hash into many logical shards by default, so growth is a move, not a rehash. Doubling powers of two moves exactly half of each shard.
  • Scatter-gather latency is set by the slowest shard: at 64 shards, about half of queries see some shard's p99.
  • Reshard with snapshot, CDC catch-up, verification, brief write block and versioned map switch, keeping reverse replication for rollback.