Sub topic 8
Scaling the data tier: replicas and sharding
This chapter assumes you know what a relational database does, how a web server talks to it, and why application servers can be made stateless (covered in the previous chapter). It focuses on why the database is harder to scale out than the application tier, and on the two main techniques for doing it: read replicas and sharding.
Why the data tier is different
Stateless application servers are interchangeable. Any server can handle any request, so adding a server adds capacity. A database holds the state that every request depends on. You cannot clone it and send requests to any copy, because the copies would disagree about what the data is.
The first move is usually vertical: a bigger database machine with more memory, faster disks, and more CPU. This works for a long time and adds no application complexity. When it stops being enough, or becomes too expensive, you scale out with one of two techniques that solve different problems.
| Problem | Technique | What it spreads |
|---|---|---|
| Too many reads | Read replicas | Read queries across copies of the same data |
| Too many writes, or data too large for one machine | Sharding | The data itself, split across machines |
Before choosing, check which problem you have. Many web applications read ten to a hundred times more than they write. For them, replicas and caching come first. Sharding is a larger change and is usually the last resort.
Read replicas
A read replica is a copy of the database that receives every change from the primary and serves read-only queries. The primary is the single node that accepts writes. This design is called single-leader replication (also called primary-replica or leader-follower).
The primary records each change in a log. Replicas read that log and apply the changes in order. The application sends writes to the primary and spreads reads across the replicas.
Read replicas give you three things:
- More read throughput. Each replica adds roughly one more machine's worth of read capacity.
- Some availability. If the primary fails, a replica can be promoted to take its place.
- Workload isolation. Slow reporting queries can run on a dedicated replica without slowing down user traffic.
They do not help with write throughput. Every replica must apply every write, so the primary's write load is the same however many replicas exist. Replicas also do not reduce the total data size, because each one stores a full copy.
Replication lag
Replication is usually asynchronous: the primary confirms a write to the client without waiting for replicas to apply it. This keeps writes fast, but a replica can be a few milliseconds, or under heavy load several seconds, behind the primary. That delay is replication lag. A system where reads may return slightly old data is eventually consistent. If replicas stop receiving changes, they eventually catch up, but at any given moment they may differ from the primary.
Lag causes visible bugs. The classic one is read-your-own-writes failure:
- A user changes their display name. The write goes to the primary.
- The page reloads and the read goes to a replica that has not yet applied the change.
- The user sees the old name and assumes the save failed.
Common mitigations:
- Read from the primary for a short window after a user writes, or for data the user just changed.
- Route reads that must be fresh (account balance, inventory count before checkout) to the primary.
- Track the replication position (such as a log sequence number) from the write and only read from a replica that has reached it.
- Use synchronous replication to one replica. Writes become slower and a slow replica can block them, so this is a deliberate trade for stronger guarantees.
A second form of anomaly appears when consecutive reads hit different replicas with different lag. A user can see a new comment, refresh, and see it vanish. Pinning each user's session to one replica avoids this.
Routing reads and writes
Something must decide which queries go where. Options include separate connection pools in the application (one for the primary, one for replicas), a database proxy that inspects statements, or a driver feature. Any approach needs to treat a read inside a transaction that also writes as a primary query. The simplest rule is explicit: the code that needs fresh data asks for the primary connection.
The pool of replicas can be balanced with the same ideas as the application tier. This is round-robin assignment, shown in miniature below.
from itertools import cycle
servers = ["app-1", "app-2", "app-3"]
pool = cycle(servers)
for request_id in range(5):
print(request_id, "->", next(pool))The output assigns requests to app-1, app-2, app-3, app-1, app-2. Replace the names with replica hosts and you have a basic read balancer. Real balancers also remove replicas whose lag exceeds a threshold or whose health checks fail.
Failover and its risks
If the primary dies, a replica must be promoted. This is failover. It raises several edge cases:
- Because replication is asynchronous, the promoted replica may be missing the last few writes the old primary confirmed. Those writes are lost, or must be reconciled by hand.
- If the old primary comes back and still believes it is the primary, two nodes accept writes. This is split brain, and it corrupts data. Systems prevent it by fencing the old primary, for example by cutting its network or storage access, before promoting a new one.
- Failover timeouts that are too short cause needless promotions during brief network hiccups. Timeouts that are too long extend the outage.
Managed database services automate most of this, but you still need to know the guarantees they give, especially how much data loss is possible during failover.
Sharding
Sharding (also called horizontal partitioning) splits a dataset into pieces called shards. Each shard holds a subset of the rows and lives on its own database server. Each shard is typically also replicated for availability. Unlike replicas, shards hold different data, so write load and data volume are divided across machines.
Choosing a shard key
The shard key is the column whose value decides which shard a row lives on. It is the most important decision in a sharded design, and changing it later is expensive because it means moving data. A good key has these properties:
- High cardinality: many distinct values, so data can spread across many shards.
- Even distribution of both data and traffic.
- Matches the dominant access pattern, so most queries touch one shard.
For a multi-tenant application, tenant_id is a common choice because most queries are scoped to one tenant. For a consumer app, user_id often works.
Sharding strategies
| Strategy | How it assigns rows | Strength | Weakness |
|---|---|---|---|
| Range | Contiguous key ranges per shard | Efficient range scans | Hot spots, such as all new rows going to the newest range |
| Hash | Hash of the key, modulo the number of shards | Even spread | Range queries must hit every shard |
| Directory (lookup) | A table maps each key to a shard | Full flexibility, easy to move one tenant | The lookup service is a new component that must itself be reliable |
A naive hash scheme, hash(key) % N, has a trap. When N changes from 3 to 4, most keys map to a different shard, so almost all data must move. Consistent hashing, or a fixed large number of logical partitions mapped to physical servers, limits movement to a small fraction of the keys when you add capacity. Many systems create, say, 1024 logical partitions up front and move whole partitions between machines.
What sharding costs you
Sharding trades capability for scale. Expect these problems:
- Cross-shard queries. A join or aggregate over data on several shards needs scatter-gather: query every shard, then combine results in the application or a coordinator. This is slower and more complex than a single-node query.
- Cross-shard transactions. Atomic updates across shards need distributed protocols such as two-phase commit, which are slow and can block on failures. Designs usually try to keep each transaction inside one shard.
- Hot shards. A celebrity account or one very large tenant can overload a single shard while others sit idle. Even a good key does not guarantee even load.
- Resharding. Splitting a shard that has grown too large, or rebalancing, is operationally risky and often must happen with live traffic.
- Global constraints. Unique constraints and auto-increment IDs that were free on one node now need coordination, or ID schemes such as UUIDs or time-ordered IDs that need none.
- Operational load. Backups, schema migrations, and monitoring now multiply by the number of shards.
Because of this, exhaust simpler options first: query and index tuning, caching, a larger primary, and read replicas. Some databases (such as distributed SQL systems and many NoSQL stores) handle sharding internally, which moves part of this burden from your application to the database.
Caching as a data tier technique
A cache such as Redis or Memcached stores the results of frequent reads in memory, in front of the database. A cache hit never reaches the database, so it can remove most read load more cheaply than replicas. The cost is staleness and invalidation: you must decide when cached data expires or is deleted after a write. Like replicas, caches can return old data, so the same read-your-own-writes concerns apply.
Putting the data tier together
A typical growth path looks like this:
- Tune queries and add indexes.
- Scale the primary vertically.
- Add a cache for hot reads.
- Add read replicas, with lag-aware routing.
- Move to sharding when write volume or data size exceeds what one primary can hold.
Each step adds complexity, so move to the next only when measurements from earlier chapters, such as primary CPU, disk I/O, and query latency, show that the current step is the limit. A database that is slow because of a missing index will not be fixed by replicas or shards.
Exercises
Exercise
A news site's database primary is at 90% CPU. Monitoring shows 95% of queries are reads, mostly for the same popular articles. Writes are low. Name two data tier techniques that would help and one that would not be justified yet.
Show answer
Read replicas and a cache both help, because the load is read-heavy and repetitive. A cache is especially effective for repeated reads of popular articles. Sharding is not justified: the problem is read volume, not write volume or data size, and sharding adds large complexity.
Exercise
A user posts a comment, the page reloads, and the comment is missing. A few seconds later it appears. The system uses asynchronous read replicas. What is the likely cause, and give two ways to fix it.
Show answer
Replication lag: the write went to the primary, but the reload read from a replica that had not yet applied it. Fixes include reading from the primary for a short time after the user writes, routing that user's reads to the primary, or reading only from a replica that has reached the replication position of the write.
Exercise
A team shards users with hash(user_id) % 4 and later grows to 5 shards. Why is this painful, and what approach reduces the pain?
Show answer
Changing the modulus from 4 to 5 changes the shard for most keys, so most rows must move. Consistent hashing, or a fixed large number of logical partitions that are moved whole between servers, means only a small fraction of the data moves when a shard is added.