Spread reads across replicas
A single primary database cannot keep up with read traffic.
Say it like this
Reads dominate, so I send them to read replicas and keep the primary for writes and for any read that must see the latest commit.
Basic solution
Replicate the primary to one or more read replicas and route read-only queries to them.
Route by intent: writes to primary, reads to replicas
The service keeps two pools. Writes and read-after-write go to the primary; all other reads spread across replicas that apply the primary log asynchronously.
How it works
- The primary database runs each write transaction, appends the change to its write-ahead log, and commits. The log is the ordered record of every change, so it is also what replicas copy.
- Each replica streams that log from the primary and applies the same changes to its own copy of the data, usually within tens of milliseconds of the commit, sometimes seconds when the primary is under heavy write load.
- The application keeps two connection pools: one pointing at the primary for writes, and one pointing at a replica endpoint, usually a load balancer that spreads queries across several replicas, for reads.
- Every query is sent to one pool or the other based on what it needs. Writes go to the primary. Reads that must see the caller's own just-committed write also go to the primary. Every other read goes to the replica endpoint.
- More read capacity means adding another replica to the endpoint. If the primary fails, one replica is promoted to become the new primary and the write pool is repointed at it.
Async vs sync
- With asynchronous replication the primary commits without waiting for any replica, so writes are fast and a slow replica does not slow anyone, but a replica can lag behind and the last few commits can be lost if the primary dies before shipping them. With synchronous replication the primary waits until at least one replica confirms it has the change, so writes are slower but nothing that was committed can be lost on failover.
Worked example
URL shortener
- 40 writes/s and 4,000 reads/s on average, 40K reads/s at peak. A single Postgres primary can serve tens of thousands of simple point reads per second, but at that rate it has no headroom left for writes, for vacuum, or for the moment the cache restarts cold.
- Put 3 replicas behind one read endpoint. After the Redis cache absorbs 95% of reads, peak database reads are about 2K/s, so each replica sees about 700/s. That leaves room for a cache outage: 40K/s spread over 3 replicas is about 13K/s each, which they can carry.
- Replication lag at 40 writes/s is under 50 ms. A link created and then read from a replica within those 50 ms would return 404, so the creation response is built from the primary write and the redirect path treats one miss as temporary.
- Failover: promote a replica and repoint the primary endpoint. With async replication the last few in-flight writes may be lost; for links that means a user has to retry creating one.
Variants and when each wins
Asynchronous replicas
- The primary commits without waiting for replicas, which copy the log a moment later. It is the default: fast writes and cheap to add, with reads that can be a few milliseconds to a few seconds stale.
Synchronous (at least one replica confirms)
- The primary waits for one replica to write the change before acknowledging. It wins for money and anything users would notice losing, because no committed write can be lost on failover; the cost is one extra network round trip on every write.
Read replicas plus a cache
- The cache serves most reads and the replicas serve the rest, including everything when the cache is cold. It wins almost always, because the two layers cover each other's weak moment.
Multi-region replicas
- Replicas in other regions serve local reads at local latency. It wins for a global read-heavy product, but lag is now a cross-continent round trip and the primary is far from some of the writers.
Recommendation: async replicas by default, one synchronous replica when you cannot lose a committed write, and read-after-write routed to the primary.
Failure modes
Read-your-writes violation
- You notice a user creates something, refreshes, it is missing, and then it appears a second later. It happens because the refresh was served by a replica that had not yet applied the write. Fix it by pinning that user's reads to the primary for a few seconds after any write, or by recording the primary's log position for the write and only using a replica whose replay position has passed it.
Replica lag spikes
- You notice replicas serving data that is minutes old. It happens because a long transaction or a bulk write on the primary produced more log than the replica can apply, or because the replica is under-sized. Fix it by monitoring lag, automatically removing a lagging replica from the read endpoint, and breaking bulk writes into batches.
Failover data loss
- You notice the most recent writes are missing after a replica was promoted. It happens because replication was asynchronous and the old primary died before shipping its last commits. Fix it with a synchronous replica for the tables that matter, or accept the loss and make clients retry writes that were not acknowledged.
Primary still the bottleneck
- You notice adding replicas does not reduce load on the primary. It happens because the load is writes, which every replica must also apply, or because the application is sending reads to the primary pool by mistake. Fix it by checking the routing first; if writes are the limit, shard the data across several primaries.
Connection explosion
- You notice "too many connections" errors. It happens because every application instance opens a full pool to every replica, so connections multiply with both. Fix it with a connection pooler such as PgBouncer, or a single replica load-balancer endpoint so each instance opens one pool.
Interviewer follow-ups
Answer out loud before you open each one.
How do you make sure a user sees their own write?
Route that user to the primary briefly after any write, using a short-lived session marker, or record the primary log position returned by the write and only use a replica whose replay position has passed it. Other users can read from replicas as normal.
How much replication lag is normal and what would you alert on?
Tens of milliseconds for a healthy in-region replica; seconds during bulk writes. Alert at a threshold the product notices, often one to five seconds, and remove a replica from the read pool automatically if it exceeds it.
When do replicas stop helping?
When the bottleneck is writes, since every replica must apply every write too. At that point you shard the data across primaries or move write-heavy data to a store built for it.
What happens during a failover?
Health checks detect the dead primary, a replica is promoted, and the write endpoint is repointed; connections drop and reconnect, so writes fail for some seconds. With async replication the last few commits can be lost, which is why retry-safe (idempotent) writes matter.
Connections
- In study paths
- Scaling reads
- Built on
- Write-ahead log
- Pairs with
- Cache the hot reads · Let users see their own writes · Survive losing a node · Pool database connections
- Pulls against
- Partition the data
- Used in
- URL Shortener (TinyURL / bit.ly) · Chat App (WhatsApp / Messenger)
The same parts on other clouds
The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.
| AWS | Used here as | Google Cloud | Microsoft Azure | Open source and others |
|---|---|---|---|---|
| Amazon EC2 Auto Scaling | Service | Compute Engine managed instance groups | Virtual Machine Scale Sets | Kubernetes Deployment with a HorizontalPodAutoscaler, Nomad |
| Amazon Aurora | Primary, Replica 1, Replica 2, Replica 3 | AlloyDB for PostgreSQL, Cloud SQL | Azure Database for PostgreSQL or MySQL | PostgreSQL, MySQL, CockroachDB |