Part 8 of How Backend Systems Scale →

Sharding and System Design: Placement, Movement, and Trade-offs

12 min readUpdated

Part 8 of the eight-part How Backend Systems Scale series. Keep the separate powers-of-ten estimation reference nearby for the calculations.

Adding a read replica gives the photo app another copy of its metadata. Eventually, the dataset no longer fits comfortably on one database machine.

A second complete copy doesn’t make the first copy smaller. We need different nodes to own different subsets of the records.

That change is easy to draw. The difficult part is deciding where each record belongs, finding it later, and moving ownership while requests keep arriving.

On this page

Divide ownership and plan migrations

Divide the records

A shard holds a subset of a dataset. A shard key helps determine which subset owns a record.

TechniqueWhat it doesWhat it does not automatically solve
ReplicationMakes extra copiesDividing a dataset that is too large for one node
ShardingSplits ownership across nodesKeeping each subset available after failure

Sharding and replication can work together. Each shard can have its own leader and replicas:

We now have multiple ownership groups. A request needs enough information to reach the right one.

Choose the key from the workload

For photo metadata, several keys look plausible:

CandidateBenefitProblem
User IDOne user’s photos stay togetherA very active user can create a hot shard
Photo IDCan distribute individual photosListing a user’s photos may need another index or multiple shards
Upload dateConvenient time ranges and retentionNew writes concentrate on the current time range

Keeping one user’s photos together helps list them and perform related work. It can also concentrate a very active user’s traffic.

Before choosing, examine:

  • Frequent query predicates.
  • Large users or tenants.
  • Transactions needing several related records.
  • The procedure for moving records later.

Even record counts don’t establish even load. A shard can be hot because a small fraction of its data receives most requests.

Estimate capacity, then look for skew

For 10^9 metadata records averaging 10^3 bytes:

raw size = 10^9 × 10^3 = 10^12 bytes ≈ 1 TB

Four evenly sized shards would each hold about 250 GB before indexes, spare space, and copies. If half the traffic belongs to one user, balancing all the other users doesn’t remove that user’s local bottleneck.

Work through a placement change

A direct placement rule is hash(key) % shard_count. It is simple to compute until the shard count changes.

Here are a few representative hash outputs before and after adding a fourth shard:

hThree shards: h % 3Four shards: h % 4Moves?
000No
111No
222No
303Yes
410Yes
521Yes
602Yes
713Yes
820Yes
901Yes
1012Yes
1123Yes

Nine of twelve move. Under uniform hashing, this three-to-four change moves roughly three quarters of keys. It doesn’t move every key, but the amount can still be expensive.

The rule changed for all callers at once. We need to move the records before requests sent under the new rule can find them correctly.

Fixed logical buckets and hash rings are distinct tools

We can add a level of indirection: hash into a fixed collection of logical buckets, then look up each bucket’s physical owner.

For twelve buckets:

bucket = hash(key) % 12
owner = directory[bucket]

Adding D can move selected buckets while leaving every key’s bucket calculation unchanged:

Physical nodeBeforeAfter adding D
ABuckets 0, 1, 2, 3Buckets 0, 1, 2
BBuckets 4, 5, 6, 7Buckets 4, 5, 6
CBuckets 8, 9, 10, 11Buckets 8, 9, 10
D—Buckets 3, 7, 11

Three of twelve buckets move in this equally sized teaching example. Their records still need copying. The indirection keeps the routing function stable; it doesn’t transport data for free.

Follow one key around a hash ring

A consistent hash ring is another placement tool. Imagine positions zero through 99:

  • A sits at 20, B at 60, and C at 90.
  • A key belongs to the first node clockwise at or after its hash position.
  • Positions after 90 wrap around to A.

Now add D at 40:

Key hashBeforeAfter
10AA
30BD
50BB
70CC
95AA

D takes positions after A at 20 through D at 40, previously owned by B. Under our clockwise-successor rule, that is the interval between the new node’s predecessor and the new node.

The diagram is schematic rather than geographic. Multiple virtual positions per physical node can improve balance. They don’t eliminate hot keys or perform the migration automatically.

A fixed bucket directory and a ring are distinct mechanisms. Large systems can combine related ideas, but calling a directory a hash ring would hide how placement is actually computed.

Make the router aware of ownership

A general balancer can route a stateless request to any suitable instance. A shard router must also send a key to the node that owns its records.

That creates another small system to design:

  • Routers need a current ownership map or deterministic placement rule.
  • Old and new owners need an agreed cutover protocol.
  • Stale routing needs defined redirects, retryable errors, or recovery signals.
  • A directory service needs its own availability and consistent updates.

A coordination service can help distribute or protect metadata. Its presence in a diagram doesn’t by itself define write authority during movement.

A migration state machine

Suppose we move one bucket. We can describe the responsibilities before selecting an implementation:

  1. Copying: the old owner stays authoritative while a snapshot is copied.
  2. Catching up: transfer newer changes until the destination is ready.
  3. Cutover: coordinate routing versions and write authority.
  4. Verification: compare expected data and observe the new path.
  5. Retirement: remove old data after rollback and active-reader requirements are met.

An implementation might use change logs, a short write pause, or coordinated dual writes. Uncoordinated writes to both locations add another partial failure: one succeeds while the other fails.

The Postgres sharding guide develops the operational costs, including cross-shard transactions and rebalancing.

A hot key is not the same as a hot shard

Moving different keys can split a hot shard. One exceptionally busy key stays busy even after every neighboring record moves away.

  • Suitable read replicas or caches can help repeated reads.
  • A heavily written counter may need a different aggregation model.
  • A last-ticket reservation can’t become independent writable copies without changing its correctness rule.

Likewise, a report scanning every shard can benefit from parallel work but still needs coordination and result merging. Dividing ownership doesn’t make cross-shard operations free.

Review three architectures against requirements

Let’s use these distinctions to make smaller design choices. Each example below states teaching assumptions; it isn’t a complete production specification.

Review in this order

  1. State the main operations.
  2. Name correctness and freshness requirements.
  3. Estimate reads, writes, bytes, and peaks.
  4. Draw a simple path.
  5. Walk through a failure.
  6. Add infrastructure for a named requirement or demonstrated limit.

Numbers tell us whether the plan might have capacity. The failure walkthrough tells us what happens when one of its assumptions stops holding.

Design A: a small online store

Assume 10^6 product-page reads and 10^4 orders per day. Use roughly 10^5 seconds per day and an illustrative peak factor of ten:

  • Product reads average roughly ten per second and peak around a hundred.
  • Orders average roughly one tenth per second and peak around one.

Start with measured application capacity, a relational database with backups, and an appropriate entry point. Keep stock changes and order creation transactional.

Repeated browsing queries may justify a cache if they become expensive. The cache shouldn’t authorize stock reservations. These request estimates alone don’t justify sharding, although failure requirements may justify redundant instances at low traffic.

Design B: a photo-sharing app

Assume 10^5 uploads per day, each averaging 2 × 10^6 bytes:

original bytes/day ≈ 2 × 10^11 ≈ 200 GB
30-day originals ≈ 6 × 10^12 ≈ 6 TB

The retained image bytes suggest object storage. Metadata can still fit a manageable database design:

Give uploads explicit status so incomplete operations can be cleaned up. Then evaluate changes against their purpose:

  • CDN delivery helps reusable content and geographic access.
  • Background workers help when resizing makes synchronous requests miss their targets.
  • Ownership checks control private download access.
  • A suitable read path preserves the writer’s freshness expectation.

A large image store doesn’t automatically imply a huge or heavily written metadata database.

Design C: a background-job service

For 10^6 jobs per day, the rounded average is ten per second. Suppose the assumed peak is a hundred, and tests show a worker completes ten per second.

Ten workers only match the peak. They don’t leave spare capacity.

Use a durable queue, workers, and durable job state. Then define the failure behavior:

  • Set a maximum acceptable queue age.
  • Make side effects repeat-safe because delivery may repeat.
  • Bound retries and increase retry delays with random variation, often called jitter.
  • Separate repeatedly failing jobs so they don’t block healthy work.

Amazon’s timeouts and retries guide explains how retries can amplify overload if the design ignores their additional work.

Make growth decisions reviewable

A useful review connects an observed limit to a candidate change and the evidence needed to evaluate it:

Observed problemCandidate changeEvidence to collect
Application CPU is saturatedOptimize or add application capacityProfiles and load tests
Repeated reads overload storageAdd a suitable cacheRead patterns and expected hit rate
Faraway downloads are slowUse edge deliveryTransfer volume and geographic timings
Stale reads confuse writersChange read routingLag and user-visible failures
One database reaches a demonstrated limitConsider partitioning or shardingData size, write load, skew, and operational cost

These are candidates to investigate, not automatic prescriptions. Recheck the whole path after changing one part.

For a project you know, write five lines:

  • Main operation.
  • Assumed peak demand.
  • Data growth and retention.
  • Correctness rule.
  • First failure to tolerate.

Use those lines to explain each component you add. The estimation reference keeps conversions and formulas nearby; the architecture still needs your account of which work runs where and which guarantees survive a failure.


Previous: Replication and Consistency: Leaders, Quorums, and CAP. Reference: Powers-of-ten estimation cheat sheet.