Blog

Replication Lag and Failover: Root Cause Analysis for Replicated Databases

Replication lag, failover and write conflicts produce stale reads, lost writes and duplicate IDs. How to investigate replica incidents from evidence.

  • replication lag
  • database replication
  • failover
  • root cause analysis
  • distributed systems

Every replicated database is lying to some of its readers some of the time. That is not a defect. It is the design, and you agreed to it the day you added a read replica.

Most of the time the lie is small: a follower that is 40 milliseconds behind the leader serves a value that was true 40 milliseconds ago, and nobody can tell. The incidents start when the lie gets bigger than anyone assumed. A replica falls ten minutes behind during a bulk load. A failover promotes a node that never received the last few seconds of writes. Two regions accept conflicting updates and one of them quietly wins. Users report that saved settings revert, that an order vanished, that a record shows up on the wrong account. Engineers check the primary, find the data correct, and close the ticket as “could not reproduce”.

Replication lag and the failures around it are among the hardest incidents to investigate, because the evidence is transient and the symptom appears somewhere other than where the cause lives. This article uses the replication chapter of Martin Kleppmann’s Designing Data-Intensive Applications as a map of the failure modes, and turns each one into something you can test during an incident: what users see, what mechanism produces it, and which evidence tells the rival explanations apart.

Table of Contents

Why replication creates its own incidents

Replication keeps a copy of the same data on several machines. Teams add it for three reasons: to survive the loss of a machine, to serve reads from more places, and to put data closer to users. All three are good reasons. All three introduce a gap in time between a write landing in one place and becoming visible in another.

The common arrangement is leader-based replication. One node, the leader or primary, accepts writes and sends a stream of changes to followers, which apply them in the same order. Kleppmann distinguishes synchronous replication, where the leader waits for a follower to confirm before acknowledging a write, from asynchronous replication, where it does not. Fully synchronous replication to every follower is rare, because one slow follower would stall every write. Most production setups are asynchronous, or synchronous to one follower and asynchronous to the rest.

Asynchronous replication means two things that matter during an incident:

  1. A write that has been acknowledged to the client may not exist on any follower yet. If the leader is lost at that moment, the write may be lost too.
  2. Followers are behind by an amount that is normally tiny and occasionally very large. There is no upper bound built into the design. Under load, during a long transaction, or while a follower is recovering, the gap can grow to minutes.

Neither is a bug. Both are the price of availability and write latency. The investigation question is usually not “why is there lag?” but “what in our application assumed there wasn’t?”

Three failure families: lag, failover, conflict

Almost every replication incident belongs to one of three families. Naming the family early tells you which evidence to collect.

FamilyWhat users reportMechanismEvidence that decides it
Lag“My change disappeared, then came back.” “The report is missing this morning’s orders.”A read was served by a follower that had not yet applied the writeWhich node served the read; that node’s lag at the time of the read
Failover“My order was confirmed and now it doesn’t exist.” “Two records have the same ID.”A new leader was promoted without some writes the old leader had acknowledgedFailover timeline; replication position of the promoted node at promotion; writes acknowledged in the gap
Conflict“Two people edited it and one change vanished.”Two leaders, or two replicas, accepted concurrent writes; a resolution rule discarded oneBoth writes in the logs; the conflict resolution rule; the timestamps or versions it compared

The families look alike from the user’s side. “My change disappeared” can be lag, a failover that discarded the write, or a conflict that resolved against it. The discriminating question is whether the write is in the primary now. If it is, the read was stale: lag. If it is not, the write was lost or overwritten: failover or conflict. That one check often halves the hypothesis list in five minutes.

What replication lag looks like to a user

Kleppmann describes three anomalies that asynchronous followers produce, and each one has a recognisable signature in support tickets.

Reading your own writes

A user saves something, the page reloads, and the old value is back. The save went to the leader; the reload read from a follower that had not caught up. The user tries again, or waits a moment, and it works. The ticket says “settings sometimes don’t save”, and the engineer who checks the database finds the new value there, because by then the follower has caught up.

The guarantee that prevents this is read-after-write consistency, also called read-your-writes: a user always sees their own updates, though not necessarily everyone else’s. The book lists the usual ways to provide it. Read data the user may have modified, such as their own profile, from the leader. Read from the leader for a short period after the user’s last write. Or have the client remember the replication position of its last write and only read from a follower that has reached that position. Each has a cost, and the investigation is often about which one the code was supposed to use and where it was bypassed.

Time going backwards

A user refreshes a page twice. The first refresh shows a new comment; the second does not. Each request went to a different follower, and the second follower was further behind. To the user, time went backwards.

The guarantee here is monotonic reads: once a user has seen data at some point in time, they never see an older state. A common way to provide it is to route each user to the same replica, for example by hashing the user ID. The incident signature is a load balancer or connection pool change that spread one user’s requests across replicas with different lag.

Answers before questions

The third anomaly appears when data is partitioned and different partitions replicate independently. One observer sees an answer before the question it answers, because the partition holding the answer was less behind than the partition holding the question. The guarantee that prevents it is consistent prefix reads: if writes happen in a certain order, anyone reading them sees them in that order.

This one shows up in data pipelines more than in user interfaces. A downstream job reads order lines from one shard and orders from another, finds lines without their orders, and either drops them or fails a foreign key check. The hot partitions article covers more of what goes wrong when partitions drift apart.

Measuring lag honestly

Every database exposes some measure of lag, and every measure has a blind spot. Knowing the blind spot is the difference between “lag was zero” and “lag was zero according to a metric that could not have seen it”.

In PostgreSQL, the pg_stat_replication view on the primary shows each standby’s position and three lag intervals. The documentation notes that for an asynchronous standby, replay_lag approximates the delay before recent transactions became visible to queries there, which is the number users actually feel.

-- On the primary: how far behind is each standby, in bytes and in time?
SELECT application_name,
       client_addr,
       state,
       sync_state,
       pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn) AS replay_bytes_behind,
       write_lag,
       flush_lag,
       replay_lag
FROM   pg_stat_replication
ORDER  BY replay_bytes_behind DESC;

-- On a standby: when was the last replayed transaction committed on the primary?
SELECT pg_is_in_recovery()                          AS is_standby,
       pg_last_wal_receive_lsn()                    AS received,
       pg_last_wal_replay_lsn()                     AS replayed,
       now() - pg_last_xact_replay_timestamp()      AS since_last_replayed_commit;

The last column is a classic trap: on a quiet system with no new commits it keeps growing even though the standby is fully caught up. MySQL’s Seconds_Behind_Source in SHOW REPLICA STATUS has its own: it measures how far the applier is behind the events the replica has already received, so if the replica is slow to receive events it can read close to zero while serving minutes-old data.

The measure with the fewest blind spots is a heartbeat: write the current time to a small table on the primary every second, and on each replica compare the latest replicated heartbeat with the clock.

-- On the primary, every second, from a scheduler or a small loop:
INSERT INTO ops.replication_heartbeat (id, written_at)
VALUES (1, now())
ON CONFLICT (id) DO UPDATE SET written_at = EXCLUDED.written_at;

-- On each replica: how stale is the data this replica is serving right now?
SELECT now() - written_at AS staleness
FROM   ops.replication_heartbeat
WHERE  id = 1;

It measures exactly what users experience, including receive delays and replay delays, at the cost of depending on reasonably synchronised clocks between hosts.

MeasureWhat it tells youBlind spot
Bytes behind (LSN or binlog position difference)Volume of changes not yet appliedDoes not translate directly into time; a large transaction looks like a cliff
replay_lag and similar interval columnsTime for recent changes to become visibleCan show NULL once the standby is caught up and the primary is idle
Time since last replayed commitAge of the newest applied transactionGrows on a quiet system even with zero lag
Seconds_Behind_SourceHow far the applier trails the received eventsNear zero when the replica is behind at receiving
Heartbeat tableEnd-to-end staleness as a reader sees itDepends on clock synchronisation between hosts

The lag you need is the lag at the time

Lag is transient. By the time someone looks, the follower has usually caught up, and a query against the live views returns a reassuring zero. What the investigation needs is lag at the moment of the stale read, which means a time series kept by your monitoring, not a query run afterwards. If you do not have one, look for indirect evidence of the window: bulk jobs, long-running transactions, replica restarts, vacuum or maintenance, or replica-side queries long enough to delay replay. In PostgreSQL, for example, a long query on a hot standby can hold back replay up to the max_standby_streaming_delay setting, so a heavy report on a replica can make that replica stale for everyone.

Failover: where acknowledged writes go missing

Failover is the moment replication stops being a performance detail and becomes a durability question. When the leader fails, a follower is promoted, clients are pointed at it, and the old leader, if it comes back, has to become a follower. Kleppmann lists what goes wrong, and each item is an investigation hypothesis:

  • The new leader was behind. With asynchronous replication, it may not have received the last writes the old leader acknowledged. Those writes are usually discarded, which means a client was told “committed” for data that no longer exists.
  • Discarded writes collide with other systems. If anything outside the database recorded those writes, such as a cache, a search index, an email that was sent, or an ID stored somewhere else, the systems now disagree.
  • Two nodes believe they are the leader. This is split brain, covered below.
  • The timeout was wrong. Too long and recovery is slow. Too short and a leader under heavy load is declared dead, the failover adds more load, and the system thrashes.

GitHub’s 2012 post on that week’s availability is an unusually candid example of several of these at once, and Kleppmann uses it in the book. After a cluster partition, a MySQL node that the team already knew was out of date was elected master for seven minutes. Rows created in that window received auto-generated IDs that disagreed with references already held in Redis, so some dashboard events appeared for the wrong users and some repositories were routed incorrectly, including a small number of private ones that were briefly accessible to people outside them. The same post describes failovers triggered by health checks failing under a cold cache, and the team’s decision to make failover of the active database role manual.

For any incident that involves a failover, build the timeline explicitly:

14:02:10  leader stops acknowledging writes          (database log, primary)
14:02:31  failure detected; promotion begins         (orchestrator or managed service event)
14:02:33  last WAL position received by new leader   (replica log or promotion record)
14:02:40  new leader accepts writes                  (database log, new primary)
14:02:40+ clients reconnect                          (application logs, by host)

Question: which client writes were acknowledged between the new leader's
last received position and the old leader's last acknowledged position?

That window, between what the old leader acknowledged and what the new leader had, is where lost writes live. If application logs record a write ID or order number with its acknowledgement, you can list exactly which writes were lost and repair them deliberately. If they do not, you will be reconstructing them from customer complaints.

Split brain

Split brain is two nodes accepting writes as leader at the same time, usually after a network partition or a failure detector that disagrees with itself. Both sides acknowledge writes. When the partition heals, one side’s writes are discarded or must be merged by hand, and any IDs generated on both sides may collide.

The evidence pattern is distinctive: writes accepted by two different hosts with overlapping time ranges, and duplicate or interleaved sequence values. If you find it, the finding is rarely “the network partitioned”. Networks partition. The finding is about the mechanism that was supposed to make a second leader impossible, such as fencing, a majority vote, or a manual promotion step, and why it did not.

Conflicts: when two writes both succeed

Multi-leader and leaderless setups accept writes in more than one place: multi-region active-active databases, offline-capable mobile apps that sync later, collaborative editors, and leaderless stores that use quorums. Concurrent writes to the same record will happen, and the system has to resolve them.

The simplest rule, and the one many systems default to, is last write wins: keep the write with the highest timestamp and discard the rest. Kleppmann is direct about its cost. It achieves convergence by silently throwing away writes, and when the timestamps come from machine clocks, a node with a fast clock can win against a write that actually happened later. From the user’s side, a change simply vanished, and nothing logged an error, because discarding it was the design.

Investigating a suspected conflict needs three pieces of evidence: both writes, with the node that accepted each; the resolution rule as configured, not as remembered; and the values the rule compared, such as timestamps, versions or vector clocks. If the losing write’s timestamp is earlier than the winning one by less than the clock skew between the two nodes, you cannot tell from the data which one really came last, and the honest finding says so. The article on stale reads and consistency models goes further into why clocks make incident timelines unreliable.

Investigating a replica incident

The general method is hypothesis-driven debugging; what is specific to replication is the evidence. For each reported read or write, you want to know which node served it, when, and what that node’s replication position was. Most applications log none of that. Before you can test hypotheses you may need to reconstruct it from connection pool logs, proxy logs or the database’s own connection logs.

A useful first pass:

  1. Check whether the write is on the leader now. Present: the read was stale. Absent: the write was lost or overwritten.
  2. Find which node served the stale read. Application logs, proxy logs, or the routing rule in the code at that version.
  3. Find that node’s lag at that time. From a monitoring time series, or from indirect evidence of a lag window.
  4. Look for a failover or partition in the window. Managed service events, orchestrator logs, database logs on every node.
  5. Look for changes in routing. Code that moved a read path to replicas, a pool or proxy configuration change, a new replica added to the rotation.

If your application logs go to Google Cloud Logging, a structured log line per query path that includes the node role makes step 2 a filter rather than an archaeology project:

resource.type="k8s_container"
labels."k8s-pod/app"="settings-api"
jsonPayload.db_role="replica"
jsonPayload.route="GET /settings"
timestamp>="2026-11-04T02:00:00Z"
timestamp<"2026-11-04T03:00:00Z"

More patterns for pulling two windows side by side are in the Google Cloud Logging debugging queries article.

A worked example: settings that revert

This is an illustrative example. The numbers are invented to make the method concrete.

Symptom. Support tickets about notification settings “reverting after saving” rose from about one a week to around fifteen a day, starting on a Wednesday. Every ticket checked by an engineer shows the correct, new value in the database. The tickets cluster between 02:00 and 03:30 UTC, which is business hours for the affected users.

Hypotheses.

  • H1: the settings page now reads from a replica, and users see the old value while the replica lags (lag).
  • H2: an application cache serves the previous value after a save (cache).
  • H3: a client-side race sends an older version of the settings after the new one, overwriting it (lost update).

First test. H3 predicts the database holds the old value after the incident; H1 and H2 predict it holds the new one. Engineers have already observed the new value in every case, which weakens H3 a great deal. The code for the settings endpoint at the deployed version has no cache layer, which rules out H2. The commit history shows a change on the Wednesday that switched GET /settings to the read-only connection pool as part of moving read traffic off the primary.

Second, independent line of evidence. The replica lag time series shows the reporting replica routinely falling 30 to 90 seconds behind between 02:00 and 03:30 UTC, when a nightly batch job writes heavily to the primary. Before Wednesday, nobody read user-facing data from replicas during that window, so the lag was harmless. The ticket times line up with the lag spikes.

Finding. “A read path for user settings was moved to replicas without read-your-writes handling. During a nightly bulk write window, replica lag of up to 90 seconds made users see their previous settings after saving.” The fix routes reads of a user’s own settings to the primary for a short period after that user writes, and the investigation adds a replica-lag alert for user-facing pools. The rejected H3 is worth keeping: it confirms the save path itself is sound, which someone will otherwise suspect next time.

Making the next one easier to investigate

Most replication incidents are slow to investigate because the evidence was never recorded, not because the mechanism is complicated. A few cheap habits change that:

  • Log the node that served each critical read and write. A host name or a role is enough. Without it, every stale-read investigation starts with guesswork.
  • Keep a lag time series with history, from a heartbeat if possible. The live view is useless after the fact.
  • Record write acknowledgements with an ID. It turns “find the lost writes” into a set difference instead of a support exercise.
  • Treat failovers as events worth logging in full: who or what decided, when, which position the new leader had, when clients moved.
  • Do not let IDs generated by one store become keys in another without a plan for what happens when the first store rolls back. The GitHub post is the canonical illustration.
  • Write down which consistency guarantee each read path relies on. “This page needs read-your-writes” is a design fact that should survive the next refactor of the connection pool.

Frequently asked questions

What is replication lag?

Replication lag is the delay between a write being committed on the leader and that write becoming visible on a follower. With asynchronous replication it is usually a few milliseconds, but there is no built-in upper bound: under heavy write load, long transactions, network problems or replica-side contention it can grow to seconds or minutes. Any read served by a follower during that window returns data that is out of date.

What causes sudden replication lag spikes?

The common causes are bursts of writes on the leader, such as bulk loads, backfills and schema migrations; a single large transaction that must be applied in one piece; a replica that is short of CPU or disk throughput; long-running queries on the replica that delay replay; and network trouble between leader and follower. During an investigation, look for any of these in the window rather than at the replica’s state now, because lag usually disappears before anyone looks.

How do I fix read-your-writes problems?

Route reads that must reflect a user’s own changes to the leader, either always for that data or for a short period after the user writes. Alternatively, record the replication position of the user’s last write and only read from a replica that has reached it. All three cost something: leader load, routing complexity, or extra coordination. Choose per read path, and write down which path needs which guarantee so it survives later changes.

Can a database failover lose committed data?

With asynchronous replication, yes. A write acknowledged by the old leader may not have reached the follower that is promoted, and when the old leader returns those writes are typically discarded. Synchronous replication to at least one follower narrows or closes that window at the cost of write latency. If your application cannot tolerate lost acknowledged writes, check which replication mode your database or managed service actually uses during failover, rather than assuming.

Is synchronous replication the answer?

It removes one failure mode, lost acknowledged writes on failover, and introduces others: every write now depends on a follower being up and fast, so a slow follower slows the whole system. Many teams use one synchronous follower and the rest asynchronous. Synchronous replication also does not prevent stale reads from other asynchronous followers, so read-your-writes still has to be handled in the application or the routing layer.

Replication is a trade, and incidents show you the terms

Replication buys availability, read capacity and locality, and it pays with staleness, a durability window on failover, and conflicts if more than one node accepts writes. Those terms are fine when the application is written with them in mind. Incidents happen where code, configuration or operations quietly assume the terms are better than they are: that replicas are current, that failover is lossless, that the last write is the latest.

The investigation’s job is to find that assumption and make it explicit. Tools can help with the gathering: Decim, for instance, reads the code and commits from GitHub and the application logs from Google Cloud Logging, and when the deciding evidence is inside the database it writes a read-only check for your team to run rather than querying it. The investigations page shows that flow and the docs cover setup. How that differs from error-tracking tools is on the Sentry Seer comparison. For the broader frame of which faults your system tolerates and which it does not, start with faults vs failures.


Decim investigates incidents in your own system, from code, logs and tickets, and returns a diagnosis where every claim links to its evidence, with the rejected explanations kept so your team learns how its replicas really behave. It reads GitHub, Google Cloud Logging and Jira, writes database checks for your team to run, never runs SQL and never merges a fix. Learn more at decim.dev or see pricing.

Decim investigates pipeline incidents

It reads your code, logs and tickets, works through the pipeline step by step, and confirms the cause with evidence you can check: every claim links to the log line, commit or check behind it. Then it proposes the fix and writes the report.

Request a demo

← All articles