Sub topic 9
Scale with Replication, Partitioning, and Caching
This chapter assumes you can read short Python snippets and know how a client, an API server, and a database fit together. It also assumes you have a capacity estimate like the one from the estimation chapter. Here you choose the scaling techniques that estimate calls for and say what each one costs.
Let the numbers pick the technique
Scaling techniques solve different problems. If you apply one without naming the problem, you add complexity and fix nothing.
Take the running example: 10 million daily users, about 579 average write QPS, about 11,574 average read QPS, and about 9.1 TB of new data per year. With a peak factor of 2, writes peak near 1,160 QPS and reads near 23,000 QPS. Two observations follow:
- Reads outnumber writes by about 20 to 1. Reads are the first thing to scale.
- 9.1 TB per year will eventually outgrow one machine's disk. At 1,160 write QPS, a single well-tuned database can still absorb the writes for a while.
| Symptom | Technique | What it fixes | What it costs |
|---|---|---|---|
| Read load too high for one database | Replication, caching | Read throughput, availability | Stale reads, invalidation logic |
| Data too large for one node | Partitioning | Storage and write throughput | Harder queries, resharding |
| Same hot items read repeatedly | Caching | Latency and database load | Consistency risk |
| Node failure causes an outage | Replication | Availability | Replication lag, failover logic |
Replication: copies of the same data
Replication keeps the same data on several nodes. The most common setup is single-leader. All writes go to one leader, which streams changes to followers. Reads can go to any follower.
Replication gives you two things: more read capacity, and a surviving copy if a node dies. It does not give you more write capacity or more storage, because every node holds everything. Teams often forget this.
The key decision is how the leader acknowledges a write:
- Synchronous replication. The leader waits for a follower to confirm before it acknowledges the write. A failover cannot lose acknowledged data, but writes get slower, and a slow or dead follower can block them.
- Asynchronous replication. The leader acknowledges immediately. Writes are fast, but followers lag, and a leader crash can lose the most recent writes.
Many systems use a mix: one synchronous follower and the rest asynchronous.
Lag causes visible bugs. A user posts a comment, the page reloads from a lagging follower, and the comment is missing. Common mitigations:
- Read your own writes from the leader for a short window after a write.
- Route a user's reads to the same follower so they never see time go backwards.
- Accept staleness where the requirements allow it, such as a view counter.
Multi-leader and leaderless designs allow writes on several nodes. They add conflict resolution, so reach for them only when a requirement forces it, such as writes in several regions.
Partitioning: splitting the data
Partitioning (also called sharding) divides the dataset so each node holds only a slice. It is the main way to scale writes and total storage. Each partition is usually replicated as well, so the two techniques combine.
Choose the partition key from the access pattern
The key decides which queries are cheap. Look back at the API sketch: GET /v1/users/{owner_id}/items fetches one owner's items. Partitioning by owner_id keeps that query on one shard. Partitioning by item_id spreads load evenly, but listing a user's items then has to ask every shard (a scatter-gather query), and its latency is set by the slowest shard.
A good key has high cardinality, spreads load evenly, and matches your most frequent queries. A bad key, such as country or creation date, creates hot spots. With a date key, all of today's writes land on one shard.
Hash versus range
- Hash partitioning applies a hash function to the key and maps the result to a shard. It spreads load evenly but destroys ordering, so range scans become scatter-gather.
- Range partitioning assigns contiguous key ranges to shards. Range scans are cheap, but sequential keys such as timestamps concentrate writes on the newest range.
The function below is the hash approach, extended to measure its main weakness:
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
keys = [f"user:{i}" for i in range(10_000)]
moved = sum(1 for k in keys if shard_for(k, 4) != shard_for(k, 5))
print(f"{moved / len(keys):.0%} of keys move when going from 4 to 5 shards")The output is close to 80%. With hash % N, changing N remaps most keys, so adding one shard means migrating most of your data. Two common fixes:
- Consistent hashing places shards and keys on a ring, so adding a shard moves only about 1/N of the keys.
- Many fixed logical partitions. Create, say, 1,024 logical partitions up front and map them to physical nodes through a lookup table. Adding a node means moving whole partitions, and the key-to-partition mapping never changes.
What partitioning takes away
- Joins and transactions across shards become expensive or unavailable.
- Secondary indexes either live per shard (so queries fan out) or are partitioned separately (so writes touch two places).
- A celebrity key can overload one shard even with a good hash. Mitigate by splitting that key, for example by appending a small random suffix and merging the results on read.
Caching: answer from memory
A cache stores the results of expensive reads in fast storage, usually memory, so most requests never reach the database. It works when a small share of items receives most of the reads. With 23,000 peak read QPS, a cache hit rate of 90% leaves about 2,300 reads per second for the database.
The most common pattern is cache-aside. The application checks the cache first, and on a miss it reads the database and fills the cache:
import time
class TTLCache:
def __init__(self, ttl_seconds: float):
self.ttl = ttl_seconds
self.store = {}
def get(self, key):
entry = self.store.get(key)
if entry is None:
return None
value, expires_at = entry
if time.monotonic() >= expires_at:
del self.store[key]
return None
return value
def set(self, key, value):
self.store[key] = (value, time.monotonic() + self.ttl)
def delete(self, key):
self.store.pop(key, None)
database = {"item:1": "hello"}
db_reads = 0
cache = TTLCache(ttl_seconds=30)
def read_item(item_id: str):
global db_reads
value = cache.get(item_id)
if value is not None:
return value
db_reads += 1
value = database.get(item_id)
if value is not None:
cache.set(item_id, value)
return value
def update_item(item_id: str, value: str):
database[item_id] = value
cache.delete(item_id)
for _ in range(100):
read_item("item:1")
print("database reads for 100 requests:", db_reads)
update_item("item:1", "hello again")
print(read_item("item:1"), "| database reads:", db_reads)The first 100 requests cause one database read. After the update, the cache entry is deleted, so the next read fetches the new value.
Where caches fail
- Stale data. A time-to-live (TTL) bounds how stale an entry can get, and deleting the entry on write shortens the window. Deleting is safer than updating the cache in place, because concurrent writers can leave an old value behind.
- Cache stampede. When a popular entry expires, many requests miss at once and all hit the database. Mitigations are request coalescing (one request refills while the others wait), jittered TTLs, and refreshing entries before they expire.
- Cold start. An empty cache sends full load to the database. Plan for warming or gradual rollout.
- Low hit rate. If reads are spread evenly over a huge key space, a cache gives little benefit. Check the access pattern before adding one.
Caches can sit at several levels: the client or CDN for static and public content, an application-level cache like the one above, and the database's own buffer cache. Put each cache as close to the user as the consistency requirement allows.
Putting the three together
Apply the techniques in this order, and stop when the estimate says you are done:
- Start with one database and an index that matches your main query.
- Add a cache if reads are skewed toward hot items.
- Add read replicas if reads still exceed one node.
- Partition only when data size or write rate exceeds what one leader can handle.
Common errors
- Using replication to scale writes. Followers copy every write, so write capacity does not grow.
- Ignoring lag. Sending reads to followers without a plan for read-your-writes gives users missing data.
- Picking a key that creates hot spots. Timestamps, countries, and popular accounts concentrate load.
- Using
hash % Nand expecting painless growth. Name consistent hashing or logical partitions when you mention resharding. - Caching without invalidation. Always state the TTL and what happens on a write.
- Adding all three techniques without numbers. Tie each one to a measured or estimated bottleneck.
Exercise
Exercise
A service has 20,000 peak read QPS and 800 peak write QPS. The dataset is 300 GB and grows by 40 GB per year. Which scaling techniques do you add first, and what do you leave out for now?
Show answer
Add a cache and read replicas first. Reads dominate, so a cache with a high hit rate cuts database reads sharply, and replicas add read capacity and a failover copy. Leave out partitioning. 300 GB fits on one node, 800 write QPS is within a single leader's capacity, and 40 GB of growth per year gives years of room. State the trigger for revisiting: for example, the leader's disk or write throughput passing about 70% of capacity. Also state how you handle replication lag (read your own writes from the leader) and cache staleness (TTL plus delete on write).
Exercise
Why does going from 4 to 5 shards with hash(key) % shard_count move about 80% of keys, and how does a fixed set of logical partitions avoid this?
Show answer
A key stays in place only when its hash gives the same remainder modulo 4 and modulo 5. For a uniform hash that happens for about 20% of keys, so about 80% move. With logical partitions, the key-to-partition mapping uses a fixed count such as 1,024 and never changes. Adding a node moves only whole partitions to it, and the lookup table is updated.