Sharding Strategies and Choosing a Partition Key

Replication Sharding and the Capstone · 45 min

System Design · Module 7 · Lesson 2 of 4 · 45 min

Sharding Strategies and Choosing a Partition Key

Choose range hash or directory placement from access patterns and explain what happens to queries using another key.

The shard key determines ownership and locality, so evaluate both the main lookup and the important secondary access paths.

01 The idea

The problem this lesson solves

Map short code a7 to a shard owner.

Prerequisite: earlier lessons introduce the vocabulary and shared examples used here. Follow the module order.

ShardA partition owning a subset of a dataset.
Shard keyThe value used to determine which partition owns a record.
Scatter-gatherQuerying several partitions and combining their results.

02 Worked example

Follow one worked example

Sharding Strategies and Choosing a Partition Key worked diagram01Code lookupSingle owner02Shard ASubset of codes03Shard BAnother subset04Owner listingSecondary access pathSharding Strategies and Choosing a Partition Key compact diagram01Code lookupSingle owner02Shard ASubset of codes03Shard BAnother subset04Owner listingSecondary access path
Code lookup: Single owner • Shard A: Subset of codes • Shard B: Another subset • Owner listing: Secondary access path.

Trace the example in order. Follow the same identities, units and state transitions through the diagram and the events below.

1
Choose redirect localityMap short code a7 to a shard owner.
2
Serve one lookupThe redirect reads only that owner’s mapping.
3
Ask by ownerThe management listing now needs another index or multiple partitions.
4
Defend the trade-offState the secondary index’s update and recovery policy instead of hiding it behind another box.

The shard key determines ownership and locality, so evaluate both the main lookup and the important secondary access paths.

03 The method

Mechanisms decisions and a guided tutorial

Work through the explanation in order, then apply it in the tutorial. Each comparison names a cost as well as a benefit.

Choice or conceptPurposeBoundary or cost
Range shardsRange localityHot newest range or uneven tenant sizes
Hash shardsDistributed key ownershipScatter for range or alternate-key queries
Secondary indexSupports another query keyMaintenance and consistency work
Cross-shard transactionCoordinates multi-owner stateHigher complexity and failure surface

Choose a shard key from access patterns

Range sharding keeps nearby keys together and can make range scans efficient, but a growing time range can concentrate all new writes on one shard. Hash sharding spreads keys more evenly under suitable assumptions, but loses range locality. Directory routing maps logical partitions to physical owners and gives migration flexibility at the cost of maintaining reliable routing metadata. A key that places all of one tenant's data together helps tenant queries but can create an oversized tenant shard.

One primary partitioning choice cannot optimize every query

For a short-link service, sharding by short code makes redirect lookup a single-shard operation. An owner's ‘list all my links’ query then spans many code partitions unless you maintain a separate owner index or materialized view. Sharding by owner solves the listing but requires another route from code to owner for redirects. State which access path matters most and how the secondary path stays correct. A globally unique code also needs a deliberate generation or collision-check strategy.

Cross-shard queries and transactions are design costs

A global top-k query may ask each shard for its local top k and merge the candidates under the same total order. A scattered query's latency is affected by its slowest participant; partial failures need a policy. Global uniqueness, joins and all-or-nothing writes across shards may require extra coordination or a workflow with compensating actions. Do not pretend a transaction that is easy inside one SQL database remains equally simple after partitioning.

Sharding solves a particular limit

Read replicas copy data; shards divide ownership. If reads are the only limit and can tolerate lag, copying may help without changing all data routing. If write throughput, size or tenant isolation requires partitioning, sharding may be justified. Diagnose the limit before accepting the added routing and migration costs.

Range placement preserves useful locality but can concentrate a growing newest range. Hash placement can distribute keys under suitable assumptions but does not preserve ranges. Directory placement records an explicit owner mapping and offers flexibility while making reliable routing metadata part of the serving system.

Work both short-link access patterns

Redirects begin with a short code. Sharding by that code makes the primary lookup a single-shard operation. The owner’s “all my links” page begins with owner_id instead, so the owner’s codes may be spread across partitions.

Choose a secondary owner index, a maintained projection or a bounded scatter query with a defined consistency policy. Sharding by owner reverses the trade-off: owner listings become local while redirects need a route from code to owner. One partition key cannot automatically optimize every query. Code uniqueness also needs an explicit generation or collision-handling contract.

Cross-shard work has coordination costs

A global top-k query can request each shard’s local top k under one total order and merge candidates. The fan-out waits on several participants and can fail partially. A global join or all-or-nothing update across partitions needs more coordination than a local transaction.

State what partial results mean and bound the fan-out. If one tenant can grow much larger than others, an owner-based shard may become a hotspot even with many tenants overall. Plan thresholds and migration paths from measured size and demand; uniform key count does not guarantee uniform work.

Guided tutorial

1. List queries

Write lookup keys, expected result size and consistency for redirect and owner listing.

2. Compare three keys

Evaluate code, owner and creation date against those queries.

3. Test skew

Add one owner with half the workload and see where it lands.

4. Plan the secondary path

Define how owner listings stay consistent enough after a code-keyed write.

redirect: code → partition owner → mapping lookup
owner listing: owner_id → secondary index / projection / scatter
range placement: preserves selected ordering, may skew
hash placement: spreads suitable keys, loses range locality
directory placement: explicit logical owner metadata

04 Cheat sheet

Review the decisions

Use this table to explain the mechanism and its limit without memorizing a product name.

Choice or conceptRememberCheck
Range shardsRange localityHot newest range or uneven tenant sizes
Hash shardsDistributed key ownershipScatter for range or alternate-key queries
Secondary indexSupports another query keyMaintenance and consistency work
Cross-shard transactionCoordinates multi-owner stateHigher complexity and failure surface
ShardA partition owning a subset of a dataset.
Shard keyThe value used to determine which partition owns a record.
Scatter-gatherQuerying several partitions and combining their results.

05 Where & why

Check the primary references

Use official references for protocol and implementation details. The questions here are teaching prompts.

Primary reference
PostgreSQL replication

Read PostgreSQL replication

Primary reference
PostgreSQL synchronous replication

Read PostgreSQL synchronous replication

Primary reference
Dynamo paper

Read Dynamo paper

State the implementation version and the workload assumptions when defending your own design.

06 Interview questions

Explain the reasoning out loud

Answer before opening the explanation. The questions progress from vocabulary to decisions and failure behavior.

What does Shard mean?
A partition owning a subset of a dataset.
What does Shard key mean?
The value used to determine which partition owns a record.
What does Scatter-gather mean?
Querying several partitions and combining their results.
Does adding read replicas distribute writes?
Not in a simple single-leader group. They copy the same writes; sharding divides write ownership across partitions.
Why can timestamp sharding hotspot?
New writes can all target the newest time range. Range locality may concentrate work rather than distribute it.
What does sharding by owner improve?
Owner-local queries and some owner-local transactions. It can also create an oversized or unusually busy owner partition.
Why needs a secondary owner index a consistency policy?
It duplicates a route or view of primary data. Delayed updates, partial failures and rebuilds can make its results differ from the primary.
When should you avoid sharding?
When a simpler measured database setup meets requirements with sufficient headroom. The routing and coordination costs need a concrete benefit.

07 Practice problems

Practice a new case

Solve the new cases before revealing hints. Complete worked solutions follow the set.

Copies and partitions

Easy
A system has 4 shards and 3 full copies per shard; state the logical partitions and total shard copies.
Follow-up
A copy is not necessarily a separate physical machine.
Show the hint
Multiply only when counting copies.

Choose locality

Easy
For a query fetching all messages in one conversation, name a locality-friendly candidate key.
Follow-up
State the assumption or edge case that makes the answer correct.
Show the hint
Group the data queried together.

Choose a shard key

Medium
Choose between timestamp and account_id for account-local transaction-history queries and name one risk.
Follow-up
One account may be much larger than others.
Show the hint
Prefer locality for the important query but inspect skew.

Merge top results

Medium
Find the global top 3 from shard scores [99,80,70] and [95,90,60], with descending score and unique ids as tiebreakers.
Follow-up
No score ties occur here, but the contract must handle them.
Show the hint
Merge candidates using one total ordering.

Partial fan-out

Medium
One of eight shards times out during a global listing; specify why silently returning seven shards is unsafe.
Follow-up
State the assumption or edge case that makes the answer correct.
Show the hint
The caller may believe the result is complete.

Two-query defense

Hard
Choose a partition key for short-link redirects and owner listings, including the secondary path and one failure case.
Follow-up
State the assumption or edge case that makes the answer correct.
Show the hint
The two entry keys differ.

Worked solutions

1. Copies and partitions

There are 4 logical partitions and 12 shard copies. Physical machines depend on how copies are placed.

2. Choose locality

conversation_id is a candidate, with separate analysis for very large conversations and alternate access patterns.

3. Choose a shard key

account_id co-locates an account's history and avoids scattering each lookup. A very large or busy account can become a hotspot; plan a split or special handling if measurements require it. Timestamp partitioning helps retention but can concentrate new writes and scatter account history.

4. Merge top results

The top scores are 99,95,90. Fetching each shard's local top 3 is sufficient for the global top 3 under the same total order; define id ordering for ties and a snapshot or consistency policy for changing data.

5. Partial fan-out

The contract must report partial results or fail/retry under a bounded policy. Silent omission can misrepresent a complete global view.

6. Two-query defense

A code-keyed primary can make redirects local while an owner projection supports listings. Define when that projection updates, how it catches up and what a delayed update means to the owner. Alternatively justify another key and its redirect lookup route.