Sub topic 11
Scaling storage with replication and sharding
This chapter assumes you know basic SQL, HTTP status codes, and the cache-aside pattern from the caching chapter. It also assumes you have seen the urls table and the idea of allocating IDs in ranges. Here you will learn how to grow the storage layer past one machine.
Why one database is not enough
A URL shortener is read-heavy. Suppose the capacity estimate gave 100 reads for every write. A cache absorbs most reads, but the database still has to handle three things:
- Cache misses, which hit the database directly.
- All writes, which must be durable.
- Recovery after a cache restart, when many requests miss at once.
A single database server can fail in two ways. It can run out of capacity (disk, memory, connections, or write throughput), or it can crash and take the service with it. Replication addresses read load and crashes. Sharding addresses total data size and write throughput. They solve different problems, and a large system usually uses both.
| Technique | Main problem solved | What it does not solve |
|---|---|---|
| Replication | Read throughput, failover | Data size, write throughput |
| Sharding | Data size, write throughput | Failover by itself |
Replication
Replication keeps copies of the same data on several servers. The common setup is leader-follower (also called primary-replica). All writes go to the leader. The leader sends its changes to the followers, and clients can read from the followers.
This fits the URL shortener well. Writes are rare, and a stored mapping never changes after creation (apart from expiry or deletion). That makes the data easy to replicate.
Replication lag
Replication is usually asynchronous. The leader confirms a write to the client before every follower has applied it. The delay between the two is replication lag. It is often milliseconds, but it can grow to seconds under load.
Lag causes a visible bug in this system:
- A user creates a short link. The write goes to the leader.
- The user immediately opens the link.
- The redirect lookup goes to a follower that has not received the row yet.
- The service returns 404 for a link that exists.
There are three common fixes:
- Read-your-writes on the leader. After a create, the service reads that code from the leader, or returns the long URL from the create response and warms the cache with it.
- Fall back on a miss. If a follower returns "not found", retry once on the leader before returning 404.
- Synchronous replication to one follower. The leader waits for one follower to confirm. This cuts the risk of losing a write when the leader fails, but it adds latency to every write and stalls writes if that follower is down.
The fallback is cheap and fits this workload. Misses for codes that really do not exist (typos, scanners) will also reach the leader, so combine this with the abuse protections covered later, or cache "not found" results for a short time.
Failover
If the leader crashes, a follower must be promoted. Promotion is risky for two reasons:
- With asynchronous replication, the chosen follower may be missing the last few writes. Those links are lost, or worse, the new leader may hand out the same ID or code again.
- If the old leader comes back and still believes it is the leader, you have two leaders (split brain).
For a counter-based generator, the second problem is serious because duplicate codes would point to different URLs. The protection is the primary key on short_code. The database rejects a duplicate, and the service must treat that rejection as an error rather than overwrite the row. Production systems also use a coordinator or managed service to elect one leader and fence off the old one.
Sharding
Sharding (also called partitioning) splits the data so that each server holds only a part of it. Each part is a shard. Replication copies the same data. Sharding divides different data across servers.
You need sharding when the data no longer fits on one machine, or when one leader cannot keep up with writes. At typical shortener scale this happens late. Five billion rows of about 500 bytes each is roughly 2.5 TB, which a modern server can hold. Do the arithmetic from your own estimate before you shard, because a sharded system is harder to operate.
Choosing a shard key
The shard key decides which shard stores a row. For lookups by short code, the natural key is short_code. A redirect request carries the code, so the service can compute the shard and query only that one.
The service picks a shard in one of three ways:
| Strategy | How it works | Strength | Weakness |
|---|---|---|---|
| Range | Codes `0-9, A-Z` go to shard 1, and so on | Simple, range scans are easy | Hot spots if codes cluster |
| Hash modulo | `hash(code) % N` | Even spread | Changing N moves most keys |
| Consistent hashing | Keys and servers sit on a ring | Adding a server moves only a fraction of keys | More complex to build |
Range sharding is risky for a counter-based generator. New codes are always the largest numbers, so every write lands on the newest shard while the old shards sit idle. Hashing the code spreads writes evenly.
Hash sharding in code
This example routes a code to a shard with a stable hash. It uses hashlib because Python's built-in hash() for strings changes between runs.
import hashlib
SHARD_COUNT = 4
def shard_for(short_code: str, shard_count: int = SHARD_COUNT) -> int:
digest = hashlib.sha256(short_code.encode()).digest()
return int.from_bytes(digest[:8], "big") % shard_count
for code in ["aZ3k9Q1", "0000001", "0000002", "zzzzzzz"]:
print(code, "-> shard", shard_for(code))Consecutive codes such as 0000001 and 0000002 land on unrelated shards, so sequential writes spread out.
The resharding problem
With hash % N, changing N from 4 to 5 changes the answer for most keys, so most rows must move. Two common ways to avoid this:
- Many logical shards on few servers. Create, for example, 256 logical shards from the start. Map them to physical servers in a table. To add a server, move some logical shards to it and update the table. The hash function never changes.
- Consistent hashing. Place servers at points on a ring. A key belongs to the next server clockwise. Adding a server takes keys only from its neighbor.
The first option is simpler and works well for a shortener. The mapping table is small and can be cached by every application server.
Where the shard is chosen
The shard must be derivable from the short code alone, because the redirect request has nothing else. Two designs achieve this:
- Hash the code. Any server computes the shard. Allocation of codes is independent of placement.
- Embed the shard in the code. The generator reserves a few characters, or a few bits of the ID, to hold the shard number. Lookup is trivial. The cost is that the code format now depends on the shard layout, so changing it later is hard.
Hashing the code is the more flexible choice.
Combining ID allocation with sharding
The distributed ID chapter described giving each application server a range of counter values. This pairs well with sharding. Each server takes a block, for example one million IDs, converts each ID with base62, and then writes the row to the shard chosen by hashing the code. The allocator is a small service that hands out blocks and is not on the read path, so it can use a single consistent store.
If a server crashes with part of its block unused, those IDs are skipped. Gaps are harmless here. The code space is large, so the waste is small.
Trade-offs and failure modes
Sharding gives up things a single database provides:
- No cross-shard transactions. A single create touches one shard, so this is fine. Operations like "list all links by user" do not fit the shard key.
- Secondary indexes. If users need "my links", you need either an index sharded by user ID (a second copy of the data) or a query across all shards. Keep the primary store keyed by code and maintain a separate user-to-codes index.
- Uneven load. A viral link makes one shard hot even with a good hash. The cache absorbs this, which is another reason the read path should rarely reach the database.
- Custom aliases. A user-chosen alias hashes to some shard, and uniqueness is enforced there. This works without cross-shard coordination because the alias is the shard key.
Putting it together
A typical layout has a cache in front, then a routing layer, then several shards. Each shard is a leader with followers.
Common errors
- Using Python's
hash()or another per-process hash to pick shards. Different servers then disagree about where a code lives. - Sharding by creation time or by sequential ID, which concentrates writes on one shard.
- Reading from a follower right after a write and returning 404.
- Forgetting that a promoted follower may have lost recent writes.
- Choosing
hash % Nwith a small N and no plan for growth.
Exercise
Your shortener uses 4 shards chosen by hash(code) % 4. Traffic grows and you move to 5 shards with hash(code) % 5. Roughly what fraction of existing rows must move, and what design choice would avoid most of that movement?
Show answer
About 80% of rows move, because a key stays on its shard only when hash % 4 and hash % 5 agree, which happens for about 1 in 5 keys. Creating many logical shards up front (for example 256) and mapping them to servers through a table avoids this, because adding a server moves whole logical shards and the hash function never changes. Consistent hashing also limits movement to a fraction of keys.
Exercise
A user creates a short link and immediately gets a 404 when opening it. Writes go to the leader and redirects read from followers. Explain the cause and give one fix.
Show answer
Replication lag: the follower that served the redirect has not yet applied the new row. Fixes include retrying a "not found" on the leader before returning 404, reading recently created codes from the leader, or warming the cache with the new mapping at creation time.