Asynchronous Replication: Lag, Failover, and Freshness
Learn how asynchronous database replication affects read freshness, failover data loss, lag monitoring, and recovery choices during network partitions.
With asynchronous replication, a primary can acknowledge a write before replicas receive it. Replicas may return stale reads, and promoting a lagging replica can lose acknowledged writes. During a network partition, the database's read and write policy determines which clients continue and whether the system preserves linearizable consistency. This guide covers replication lag, read-after-write routing, and failover decisions.
Asynchronous Replication: Lag, Failover, and Freshness
Introduction
With asynchronous replication, the primary can confirm a write before a replica receives it. Replication delay depends on the database, workload, and network; there is no general lag bound. If the primary fails before the write reaches an eligible failover replica, that acknowledged write may be lost. Whether that risk is acceptable depends on the application’s recovery-point objective and failover policy.
How asynchronous replication works
The primary processes a write, confirms it to the client, and sends the change to replicas in the background. The client does not wait for replica confirmation.
sequenceDiagram
participant Client
participant Primary
participant Replica
Client->>Primary: BEGIN, UPDATE..., COMMIT
Primary->>Primary: Write to local WAL
Primary-->>Client: COMMIT confirmed
Note over Primary,Replica: (Background replication)
rect rgb(200, 200, 200)
Primary->>Replica: Send WAL entry
Replica-->>Primary: ACK
end
Because the client does not wait for replica confirmation, async replication can reduce write wait compared with a policy that waits on a remote replica. Actual latency depends on the database’s commit settings and workload.
The replication lag problem
With async replication, a replica can fall behind the primary. Lag depends on write rate, network conditions, and how quickly the replica applies changes; use measurements rather than a universal time range.
# This sequence can fail with async replication
def update_and_read(user_id, new_email):
db.execute("UPDATE users SET email = ? WHERE id = ?", new_email, user_id)
# Write confirmed immediately
# But replica might not have the update yet
user = db_replica.execute("SELECT email FROM users WHERE id = ?", user_id)
# Might return old email if replica is lagging
return user['email']
Reads from a lagging replica may return the old value even after the primary acknowledged a write.
Statement-based vs. WAL-based replication
Different databases use different mechanisms.
Statement-based replication sends the SQL statements to replicas. MySQL’s original replication used this approach.
-- Primary executes:
UPDATE users SET email = 'new@example.com' WHERE id = 1;
-- Replica executes the same statement:
UPDATE users SET email = 'new@example.com' WHERE id = 1;
The problem: nondeterministic functions like NOW() or RAND() produce different results on different nodes.
WAL-based replication sends the binary WAL entries. PostgreSQL uses this. WAL entries are deterministic because they contain the actual bytes that changed.
# WAL entry contains the actual bytes
wal_entry = {
'type': 'UPDATE',
'table': 'users',
'key': 'id=1',
'old_data': {'email': 'old@example.com'},
'new_data': {'email': 'new@example.com'},
'timestamp': 1711234567 # example Unix timestamp
}
Row-based replication sends the actual row changes. MySQL’s row-based replication combines the benefits of both.
Eventual consistency
With one authoritative primary, working replication, and no new writes, replicas can converge after they apply the primary’s changes. That convergence is not guaranteed if replication stays broken, writes are accepted independently on multiple nodes, or data is discarded during failover.
flowchart LR
P[Primary] -->|immediate| R1[Replica 1]
P -->|immediate| R2[Replica 2]
R1 -.->|eventually consistent| Same[Same State]
R2 -.->|eventually consistent| Same
While lag persists, reads from different replicas may return different results.
# User experience with eventual consistency
def get_user_email(user_id):
# Route to random replica
replica = random.choice([replica1, replica2, replica3])
return replica.execute("SELECT email FROM users WHERE id = ?", user_id)
# Two consecutive calls might return different results
email1 = get_user_email(123) # 'old@example.com'
email2 = get_user_email(123) # 'new@example.com' if replica2 has newer data
When async replication fits
Async replication can fit when:
- Web sessions and preferences: Some applications can tolerate delayed visibility of profile changes
- Analytics and reporting: Some dashboards can tolerate delayed freshness
- Social media feeds: Timeline updates do not need to be immediately consistent
- Logging and metrics: Time-series data tolerates small gaps
- Geographic distribution: Async replication can avoid waiting for acknowledgments across a high-latency link; the consistency and recovery trade-offs still need to fit the application
# Good async use case: user preferences
def update_user_preference(user_id, key, value):
# Write immediately, replicate async
db.execute("UPDATE preferences SET value = ? WHERE user_id = ? AND key = ?",
value, user_id, key)
# User sees update instantly on primary
# Other replicas catch up shortly
# Bad async use case: account balance
def transfer_funds(from_id, to_id, amount):
# Use a database transaction for the debit and credit together.
# Async replication alone may lose an acknowledged transfer during failover.
db.execute("UPDATE accounts SET balance = balance - ? WHERE id = ?",
amount, from_id)
db.execute("UPDATE accounts SET balance = balance + ? WHERE id = ?",
amount, to_id)
Monitoring replication lag
Lag monitoring is critical with async replication. You need to know how far behind your replicas are.
-- PostgreSQL: Check replication lag
SELECT client_addr, state,
sent_lsn, replay_lsn,
sent_lsn - replay_lsn AS lag_bytes
FROM pg_stat_replication;
-- MySQL: Check replica lag
SHOW REPLICA STATUS\G
# Inspect Seconds_Behind_Source, Replica_IO_Running, and Replica_SQL_Running.
# Interpret the lag field with the topology and server version in mind.
In MySQL 8.4, Seconds_Behind_Source is an estimate based on replication timestamps and may not reflect network delay accurately. Check the versioned SHOW REPLICA STATUS reference when interpreting it.
# Application-level lag monitoring
def check_replica_health(replica):
last_replicated_ts = replica.get_last_replicated_timestamp()
current_ts = time.time()
lag_seconds = current_ts - last_replicated_ts
# Set this limit from the application's recovery or freshness objective.
if lag_seconds > max_lag_seconds:
alert(f"Replica {replica.name} lag: {lag_seconds}s")
# Route reads away from this replica
remove_from_read_pool(replica)
Key metrics to track:
| Metric | What to watch | Alert basis |
|---|---|---|
| Replication lag | Time and/or log position difference | Compare with the application’s recovery and freshness goals. |
| Replica IO thread | Connection and receiver state | Alert when replication has stopped unexpectedly. |
| Replica SQL thread | Apply state and errors | Alert when changes are not being applied. |
| WAL backlog | Retained and unapplied log volume | Check slot retention, disk headroom, and recovery needs. |
CAP during a network partition
CAP concerns the guarantees a distributed read/write service makes while nodes cannot communicate. In Gilbert and Lynch’s model, consistency means atomic, linearizable behavior; availability means every request to a non-failing node eventually receives a response. During a partition, a service cannot guarantee both for every request. The usual “pick any two” shorthand hides that condition: the limit applies while the partition is happening. Synchronous and asynchronous replication describe when writes are acknowledged; the mode alone does not decide which CAP guarantee the service keeps. See Gilbert and Lynch’s paper (DOI 10.1109/MC.2011.389).
A primary and replica during a partition
Assume primary P and replica R both hold balance=10, and R has caught up.
- At
t0, the nodes can communicate. A read from either one returns10. - At
t1, the network path between them breaks. Clients that can reachPcan still read and write if the database allows the primary to operate alone. One client debits 3;Pcommitsbalance=7and acknowledges the write beforeRreceives it. Reads fromPnow return7. - Clients that can reach only
Rmay receive the old value,10, if stale reads are allowed. The request gets a response, but the read is stale and not linearizable. A request for the latest value or a write must wait or fail under a single-primary policy becauseRcannot coordinate withP. IfRaccepts independent writes, the two sides can diverge and need conflict handling. - At
t2, if the link heals andPremains authoritative,Rapplies the missing update and catches up. IfPcrashes beforeRreceives the update and failover promotesRfrom its local state,balanceis still10. The acknowledged debit is missing unless another durable copy or log can restore it.
Promotion also needs to fence the old primary, or use a lease or quorum rule that prevents it from accepting writes. Promotion alone does not promise zero data loss. For RPO 0, the candidate that will be promoted must be able to recover every acknowledged write before it serves traffic. If the system cannot guarantee that for the stated failure model, its RPO is nonzero. A synchronous setting helps only if its acknowledgment rule meets that condition; writes may wait or fail if the required replica cannot respond. See CAP Theorem and Consistency Models for the broader model.
Reducing lag in async setups
If lag is a problem, there are techniques to reduce it.
Upgrade replica hardware: Replicas that cannot keep up with the primary’s write rate will always lag. Give them faster disks and more CPU.
Reduce write workload: If the primary produces changes faster than replicas can apply them for a sustained period, lag grows. Measure both rates on representative traffic before changing capacity.
Use parallel replication: Modern MySQL and PostgreSQL support parallel replica apply.
For MySQL 8.4, the reference documentation checked on 2026-11-02 lists a default of four replica_parallel_workers. An override is a tuning choice, not a throughput promise; the right value depends on workload and server resources. See the versioned MySQL replica options.
PostgreSQL’s wal_sender_timeout detects inactive replication connections; it does not speed up applying WAL. Change it only to fit network and failure-detection needs. See the PostgreSQL 18 replication settings.
Cascade replication: Chain replicas so the primary does not feed every replica directly. This reduces primary load.
flowchart TD
P[Primary] --> R1[Replica 1]
R1 --> R2[Replica 2]
R1 --> R3[Replica 3]
R2 --> R4[Replica 4]
Read routing with async replicas
Application code should handle stale reads gracefully when using async replicas.
# Read from replica with fallback to primary
def read_user(user_id):
try:
# Try replica first
replica = get_read_replica()
user = replica.execute("SELECT * FROM users WHERE id = ?", user_id)
return user
except ReplicaTooLagError:
# Fall back to primary if replica is too far behind
return primary.execute("SELECT * FROM users WHERE id = ?", user_id)
# Read-after-write with async replication
def update_and_read(user_id, new_email):
# Always read from primary after writes
db.execute("UPDATE users SET email = ? WHERE id = ?", new_email, user_id)
return primary.execute("SELECT email FROM users WHERE id = ?", user_id)
When async replication is not enough
Some data genuinely cannot tolerate async replication:
- Financial transactions: If you write a payment and the primary fails before replicas receive it, money disappears
- Inventory management: Overselling happens when replicas do not have the latest stock counts
- Locking operations: If you acquire a lock and the primary fails before it replicates, you have a zombie lock
For these cases, see Synchronous Replication for strong consistency options.
Illustrative failure scenarios
Scenario 1: The replica falls behind
Illustrative case: the primary produces WAL faster than a replica can apply it, so the replica’s backlog grows. If the primary then fails, promoting that replica can lose writes the primary had acknowledged but the replica had not received. In PostgreSQL, compare sent_lsn and replay_lsn in pg_stat_replication; set alerts against the application’s RPO and investigate a sustained gap instead of treating a threshold as universal.
Scenario 2: Clients reach different sides of a partition
With a single-primary policy, clients that can reach the primary may continue to write if it is allowed to operate alone. Clients that reach only the replica may read stale data or receive errors; that replica cannot safely accept independent writes as part of the same single-primary history. If an operator promotes the replica before fencing the old primary, both nodes could accept writes and diverge. A healed connection does not choose which conflicting business update to keep. The application and failover policy must define which side may write and how any divergence is reconciled.
Scenario 3: Promotion does not meet the RPO
Illustrative case: an analytics workload slows replica apply, and an operator promotes that replica without checking its position. Service may return quickly, but acknowledged writes missing from the candidate remain lost. RTO and RPO measure different outcomes: time to restore service and the amount of data the system can lose. Before promotion, check the candidate’s lag against the RPO, verify replication state, and fence the old primary. If no candidate meets the RPO, the recovery plan must explicitly choose between waiting, reconciling, or accepting documented data loss.
Scenario 4: A replica loses required WAL
If a PostgreSQL replica falls behind and required WAL is no longer available from the primary’s retained files, it can recover only if an archive has the missing segments. Otherwise, it may need to be rebuilt from a new base backup. Monitor replication slot state and retained WAL volume, and set retention to fit the planned recovery window. See the versioned PostgreSQL 18 replication slot documentation.
Common pitfalls
-
Assuming replica data is current: After a write, do not assume replicas have the update immediately. Always read from primary for critical data after writes.
-
Not monitoring lag: A replica can fall far behind before users notice. Monitor replication position and apply state, and alert against the application’s recovery objective.
-
Promoting a lagging replica: Promotion can omit acknowledged writes the candidate has not received. Check lag and the RPO before promoting.
-
Ignoring replication slot retention: If a slot is lost and required WAL is unavailable from retained files or an archive, the replica may need a full resync.
-
Testing in ideal conditions: Replication lag grows under load. Test with production-level write rates.
Quick recap
- Async replication confirms writes immediately without waiting for replicas
- Replication lag means replicas can return stale data
- Best for: non-critical reads, analytics, geographically distributed systems
- Monitor lag actively and alert on threshold breaches
- Use read-after-write consistency when needed by reading from primary after writes
- For a zero-RPO requirement, configure acknowledgments and failover selection for a defined failure model; synchronous replication alone does not guarantee it
Read-your-writes consistency checklist
When using async replicas, ensuring read-after-write consistency requires explicit handling:
# Strategy 1: Read from primary after writes
def read_after_write(session, user_id, new_email):
session.execute(
"UPDATE users SET email = ? WHERE id = ?",
new_email, user_id
)
# Must read from primary to see our own write
return primary.execute(
"SELECT email FROM users WHERE id = ?",
user_id
)
# Strategy 2: Track LSN and wait for replication
def read_after_wait(session, user_id, new_email):
lsn = session.execute(
"UPDATE users SET email = ? WHERE id = ?",
new_email, user_id
)
# Wait for replica to catch up to our LSN
# The wait budget is an application setting, not a replication guarantee.
replica.wait_for_lsn(lsn, timeout=consistency_wait_budget)
return replica.execute(
"SELECT email FROM users WHERE id = ?",
user_id
)
# Strategy 3: Session pinning (sticky to primary)
def read_with_session_pin(session, user_id):
# Session always routes to primary for this user
session.set_pin(user_id, to_node='primary')
return session.execute(
"SELECT email FROM users WHERE id = ?",
user_id
)
| Strategy | Pros | Cons | Best For |
|---|---|---|---|
| Read from primary | Simple, always correct | Adds primary load | Write-heavy workloads |
| Wait for LSN | Works with any replica | Adds latency | Occasional consistency needs |
| Session pinning | Consistent experience | Reduces flexibility | User-specific data |
Trade-off analysis
| Aspect | Asynchronous Replication | Synchronous Replication |
|---|---|---|
| Write acknowledgment | Can complete before a replica confirms receipt | Waits for confirmation according to the configured sync policy |
| Data safety | Writes not received by the promoted replica may be lost | Risk depends on what the standby confirms and which candidate is promoted |
| Availability | A primary may keep serving writes alone; other-side requests depend on policy | Writes needing an unavailable standby confirmation may wait or fail |
| Replica placement | Can operate over higher-latency links, with a larger catch-up window | Confirmation across a higher-latency link adds wait to commits |
| Use case fit | Useful when lag and possible loss fit the recovery objective | Useful when the configured acknowledgment and failover policy meets the data-safety objective |
| Failover | Candidate may be behind; check its position and fence the old primary | Confirmation can narrow the loss window, but promotion and fencing still matter |
Interview questions
Expected answer points:
- Synchronous replication waits for replica confirmation before acknowledging the write to the client
- Asynchronous replication confirms the write immediately after the primary records it locally, then sends changes to replicas in the background
- This difference makes async replication faster but introduces the possibility of data loss during failover
Expected answer points:
- Replication lag is the time difference between when a write is committed on the primary and when it is applied on a replica
- Reads from lagging replicas can return stale or outdated data
- Lag depends on network conditions, workload, and replica apply capacity; define thresholds from the application's freshness and recovery objectives
- Applications must handle potentially inconsistent reads during the lag window
Expected answer points:
- Statement-based: Sends SQL statements to replicas. Simple but problematic for nondeterministic functions like NOW() or RAND() that produce different results on different nodes
- WAL-based: Sends binary Write-Ahead Log entries containing actual changed bytes. Deterministic and compact. Used by PostgreSQL
- Row-based: Sends actual row changes. Combines benefits of both - deterministic and complete. Used by MySQL's row-based replication
Expected answer points:
- With one authoritative primary and working replication, replicas can converge after they apply changes and new writes stop
- During lag, different replicas can return different results for the same query
- Applications need a policy for handling stale or differing reads
- Suitable for applications where strict immediate consistency is not required
Expected answer points:
- CAP concerns behavior during a network partition; a distributed read/write system cannot guarantee both linearizable consistency and availability for every request during that partition
- Async replication describes when writes are acknowledged; it does not, by itself, select the system's CAP behavior
- A single-primary policy may keep serving requests that reach the primary while refusing writes or fresh reads on a disconnected replica side
- If the primary fails before an acknowledged write reaches the promoted replica, that write can be missing after failover
Expected answer points:
- Read from primary after writes: Route reads to the primary immediately following a write. Simple but adds primary load
- Track LSN and wait: After a write, track the Log Sequence Number and wait for the replica to catch up to that LSN before reading. Adds latency but works with any replica
- Session pinning: Pin a user's session to the primary for consistent reads. Reduces flexibility but provides consistent experience per user
Expected answer points:
- Replication lag: Compare sent and replayed log positions or timestamps with the application's RPO and freshness goals; thresholds depend on the workload
- Replica IO thread status: Must be running. Stopped thread means replication has stopped
- Replica SQL thread status: Must be running. Stopped thread means events are not being applied
- WAL backlog: Monitor retained and unapplied log volume against disk headroom and recovery needs
Expected answer points:
- A promoted replica may lack acknowledged writes it has not received; check its position against the recovery objective
- The new primary will have incomplete data compared to what was committed
- Always check lag metrics before promoting a replica
- Establish a maximum acceptable lag threshold (e.g., RPO) before allowing automatic failover
Expected answer points:
- Cascade replication chains replicas, so downstream replicas receive changes through an upstream replica
- Reduces load on the primary, which no longer needs to feed every replica directly
- Trade-off: adds latency as changes propagate through the chain
- Useful for read-heavy deployments with many replicas across geographic regions
Expected answer points:
- If the primary fails after write confirmation but before replicas receive the change, that data is lost
- In financial systems, losing committed transactions (even small amounts) is unacceptable
- Money disappearing due to replication lag can cause regulatory and customer trust issues
- If a financial system cannot lose acknowledged writes under a defined failure model, it needs an acknowledgment and failover policy that protects those writes, often using synchronous replication or consensus
Expected answer points:
- Upgrade replica hardware: Faster disks and more CPU so replicas can keep up with the primary's write rate
- Reduce write workload: If the primary produces changes faster than replicas can apply them for a sustained period, lag grows
- Enable parallel replication: Modern MySQL and PostgreSQL support applying events in parallel on replicas
- Cascade replication: Chain replicas to reduce primary load
Expected answer points:
- Statement-based: Replicas execute the same SQL statements as the primary. Can produce different results with nondeterministic functions
- Row-based: Replicas receive the actual row changes (before and after images). Deterministic and complete
- Row-based replication produces larger binary logs but avoids subtle replication bugs
- MySQL allows switching between modes based on workload
Expected answer points:
- Replication slots prevent the primary from removing WAL segments that replicas haven't yet received
- If a replica falls behind significantly and the replication slot is lost, the gap cannot be recovered
- If required WAL is unavailable from retained files or an archive, the replica may need a full resync instead of resuming from its old position
- Monitor replication slot status and ensure replicas stay connected
Expected answer points:
- Web sessions and preferences: Some applications can tolerate delayed visibility of profile changes
- Analytics and reporting: Dashboard reads may tolerate stale data if the freshness objective allows it
- Social media feeds: Timeline updates tolerate eventual consistency
- Logging and metrics: Time-series data tolerates small gaps
- Geographic distribution: Async replication can avoid waiting for acknowledgments across a high-latency link
Expected answer points:
- If the primary fails while replicas are lagging, a promoted replica may lack writes the primary acknowledged but had not sent
- The RPO may be exceeded if the promoted candidate lacks writes the primary had acknowledged
- Before promoting any replica, check its lag metrics against your acceptable RPO threshold
- If no replica is within acceptable lag, prefer manual reconciliation over automatic failover
Expected answer points:
- Replication slots are PostgreSQL features that prevent WAL segment removal until replicas confirm receipt
- If a replica is disconnected and the slot is dropped (due to misconfigured retention), WAL segments needed for recovery are purged
- If the required WAL is unavailable from retained files or an archive, the replica may need a fresh base backup
- A rebuild can reduce read capacity and add load while the replica catches up
Expected answer points:
- In cascade replication, the primary feeds a subset of replicas directly, and those replicas feed downstream replicas
- The primary no longer needs to maintain concurrent connections for every replica
- Network bandwidth on the primary is significantly reduced in large replica deployments
- Trade-off: adds propagation latency as changes flow through intermediate replicas
Expected answer points:
- WAL advantages: Deterministic (contains actual changed bytes), compact, works for any SQL operation
- WAL disadvantages: Binary format tied to specific database version, harder to inspect and debug
- Statement advantages: Human-readable, portable across MySQL versions
- Statement disadvantages: Nondeterministic functions cause divergence between primary and replica
Expected answer points:
- During the replication lag window, replicas are at different points in the transaction stream
- If queries are load-balanced across replicas randomly, consecutive reads can return different results
- This observable inconsistency is the price of async replication's speed
- Applications must either accept staleness or implement read-after-write consistency by routing critical reads to the primary
Further reading
- Database Replication - Replication patterns, including sync, async, and semi-sync approaches
- Synchronous Replication - Strong consistency options when async is not sufficient
- Consistency Models - Understanding strong, eventual, and causal consistency
- Distributed Caching - Read-scaling patterns that complement replication
- Event-Driven Architecture - Alternative consistency models using event sourcing
- CAP Theorem - The theoretical foundation behind replication trade-offs
Conclusion
Async replication fits when delayed reads and possible loss of unreplicated writes fit the recovery policy. During a partition, availability depends on which requests each side can safely serve. A failover plan must check the candidate’s state and fence the old primary.
Category
Related Posts
CRDTs: Conflict-Free Replicated Data Types
Learn how conflict-free replicated data types converge after concurrent updates, and where counters, LWW registers, and observed-remove sets fit.
Synchronous Replication: Data Consistency Across Nodes
Learn about synchronous replication patterns in distributed databases, including Quorum-based replication and write-ahead log shipping for zero RPO.
Database Replication: Primary and Replica Failover
Understand primary and replica topologies, synchronous and asynchronous replication, failover risks, replication lag, and why replicas do not replace backups.