Sharding Strategies
On this page
Sharding distributes different subsets of data across different resources, while replication maintains multiple copies of the same subset. The former scales capacity and processing power; the latter provides redundancy and read availability; in practice, systems typically use both.
Before selecting a shard key, list the most common query patterns, data that needs to be modified together, data growth patterns, and access skew. A good shard key allows common requests to be routed directly and co-locates data that is frequently operated on together, but it usually cannot optimize all queries simultaneously.
Distinguish Keys, Logical Partitions, and Machines
Business keys are mapped to logical partitions via sharding rules, and routing metadata maps logical partitions to replica sets or machines. A single machine can host multiple partitions, and a single partition can have multiple replicas.
Therefore, "having 100 partitions" does not equal "having 100 machines." The number of logical partitions determines the granularity of migration and the size of the metadata; the number and specifications of machines determine actual resources. Separating these two layers allows you to migrate only a subset of partitions during scaling, without needing to redefine the meaning of each business key.
Range Sharding: Preserving Key Order
Range sharding splits data based on boundaries of ordered keys, such as [0,1000), [1000,2000). A query id BETWEEN 950 AND 1050 will access two partitions; narrower ranges might access only one, while wider ranges might cover all. The advantage is the ability to prune irrelevant partitions based on boundaries, rather than guaranteeing that all range queries access only a single partition.
If records are written in increasing time order, the latest data may continuously concentrate in the last partition. Splitting reduces the data range but does not necessarily disperse new writes: subsequent requests may still all land in the newly created rightmost partition. Design must consider write concurrency, time buckets, and other key dimensions.
Logical adjacency does not equal physical sequential I/O. Page organization, LSM tree flushes, compression, and storage media determine actual I/O; sharding only determines which resource is responsible for which range.
Hash Sharding: Dispersing Key Adjacency
Hash sharding first applies a deterministic hash to the shard key, then selects a bucket or token range. Different keys are more likely to be distributed evenly, but hashing scatters the original order: if routing depends solely on hash(order_id), querying by order time generally cannot directly determine which partition to access.
Uniform key count does not imply uniform load. Ten thousand ordinary keys may generate fewer requests than a single popular product key. Hashing does not automatically split a single hot key. AWS DynamoDB's official guidelines also emphasize designing partition keys based on actual access patterns, not just key value counts. Partition Key Design Guidelines
Composite Keys: Preserving Useful Order Within Partitions
Consider an order system where user_id is the partition key, and (created_at, order_id) is the sort key within the partition. This allows querying a user's last 20 orders by locating the user's partition and performing a bounded range scan; order_id distinguishes records with the same timestamp.
This is an access pattern design, not limited to a specific database's syntax. Its boundary is large tenants or large users: if a tenant's data must reside in a single logical partition, that partition's capacity or throughput may hit limits first. You can add month buckets or hash suffixes, at the cost of querying multiple buckets and merging sorted results.
Fetching the Last K Records Across Shards: Local Candidates First, Then Global Merge
If user data is split into multiple buckets, querying the last K records in reverse chronological order requires fetching the top K matching records from each bucket, then selecting the global top K. The (K+1)-th record in a local bucket already has K records from the same bucket ahead of it, so it cannot enter the global top K; this reasoning requires all buckets to use the same filtering conditions and the same total order.
The following tuples represent (created_at, order_id), both columns in descending order, with order_id being globally unique. All data is fixed, and records within each shard are pre-sorted:
=
=
return
assert ==
, = , None
= :
=
assert ==
assert == == 9
# When crossing pages with the same timestamp, saving only the time will miss other orders.
=
=
assert ==
assert ==
assert ==
The model collects at most P×K candidates (where P is the number of shards) and returns K via multi-way merge; real queries must also define rules for timeouts, partial results, and uneven responses from buckets. Python's filtering scans in memory, but database implementations should leverage sorted indexes to locate from the cursor, and this function should not be treated as an efficient database query plan.
order_id is the final tie-breaking dimension for pagination order. If sorting only by created_at or only including time in the cursor, multiple orders in the same millisecond may be lost across pages. SQL LIMIT also requires an ORDER BY that establishes a unique order, see PostgreSQL LIMIT/OFFSET documentation.
Composite cursors do not automatically provide cross-page snapshots: records inserted after the first page that sort before the cursor will not appear in subsequent pages; if original records change their sort keys, they may be missed or re-read. If the product requires "iterating through the complete result set at a specific moment," you must fix a usable snapshot or read version, and bind the snapshot identifier, filtering conditions, and sorting rules together to the cursor. Saving only the last ID is insufficient.
How Many to Fetch Per Shard to Get the Global Top K?
Separating local candidates from final return values reveals the actual cost of query fan-out: three shards each return K records, collecting 3K candidates in total, but only K are ultimately needed. The golden results must be selected based on the same (time, id) total order; you cannot simply compare time and arbitrarily discard ties; the records in the diagram are fixed, and new/modified records during pagination still require the snapshot conventions in the main text.
The local (K+1)-th record already has K records from the same shard ahead of it, so it cannot enter the global top K. The candidate set must use the same filtering conditions and a deterministic total order.
Handle Hotspots by Root Cause
| Hotspot Type | Possible Mitigations | Costs Involved |
|---|---|---|
| One key is heavily read | Caching, request merging, read replicas if allowed | Invalidation and consistency policies |
| One counter is heavily updated | Multiple sub-counters, aggregate on read | Total value visibility and precise constraints become complex |
| Latest time range receives continuous writes | Time buckets combined with other hashing dimensions | Range queries may fan out |
| One tenant is much larger than others | Reshard within tenant, or dedicated resources | Increased routing and cross-shard operations |
| A partition mixes multiple hot keys | Split or migrate partitions | Resource consumption during migration |
Salting adds a bucket dimension to logical keys, e.g., (product_id, bucket_id). You must define how to choose the bucket, how to locate old records, and whether queries traverse all buckets. Randomly writing a single record requiring atomic updates to different locations changes business semantics and cannot serve as a universal scaling technique.
For example, (date, hash(order_id) % B) allows point lookups for duplicate checks knowing the date and order_id to calculate the bucket; if buckets are chosen randomly on each write, you need to save the location separately or traverse buckets. In either case, querying all orders for a day usually requires accessing all B buckets. AWS's write sharding documentation compares the query costs of random vs. computable suffixes. Write sharding
Allowing clients to connect directly to target partitions reduces proxy overhead but does not increase the storage or compute limits of the target partition itself.
Secondary Indexes: Changing Query Conditions Means Maintaining Another Organization
Assume the main table is sharded by user_id, but the query condition is email. If each shard only has its own local email index, single-shard lookups will be faster, but the caller doesn't know which shard the email is in, potentially still requiring fan-out.
Another approach is to maintain a global index organized by email, mapping email to the record's primary key. This allows querying the index first, then back-referencing the main table; the cost is that one business write requires maintaining two organizations. If they span partitions, you must explicitly choose between cross-partition transactions, asynchronous propagation, or other consistency protocols.
The specific definitions of "local" and "global" vary by product, and you cannot infer whether index updates are atomic or support strong consistency reads solely from the name. Asynchronous indexes may temporarily miss new records or point to already deleted records; applications must handle this according to required semantics. Checking "this email doesn't exist" via an index before inserting does not automatically constitute a global unique constraint.
Why "Not Existing in Index" Cannot Serve as a Uniqueness Lock
Two registration requests use the same email but are routed to different shards by user_id. Even if single inserts on each main shard are atomic, the following interleaving is legal:
| Time | Request A | Request B |
|---|---|---|
| 1 | Check email index, record not found | |
| 2 | Check same index, record not found | |
| 3 | Write User A | |
| 4 | Write User B | |
| 5 | Index async update | Index async update |
Both main records already exist simultaneously; subsequent index updates retaining one or both entries cannot revoke this fact. The problem is not just slow index propagation: even if both queries are strongly consistent, as long as "check non-existence" and "obtain creation rights" are two separate steps, both checks can still occur before the first creation.
One direction is to atomically claim creation rights at a unique location determined by normalized email, or use covering constraints and transactions with the main record. The former requires defining how to recover if the placeholder succeeds but the main record fails, avoiding permanent placeholders; the latter requires bearing the corresponding cross-shard coordination costs. The cost of so-called global unique constraints lies in this key that must be jointly adjudicated; it cannot be pieced together by building local unique indexes on all shards separately.
Shard Key Review Checklist
- Do primary queries include the shard key? If missing, how many partitions must be accessed?
- Could a single partition's capacity, writes, or hotspots be exhausted first?
- Can records frequently modified together be co-located? What transaction semantics are needed for cross-partition operations?
- Will the shard key change? Does a change imply in-place updates or record migration?
- Are the additional costs of secondary indexes, pagination, and global sorting acceptable?
Fan-out also amplifies tail latency and failure handling costs: parallel query responses usually wait for the slowest required result. If partial results are allowed, their completeness must be defined; if complete results are required, consider retries, deadlines, and duplicate merging.
Continue reading: Consistent Hashing explains how to reduce remapping when members change; Dynamic Rebalancing explains how partitions migrate.
References
Keywords: sharding, partition key, range partitioning, hash partitioning, hot key, salting, secondary index