Sub topic 8
Scaling the data tier: replicas and sharding
This chapter assumes you know what a relational database does, how a web tier talks to it, and the idea of stateless application servers from the previous chapter. It covers the main techniques for scaling a database: vertical scaling, read replicas, caching, and sharding.
Why the data tier is harder
Stateless application servers can be cloned freely because they hold no data of their own. A database holds the single source of truth, so adding a second copy raises a question: which copy is correct? Every technique below is a different answer to that question. Each one gives up some simplicity or consistency in return for capacity.
Start by checking what is actually limited. A database can run out of CPU, memory, disk I/O, connections, or storage space. The metrics from earlier chapters tell you which one. Also check the ratio of reads to writes, because it decides which technique helps.
Step 1: scale up and tune first
Before adding machines, try the cheap options. Add indexes for slow queries, fix queries that scan whole tables, and use a connection pooler so that many app servers do not exhaust the database's connection limit. Moving to a larger instance (vertical scaling) is often the simplest next step and needs no application changes.
Step 2: read replicas
A read replica is a copy of the primary database that receives its changes by replication and serves only read queries. The primary still handles every write.
This works well for read-heavy workloads such as product catalogs or news pages, where reads often outnumber writes ten to one or more. It does not help a write-bound system, because every replica must still apply every write.
Replication lag
Replication is usually asynchronous. A write is confirmed on the primary first and reaches replicas a little later. That delay is replication lag. A replica can therefore return stale data.
A common failure: a user updates their profile, the page reloads, and the read goes to a replica that has not yet received the change. The user sees the old value. Common fixes:
- Read from the primary for a short time after a user writes.
- Route reads that need fresh data (checkout, balances) to the primary always.
- Accept stale reads where they are harmless, such as view counts.
Replicas also help availability. If the primary fails, a replica can be promoted to take its place, though with asynchronous replication the last few writes may be lost.
Step 3: caching
A cache such as Redis or Memcached keeps hot query results in memory. It takes read load off the database in the same way replicas do, and it is faster. It adds an invalidation problem: when the data changes, the cached copy must be updated or expire. Many systems use both a cache and replicas.
Step 4: sharding
When writes or total data size exceed what one primary can handle, you need to split the data. Sharding (also called horizontal partitioning) divides rows across several independent databases, each holding a subset. Each shard has its own primary, so writes scale too.
A shard key decides where a row lives. Here is a minimal hash-based router:
import hashlib
SHARDS = ["db-0", "db-1", "db-2", "db-3"]
def shard_for(user_id: str) -> str:
digest = hashlib.sha256(user_id.encode()).hexdigest()
return SHARDS[int(digest, 16) % len(SHARDS)]
for uid in ["alice", "bob", "carol", "dave"]:
print(uid, "->", shard_for(uid))The same key always maps to the same shard. Common strategies are:
| Strategy | How it works | Strength | Weakness |
|---|---|---|---|
| Hash | Hash the key, take the remainder | Even spread | Range queries hit every shard |
| Range | Key ranges per shard (A–F, G–M) | Range queries are efficient | Hot spots if keys cluster |
| Directory | A lookup table maps keys to shards | Flexible placement | The lookup table is a new dependency |
Costs of sharding
Sharding is powerful but expensive in complexity. Expect these problems:
- Hot shards. A poor key, such as a date, sends all new writes to one shard.
- Cross-shard queries. Joins and aggregates across shards are slow or must be done in application code.
- Transactions. A transaction that spans shards needs distributed coordination, which is slow and hard to get right.
- Resharding. With
% len(SHARDS), adding a fifth shard remaps most keys, so data must move. Consistent hashing or a directory reduces this.
Summary of the ladder
| Technique | Scales | Main cost |
|---|---|---|
| Bigger instance | Reads and writes, up to a ceiling | Price, single point of failure |
| Read replicas | Reads | Replication lag |
| Cache | Reads | Invalidation |
| Sharding | Writes and storage | Query, transaction, and operations complexity |
Exercise
An online store's database is at 90% CPU. Monitoring shows 95% of queries are reads, and the data fits comfortably on one machine. Which technique should you try first, and what problem must the application handle afterward?
Show answer
Add read replicas (and possibly a cache) and send read queries to them. Sharding is unnecessary because writes and data size are not the limit. The application must handle replication lag, for example by reading from the primary right after a user's own write or for data that must be fresh, such as checkout.
Exercise
A team shards orders by the order's creation date, one shard per month. Why is this a poor shard key for write scaling?
Show answer
All new orders have the current month's date, so every write goes to the same shard. That shard becomes a hot spot while the others sit idle, and write capacity does not grow. A key such as a hash of customer ID spreads writes more evenly.