What Is Database Replication - and When a Single Database Is Still the Right Answer
Database replication is keeping more than one copy of your data on more than one database server, and having changes made on one copy flow automatically to the others. That is the whole idea: one database accepts writes, and something ships those changes to one or more other machines so they end up holding the same rows.
It exists to solve two problems that a single database cannot solve by itself. The first is survival: if the only machine holding your data dies, you have an outage and possibly data loss. The second is read capacity: a single server has a fixed number of CPUs, a fixed amount of RAM for cache, and a fixed disk, and at some point your read traffic exceeds what it can serve while still committing writes promptly.
What replication does not solve is write capacity. In almost every replication setup you will meet, writes still go to exactly one machine. Confusing "I added replicas" with "I scaled my database" is the single most expensive misreading of this topic, and it is the reason this page spends as much time on the limits as on the mechanism.
| Concept | Database replication (sometimes just "replication"; the copies are "replicas" or "read replicas") |
|---|---|
| Where it sits | Data layer - sits underneath your application, between one database server and its copies |
| In one sentence | Replication copies every change from a primary database to one or more secondary databases, so you can survive losing a machine and serve reads from more than one of them. |
The 60-Second Answer
What it does: a primary database records every change it commits, and replicas continuously pull that change stream and apply it, ending up with the same data.
The problem it solves: losing one machine no longer means losing your data or your service, and read-heavy traffic can be spread across copies instead of hammering one box.
The cost it adds: replicas are behind, by an amount you do not control. Your application now has to answer "is a slightly stale read acceptable here?" at every query site, and get it right.
If you take one thing: replication scales reads and durability, not writes. All writes still land on one primary.
How It Actually Works
The mechanism, step by step
- 1. The primary writes an ordered log of every change it commits
- 2. The replica connects, states its position, and streams forward
- 3. The replica applies the changes locally - and that step is where lag is born
- 4. Synchronous vs asynchronous is a choice about whose latency you spend
- 5. Reads from a replica are reads from the past
- 6. Failover is promotion, and it is not free
- 7. Multi-primary moves the problem rather than removing it
1. The primary writes an ordered log of every change it commits
The change stream is the foundation
Replication does not copy files or diff tables. The primary already maintains an append-only log of committed changes for crash recovery, and replication reuses it. Every committed change gets an entry, and entries are strictly ordered, so a replica that applies them in order from a known position reaches exactly the state the primary was in at that position.
This ordering is why replication works at all. The replica does not need to understand your schema, your transactions, or your application. It needs one number: how far through the log it has got.
⚠️ In production — That log is on disk on the primary, and it is finite. If a replica falls far enough behind that the log segments it still needs have been rotated away, it cannot catch up incrementally - you have to rebuild it from a fresh copy of the data. On a large database that rebuild is measured in hours, and it happens at exactly the worst time, because replicas fall behind during load spikes.
2. The replica connects, states its position, and streams forward
A long-lived pull, not a push
A replica opens a connection to the primary and says, in effect, "I am at position X, send me everything after that." The primary streams log entries as they are produced, and the connection stays open. There is no polling interval to tune and no batch job.
Because the replica tracks its own position durably, this survives restarts and network blips. It reconnects, names its position, and resumes.
⚠️ In production — The replica is a client of the primary, which means the primary is now doing work on its behalf: holding a connection, reading log segments, and sometimes retaining log data it would otherwise have discarded. Add enough replicas and the primary's outbound network and disk reads become a real line item, not a rounding error.
3. The replica applies the changes locally - and that step is where lag is born
Receiving is fast; applying can be slow
Receiving the log is cheap. Applying it is not: the replica has to perform the same writes, update the same indexes, and flush the same pages that the primary did. If the primary committed those changes using many parallel connections and the replica applies them with less parallelism, the replica does the same work with less concurrency and falls behind.
Replication lag is the gap between what the primary has committed and what the replica has applied. It is not a constant. It is near zero on an idle system and grows under exactly the write bursts you care about.
⚠️ In production — A single expensive statement on the primary can stall the whole apply stream. One UPDATE touching millions of rows, or a schema change that rewrites a table, commits once on the primary but may serialise on the replica while everything behind it waits. Your "a few milliseconds of lag" assumption becomes minutes, for every query routed to that replica.
4. Synchronous vs asynchronous is a choice about whose latency you spend
Commit now and risk loss, or wait and be sure
In asynchronous replication the primary commits and replies to the client immediately, then ships the change whenever it can. Writes are fast; if the primary dies before shipping a change, that change is gone.
In synchronous replication the primary waits for at least one replica to confirm it has the change before telling the client the write succeeded. Nothing committed is lost, but every write now pays a network round trip, and you have coupled your write latency to the health of another machine.
Most systems default to asynchronous, which is why most teams have a data-loss window they have never measured.
⚠️ In production — Naive synchronous replication to a single replica can turn that replica into a hard dependency: if it stops acknowledging, writes stall. Production setups almost always need a rule like "wait for any one of these N replicas" plus a timeout policy - and then you have to decide what the timeout does, because falling back to async at that moment silently reopens the data-loss window.
5. Reads from a replica are reads from the past
The consistency problem lands in your code
Once you route reads to replicas, a user can write a row and then immediately fail to read it back, because their read went to a replica that has not applied it yet. This is not a bug in replication. It is replication working as designed.
The fix is per-query intent, not a global setting. Reads that follow a user's own write go to the primary; reads that tolerate staleness go to replicas.
# The routing decision belongs at the call site, not in config
user = db.primary.get_user(user_id) # just updated their profile
feed = db.replica.get_recommendations() # stale by a second is fine
⚠️ In production — This bites hardest in the write-then-redirect pattern: form submits, you redirect, the next page reads from a replica and renders the old value. It reproduces inconsistently in development because lag is near zero on an idle laptop, and it shows up in production as "my change didn't save" tickets that you cannot reproduce.
6. Failover is promotion, and it is not free
Deciding who is primary is the hard part
A replica becomes useful for availability only when something can promote it to primary and point clients at it. That means detecting that the old primary is gone, choosing which replica to promote, reconfiguring clients, and dealing with whatever the old primary does when it comes back.
Under asynchronous replication, promotion is also a decision to discard: any change the old primary committed but had not shipped is lost by the promotion.
⚠️ In production — The genuinely dangerous case is split brain - the old primary is alive but unreachable, still accepting writes, while a replica has been promoted. Now you have two divergent databases and no automatic way to merge them. This is why failover tooling is built around quorum and fencing rather than a simple health check, and why "we'll just promote a replica manually" is a plan that works until the one time the network, not the machine, is what failed.
7. Multi-primary moves the problem rather than removing it
Two writers means conflicts you must resolve
If you let two machines accept writes for the same data, two users can modify the same row in two places at the same time, and no ordering decides who was right. Someone has to resolve that conflict: last-writer-wins, application-level merge, or data types designed to merge deterministically.
This is a real and sometimes necessary design - geographically split writes, or offline-first clients - but it changes the question from "how do I copy data" to "what does my business want to happen when two people edit the same thing." That is a product decision, not an infrastructure one.
⚠️ In production — Last-writer-wins is the default in many systems and it silently discards data. It also depends on comparing timestamps from different machines, which is only as trustworthy as their clock synchronisation. If you cannot say out loud which write you want to lose, you are not ready for multi-primary.
## Where You Meet It
- A content site where the same articles are read far more often than they are written. One primary takes editorial writes; several read replicas serve the public pages, and each replica also warms its own cache of the hot rows. Lag of a few seconds on a published article is invisible to readers, so almost all traffic can be served off replicas safely.
- An operational database with an analytics problem. Someone's dashboard runs a query that scans half a table, and it competes with transactional traffic for the same CPU and cache. Pointing the reporting tool at a dedicated replica means the expensive query only ever degrades the replica, and the checkout path never notices.
- A standby that exists purely for survival, taking no read traffic at all. It is there so that when the primary's host fails, there is an up-to-date copy to promote in minutes rather than restoring a backup over hours. The value is entirely in the recovery time, which is why its lag is monitored as an availability metric, not a performance one.
- A read-heavy API with users on another continent. A replica placed near those users serves their reads at local latency while all writes still travel to the single primary. The trade is explicit: reads get fast, writes stay slow and cross-regional, and the application must know which of its endpoints are which.
- A migration using replication as the mechanism. A new database is set up as a replica of the old one, allowed to catch up fully, and then promoted while writes are briefly paused. The cutover window is seconds instead of the hours a dump-and-restore would need.
When You Actually Need It
- An unplanned loss of your single database host would be unacceptable - you can state a recovery time objective, and restoring from your most recent backup is slower than that number. A standby replica is the direct answer.
- Your database's CPU or I/O is saturated and the query mix is dominated by reads. You can show that the top consumers are
SELECTs, not writes, which means read replicas will actually move the load. - Reporting, analytics, or export jobs are measurably interfering with transactional latency. Isolating them on a replica is cheaper and less invasive than optimising every one of those queries.
- You have users in a region far from your database and read latency is their dominant complaint, while their write volume is low. A nearby replica converts a cross-region round trip into a local one.
- You need to move or upgrade the database with minimal downtime. Replication gives you a warm, caught-up target to cut over to, rather than a restore window.
- Your backup strategy needs a source that is not the production primary - taking consistent backups off a replica removes that load from the machine serving your users.
When You Don't
- Your bottleneck is writes. Replication does not help, at all, in the common single-primary setup - every write still lands on one machine, and each replica adds a little work to it. Fix the writes first: batch them, remove redundant indexes, move hot counters out of the row, or shard the data. Reach for replicas only once reads are the proven problem.
- You have not tried the cheap options. A database comfortably served by a single modern server - a dataset that fits in RAM, read traffic a single instance handles without saturating CPU - usually has a missing index, an N+1 query, or no caching layer, not a replication deficit. One well-placed index or a cache in front of the hot query routinely beats a replica and costs you no consistency.
- Your reads cannot tolerate staleness and you have no way to reason about it per query. If every read in the application must reflect the latest write, routing reads to replicas will produce bugs you cannot reproduce. Keep reads on the primary and buy a bigger primary; that is a legitimate, boring, correct answer for a long time.
- You want availability but will not build or adopt failover. A replica nobody can promote is not high availability - it is a second copy and a monitoring obligation. If the plan is that someone wakes up and promotes it by hand, be honest that your recovery time is "however long until someone wakes up," and consider whether a tested restore procedure gets you the same thing with less running cost.
- You are thinking about multi-primary and cannot name your conflict resolution rule. If you cannot say what should happen when two users edit the same record simultaneously, do not accept writes in two places. Route all writes to one region and replicate outward; the latency is a known cost, whereas silent data loss is not.
- You will not monitor and alert on lag. Replication without a lag alert is a correctness problem waiting to be discovered by a user. If nobody will own that alert, serving reads from replicas is not yet safe - either set up the monitoring first or keep reads on the primary.
What People Get Wrong
"We added read replicas, so the database scales now."
Reads scale; writes do not. The primary remains a single machine accepting every write, and each replica adds a small amount of load to it. If your growth is in write volume, replicas postpone nothing - you need batching, schema changes, or sharding.
"Lag is a few milliseconds, so stale reads aren't a real risk."
Lag is a distribution, not a value, and its tail is what hurts you. It stays near zero while the system is quiet and grows during write bursts, bulk jobs, and schema changes - precisely the moments when a stale read is most likely to be noticed. Design for the tail, not the median.
"A replica means we don't need backups."
Replication copies your mistakes faithfully and fast. A bad DELETE or a corrupting application bug reaches every replica within seconds. Backups give you a point in time to go back to; replicas give you a current copy. You need both, for different failures.
"Synchronous replication means we cannot lose data."
It means you cannot lose an acknowledged write if the configured number of replicas really acknowledged it. Many setups degrade to asynchronous behaviour when replicas are slow or unreachable, so the guarantee quietly depends on the timeout and fallback policy. Check what yours does under pressure before you rely on the word "synchronous".
Why It Was Built This Way
Replication is log shipping because the log already had to exist. A database that promises your committed transaction survives a crash must record changes somewhere durable before acknowledging the commit, and it must be able to replay those records in order to recover. That recovery mechanism is, structurally, exactly what a second machine needs in order to become a copy. The design choice was not "how shall we synchronise two databases" but "we already have an ordered, durable record of every change - who else could consume it." Reusing it meant replication needed no new consistency machinery and no understanding of your schema; a replica is just a recovery process that never finishes.
The thing that was traded away is simultaneity. Because applying the log takes real work on the replica, the copy is always behind by a variable, workload-dependent amount, and the database cannot hide this from you. It could have hidden it - by making every write wait for every replica - but that would place the slowest machine in the critical path of every commit, and tie your write availability to the health of every copy. Faced with that, the default went to asynchronous: fast, available, and stale. The lag is not an implementation shortcoming someone will eventually fix. It is the price of not blocking writes on remote machines, and it is paid in your application code, at every place where you decide whether a read can be from the past.
This is also why single-primary persisted long after it became an obvious bottleneck. One writer gives you a total order for free, and a total order is what makes "apply the log in sequence" a complete solution. The moment you admit a second writer, there is no single sequence, and conflict resolution becomes a problem the database cannot solve on its own because the correct answer depends on what the data means. Systems that do multi-primary have not found a trick around this; they have moved the decision up to you, either as a resolution policy you configure or as data types whose merge semantics are defined in advance. Understand that and you can predict what any replication system will and will not do for you, without memorising any of them.
Related Briefs
What to Read Next
- what is database sharding
- eventual consistency vs strong consistency
- read after write consistency
Reach for replication when you can name which failure or which read load it is absorbing - a recovery time you must meet, a read-dominated workload saturating one box, an analytics query poisoning your transactional latency. Do not reach for it to "scale the database" generically, because it does not scale writes and it hands you a staleness problem to manage in return. The honest version of the decision is a trade you state out loud: you accept reads from the past, and a lag metric someone must own, in exchange for surviving a dead machine and spreading reads. If neither side of that trade describes your system today, one database is still the right answer.
댓글
댓글 쓰기