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
- Work through a placement change
- Fixed logical buckets and hash rings are distinct tools
- Make the router aware of ownership
- Review three architectures against requirements
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.
| Technique | What it does | What it does not automatically solve |
|---|---|---|
| Replication | Makes extra copies | Dividing a dataset that is too large for one node |
| Sharding | Splits ownership across nodes | Keeping 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:
| Candidate | Benefit | Problem |
|---|---|---|
| User ID | One user’s photos stay together | A very active user can create a hot shard |
| Photo ID | Can distribute individual photos | Listing a user’s photos may need another index or multiple shards |
| Upload date | Convenient time ranges and retention | New 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:
| h | Three shards: h % 3 | Four shards: h % 4 | Moves? |
|---|---|---|---|
| 0 | 0 | 0 | No |
| 1 | 1 | 1 | No |
| 2 | 2 | 2 | No |
| 3 | 0 | 3 | Yes |
| 4 | 1 | 0 | Yes |
| 5 | 2 | 1 | Yes |
| 6 | 0 | 2 | Yes |
| 7 | 1 | 3 | Yes |
| 8 | 2 | 0 | Yes |
| 9 | 0 | 1 | Yes |
| 10 | 1 | 2 | Yes |
| 11 | 2 | 3 | Yes |
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 node | Before | After adding D |
|---|---|---|
| A | Buckets 0, 1, 2, 3 | Buckets 0, 1, 2 |
| B | Buckets 4, 5, 6, 7 | Buckets 4, 5, 6 |
| C | Buckets 8, 9, 10, 11 | Buckets 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 hash | Before | After |
|---|---|---|
| 10 | A | A |
| 30 | B | D |
| 50 | B | B |
| 70 | C | C |
| 95 | A | A |
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:
- Copying: the old owner stays authoritative while a snapshot is copied.
- Catching up: transfer newer changes until the destination is ready.
- Cutover: coordinate routing versions and write authority.
- Verification: compare expected data and observe the new path.
- 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
- State the main operations.
- Name correctness and freshness requirements.
- Estimate reads, writes, bytes, and peaks.
- Draw a simple path.
- Walk through a failure.
- 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 problem | Candidate change | Evidence to collect |
|---|---|---|
| Application CPU is saturated | Optimize or add application capacity | Profiles and load tests |
| Repeated reads overload storage | Add a suitable cache | Read patterns and expected hit rate |
| Faraway downloads are slow | Use edge delivery | Transfer volume and geographic timings |
| Stale reads confuse writers | Change read routing | Lag and user-visible failures |
| One database reaches a demonstrated limit | Consider partitioning or sharding | Data 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.