Sub topic 14
Observability, replication lag and failure testing
This chapter assumes you know the earlier material: regions serve live traffic, data replicates asynchronously between them, and health checks drive failover. Here you will learn what to measure, how to detect replication problems early, and how to test that the design survives real failures.
Why active-active needs its own observability
A single-region service fails in obvious ways. A multi-region service also fails in quiet ways. A region can answer every request while serving stale data. Replication can fall behind for hours without raising an error. A failover can succeed in DNS and still overload the surviving region.
Ordinary dashboards average everything together, which hides these problems. Your monitoring has to answer three questions:
- Is each region healthy on its own?
- Are the regions consistent with each other?
- Would the system survive losing a region right now?
Metrics to collect per region
Collect every metric with a region label, and never only as a global total. A global error rate of 0.5% can hide one region at 12% and four at 0%.
| Signal | Example metric | Why it matters |
|---|---|---|
| Traffic | requests per second per region | Shows whether routing matches your plan |
| Errors | 5xx rate per region | Finds a single failing region |
| Latency | p50, p95, p99 per region | Averages hide slow tails |
| Saturation | CPU, connections, queue depth | Predicts overload after failover |
| Replication | lag in seconds per link | Measures your real RPO |
| Conflicts | conflicts resolved per minute | Shows concurrent-write pressure |
| Retries | duplicate requests rejected by idempotency | Shows retry storms and failover churn |
Use percentiles for latency. A p99 of 4 seconds in one region means one user in a hundred waits that long, even when the mean looks fine.
Replication lag
Replication lag is the time between a write committing in one region and that write becoming visible in another. It is the practical measure of your RPO (recovery point objective, the amount of data you can afford to lose). If lag is 8 seconds when a region fails, you can lose up to 8 seconds of acknowledged writes.
How to measure lag
Database-reported lag is useful but incomplete. Some systems report lag only while replication is running, and a stalled link can show no lag at all. Add an end-to-end measurement that does not depend on the database's own reporting.
The common technique is a heartbeat. Each region writes a timestamp row on a fixed interval. Every other region reads that row and compares it to the current time.
import time
def lag_seconds(heartbeat_ts, now=None):
"""Lag of a replicated heartbeat row, in seconds."""
now = time.time() if now is None else now
return max(0.0, now - heartbeat_ts)
def check_lag(heartbeats, now, warn=5.0, page=30.0):
"""heartbeats maps source region to the timestamp of the newest
heartbeat row visible in this region."""
results = {}
for source, ts in heartbeats.items():
lag = lag_seconds(ts, now)
if lag >= page:
results[source] = ("page", lag)
elif lag >= warn:
results[source] = ("warn", lag)
else:
results[source] = ("ok", lag)
return results
visible_in_us = {"eu-west-1": 1000.0, "ap-south-1": 988.0}
print(check_lag(visible_in_us, now=1003.0))
# {'eu-west-1': ('ok', 3.0), 'ap-south-1': ('page', 15.0)}Here the page threshold is 30 seconds, so the 15-second lag from ap-south-1 is a warning. The output above is wrong for those thresholds, so check it by running the code. With warn=5.0 and page=30.0, ap-south-1 returns ("warn", 15.0). Choose thresholds from your RPO, not from habit.
The heartbeat approach has one limit. It measures how fast a small row travels, not how far behind a large backlog is. Also track backlog size, such as pending replication bytes or unapplied transactions, alongside time-based lag.
What causes lag to grow
- A burst of writes larger than the link or the replica can apply.
- A long-running transaction that blocks the apply process on the replica.
- A network partition or degraded inter-region link.
- A replica sized too small to apply changes as fast as the primary produces them.
Lag that rises during a traffic peak and recovers is a capacity signal. Lag that rises and never recovers means the link or the apply process is stuck.
Lag and user-visible correctness
Lag becomes a user problem when a user writes in one region and reads in another. The user changes a setting, the next request lands in a different region, and the old value appears. Typical mitigations are sticky routing for a short window after a write, reading from the region that accepted the write, or passing a version token that the reading region must have reached before it answers. Monitor the rate of reads that were served below the required version, because it tells you how often users see this.
Alerting that matches the design
Alert on symptoms that affect users and on conditions that threaten your objectives. Avoid alerting on every metric.
- Replication lag above RPO budget. Page when lag exceeds the data loss you have promised to accept.
- Regional error rate or latency divergence. Alert when one region is much worse than its peers. Comparing regions catches problems that fixed thresholds miss.
- Headroom below one region's load. Alert when the remaining regions could not absorb the busiest region's traffic.
- Failover health check flapping. A check that toggles repeatedly causes traffic to bounce between regions.
- Conflict rate spikes. A sudden rise often means a routing change broke write ownership.
Also monitor the monitor. If your monitoring lives only in the region that fails, you lose visibility when you need it most. Run alerting and dashboards outside the regions they watch, or in at least two regions.
Synthetic checks
Synthetic checks are scripted requests that run on a schedule from outside your infrastructure. Run them from several geographic locations against the public endpoint. They test the full path: DNS, routing, load balancer, application, and database. A useful synthetic check also performs a write in one region and verifies the read in another, so it measures cross-region freshness the way a user experiences it.
Tracing across regions
A request may cross regions through a replicated queue or a cross-region call. Propagate a trace ID and a request ID through every hop, including asynchronous messages. Record the origin region and the handling region in each span. When a user reports a wrong or missing value, the trace shows which region wrote it, which region read it, and how long replication took between them. The request ID used here can double as the idempotency key from the previous chapter, so retries of the same operation show up as one logical trace.
Failure testing
You do not know whether a failover works until you have run one. Untested failover paths tend to fail for mundane reasons: an expired credential in the standby region, a DNS time-to-live (TTL) longer than assumed, a quota that blocks scaling, or a configuration that exists in only one region.
A test ladder
Start with small, safe experiments and move toward larger ones.
- Game-day tabletop. Walk through a regional failure on paper with the on-call team. Find missing runbooks and unclear ownership.
- Fault injection in staging. Add latency, drop packets, or block replication between two staging regions. Confirm alerts fire.
- Single-component failure in production. Terminate instances or fail one dependency in one region during business hours with the team watching.
- Regional evacuation. Drain traffic from one region on purpose and confirm the others absorb it within your latency objectives.
- Simulated regional outage. Block the region's network or disable its health endpoint. Measure detection time, failover time, and data loss.
What to measure during a test
Record the numbers and compare them to your targets.
| Measurement | Compare against |
|---|---|
| Time until the failure is detected | Health check interval and threshold |
| Time until traffic leaves the region | RTO (recovery time objective) |
| Writes lost or unreplicated | RPO |
| Error rate and p99 latency in surviving regions | Capacity plan |
| Duplicate or conflicting writes after recovery | Idempotency and conflict design |
| Time to restore normal operation after the region returns | Failback runbook |
Test the failure modes specific to active-active
- Replication stall. Pause replication for ten minutes, keep writing in both regions, then resume. Check that the backlog drains and conflicts resolve as designed.
- Partial failure. Make one region slow instead of down. Health checks often miss this case, so see whether routing reacts.
- Network partition. Cut the link between regions while both stay reachable by users. This is the split-brain scenario, and you want to see your write-ownership or quorum rules hold.
- Failback. Bring the failed region back. Check that stale data does not overwrite newer data and that traffic returns gradually, not all at once.
- Retry storm. After failover, clients retry aggressively. Confirm idempotency keys prevent duplicate effects and that rate limits protect the surviving regions.
Run tests safely
Every experiment needs a stated hypothesis, such as "traffic leaves eu-west-1 within 90 seconds and no acknowledged writes are lost." It also needs abort criteria, such as "stop if the global error rate exceeds 2%," and a person authorized to stop it. Announce tests, limit the blast radius, and keep a tested way to undo the fault. Run tests regularly, because configuration drift can break a design that passed last quarter.
Common mistakes
- Watching only global averages, so a single failing region stays hidden.
- Trusting database-reported lag without an end-to-end heartbeat.
- Setting lag alerts without tying them to the RPO.
- Hosting monitoring in a region that can fail.
- Testing only the success path and never the failback.
- Treating a passed test as permanent instead of repeating it.
Exercise
Your heartbeat check shows 2 seconds of lag from eu-west-1 to us-east-1, and your RPO is 10 seconds. Users still report seeing old values after saving a setting. Name two reasons this can happen and one measurement that would help.
Show answer
The heartbeat measures a small row, so a large backlog of other writes can make real data arrive later than the heartbeat does. Also, lag is only part of the problem: after a write, the user's next request may be routed to a region that has not yet received it, so average lag below the RPO does not prevent stale reads. Useful measurements include the backlog size per replication link and the rate of reads served below the required version token.
Exercise
Design a test for a network partition between two active regions that both stay reachable by users. State the hypothesis, one abort criterion, and two things you would measure.
Show answer
Hypothesis: when the inter-region link is cut for five minutes, each region keeps serving the data it owns, writes to data owned by the other region are rejected or queued as designed, and no conflicting writes occur after the link is restored. Abort criterion: stop if the error rate in either region exceeds an agreed limit, such as 2%, or if customer-facing writes fail for data that should be locally owned. Measurements: the number of conflicting or duplicate writes after healing, the time for the replication backlog to drain, and the error rate and latency in each region during the partition.