Sub topic 9
Scale with replication, partitioning, and caching
This chapter assumes you have read the earlier chapters on capacity estimation and the high-level architecture. You should be comfortable with HTTP APIs, databases, and short Python snippets.
Once you have a high-level design and a capacity estimate, you can check whether one machine can carry the load. If it can't, three techniques cover most cases: replication, partitioning, and caching. Each one solves a different problem, and each adds its own costs.
Match the technique to the bottleneck
Start from the numbers in your estimate. Then pick the technique that addresses the limit you will hit first.
| Technique | What it does | Problem it solves | Main cost |
|---|---|---|---|
| Replication | Keeps copies of the same data on several nodes | Read load, availability | Copies can disagree (replication lag) |
| Partitioning | Splits data so each node holds a subset | Write load, data size | Cross-partition queries, hot keys |
| Caching | Keeps hot results in fast memory | Read latency, database load | Stale data, invalidation |
Take the estimate from the capacity chapter. With 10 million daily users, 5 writes and 100 reads each, and 500-byte records, you get roughly 579 average write QPS and 11,574 average read QPS. Storage grows by about 25 GB per day, or about 9.1 TB per year. Reads outnumber writes by about 20 to 1. A single database can usually handle 579 writes per second, so writes are not the first problem. Reads are. Storage of 9.1 TB per year will eventually need partitioning, but not on day one.
Replication
Replication copies data to several nodes. In the common leader-follower setup, all writes go to one leader. The leader streams changes to followers, and clients read from the followers.
- Reads scale by adding followers.
- If the leader fails, a follower can be promoted.
- Followers lag behind the leader. A user may write a value and then read an older one from a follower.
To handle that last case, route a user's reads to the leader for a short time after they write. This gives read-your-writes behavior without making every read hit the leader. State which consistency guarantee you chose, because it is a trade-off you will need to defend later.
Partitioning
Partitioning (also called sharding) splits data across nodes by a key. Each node owns a subset, so both storage and write traffic are spread out.
The simplest approach is hash-based partitioning:
import hashlib
def shard_for(key: str, shard_count: int) -> int:
digest = hashlib.md5(key.encode("utf-8")).digest()
return int.from_bytes(digest[:8], "big") % shard_count
print(shard_for("user:42", 4))
print(shard_for("user:43", 4))Hashing spreads keys evenly, but changing shard_count remaps most keys. Adding a shard then means moving a large share of your data. Consistent hashing reduces that movement, so mention it when you expect the cluster to grow.
Common errors with partitioning:
- Choosing a poor partition key. If you shard by date, all of today's writes land on one shard. Pick a key that matches the access pattern and spreads load, such as
owner_id. - Hot keys. One celebrity account can overload a shard even when keys are spread evenly.
- Cross-partition queries. A query that needs data from every shard is slow and fragile. Design the data model so the common queries touch one partition.
Caching
A cache stores the results of expensive reads in fast memory. The usual pattern is cache-aside: the application checks the cache, falls back to the database on a miss, then fills the cache.
cache = {}
def get_item(item_id, db):
if item_id in cache:
return cache[item_id]
item = db.get(item_id)
cache[item_id] = item
return itemA production cache also needs an expiry time (TTL) and a size limit with an eviction policy such as least recently used (LRU). Writes need a rule. You can delete the cached entry on write, or use a short TTL and accept brief staleness. Decide which one fits the requirements.
Apply them in order
Add techniques one at a time, starting with the cheapest. For a read-heavy system, a typical order is:
- Add a cache in front of the database.
- Add read replicas.
- Partition when storage or writes outgrow one leader.
Justify each step with a number from your estimate.
Exercise
Your service has 300 write QPS, 15,000 read QPS, and 2 TB of data. Which technique do you add first, and why? Name one cost of it.
Show answer
Add caching first, followed by read replicas if needed. Reads dominate by 50 to 1, and the write rate and data size fit on one leader. The cost of a cache is stale data and the need for an invalidation or TTL rule. Replicas cost replication lag.