Sub topic 11
Scaling storage with replication and sharding
This chapter assumes you know the urls table from the data model chapter, the cache-aside read path, and how ID ranges are handed to servers. Here you will see what happens when one database server can no longer hold the data or serve the traffic.
Why one database stops being enough
Suppose the service stores 100 million new links a year at about 500 bytes per row. After five years that is roughly 250 GB, which a single server can hold. The first limit you are likely to hit is read throughput, not disk space. Redirects outnumber link creations by a large factor, and the cache absorbs most of them, but cache misses and cold starts still reach the database.
Two techniques address different limits:
| Technique | What it does | Solves |
|---|---|---|
| Replication | Copies the whole dataset to several servers | Read throughput, failover |
| Sharding | Splits the dataset across servers | Write throughput, total storage |
Replication for the read path
In leader-follower replication, all writes go to one leader. The leader streams changes to followers, and redirect lookups can be served by any follower.
Replication is asynchronous in most setups, so a follower may lag behind the leader by milliseconds or more. For a URL shortener this matters in one place. A user creates a link and immediately opens it, and the lookup hits a follower that has not received the row yet. The user sees a 404 for a link that exists.
Two common fixes:
- Read from the leader for a short time after a write, or for codes the same client just created.
- Return the new link only after at least one follower has confirmed the write.
Links are almost never updated after creation, so replication lag causes few other problems.
Sharding by short code
When the leader cannot keep up with writes, or the data outgrows one machine, split the table into shards. Each shard is an independent database that holds a subset of the rows.
The natural shard key is short_code. Every redirect already knows the code, so the router can compute the shard without a lookup table. Hash the code before taking the remainder. Taking it directly would cluster sequential codes on one shard.
import hashlib
def shard_for(short_code: str, num_shards: int) -> int:
digest = hashlib.sha256(short_code.encode()).digest()
return int.from_bytes(digest[:8], "big") % num_shards
if __name__ == "__main__":
for code in ["0000001", "0000002", "aB3xK9z"]:
print(code, "->", shard_for(code, 4))Use hashlib here, not Python's built-in hash(). The built-in value changes between processes for strings, so two servers would route the same code differently.
Common problems
- Resharding. With
hash % N, changing N moves most codes to a different shard. Consistent hashing, or a fixed set of many small virtual shards mapped onto servers, lets you add machines and move only a fraction of the data. - Hot shards. A viral link sends heavy traffic to one shard. The cache handles most of this, because a single popular code is cheap to cache.
- Cross-shard queries. Listing all links for one user needs data from every shard. Keep a separate index keyed by user if you need it.
- Counter-based codes. If each app server takes a range of IDs, the ID has no relation to the shard. Hash the encoded code to choose the shard, not the numeric range.
Exercise
A team shards with hash(short_code) % 4 and then adds a fifth server, changing the formula to % 5. Why is this expensive, and what approach avoids it?
Show answer
Changing the modulus remaps most codes to a different shard, so most rows must move. Consistent hashing, or many virtual shards assigned to servers, moves only about 1/5 of the data when a server is added.