Disaster Recovery and Replication Lag: Multi-Region Active-Passive Architecture

Infrastructure & DevOps

Plan PostgreSQL disaster recovery with RTO/RPO goals. Learn replication lag, failover fencing, standby promotion, backups, traffic routing, and recovery drills.

TL;DR

  • Multi-region active-passive means one region accepts writes while another region keeps a recoverable copy and enough application capacity to take over.
  • Choose recovery time objective (RTO) and recovery point objective (RPO) from product impact. Asynchronous replication can lose acknowledged changes that have not reached the standby.
  • Database replication is not a backup. Preserve independent backups and point-in-time recovery in a failure domain separate from the primary.
  • PostgreSQL provides streaming replication and promotion primitives, but does not provide the complete failure detection, fencing, traffic routing, and failover orchestration system.
  • Practice the whole path, including fencing the old primary, promoting the standby, updating application traffic, verifying data, and rebuilding the former primary as a standby.

Define the failure you intend to recover from

Multi-region disaster recovery (DR) is a planned way to restore service when a region or a critical dependency in that region becomes unavailable. Active-passive keeps the application’s write authority in one primary region. A second region has a warm or hot database standby, application capacity, configuration, secrets, networking, and a tested route for becoming the active region.

“We have a replica” does not describe a recovery plan. Write down the target recovery time objective (RTO), the maximum acceptable recovery time, and the recovery point objective (RPO), the maximum acceptable data loss measured in time or committed transactions. Define the scope of “service recovered”: can users sign in, read their data, write a new transaction, receive webhook callbacks, and see their background jobs continue? A green database endpoint while the application cannot load identity-provider configuration does not satisfy the service objective.

Separate regional disaster recovery from high availability inside one region. A standby in a second availability zone may protect against a host or zone failure but does not automatically cover a region-level incident. Conversely, a cross-region replica may take longer to promote or may lag more because of network distance. Choose fault domains that match the risk you are paying to reduce.

Do not infer a universal RTO or RPO from a provider’s architecture diagram. Your outcome depends on database size, replication lag, application startup, connection recovery, routing, control-plane health, and human decision time. AWS’s DR strategy guidance treats recovery objectives as inputs to selecting backup and restore, pilot light, warm standby, or multi-site approaches. AWS Well-Architected disaster recovery planning

Choose a recovery posture that fits the objective

PatternWhat stays ready in the secondary regionMain trade-off
Backup and restoreBackups, infrastructure definitions, images, and procedures.Lower idle cost, but restore, application rollout, and validation determine a longer RTO.
Pilot lightCore network, identity, data copies, and minimal compute.More work is required to scale the application before meaningful traffic returns.
Warm standbyA running but possibly smaller application fleet and a database standby.Faster activation than rebuilding from scratch, with ongoing cost and capacity testing.
Active-passive ready capacityNear-production application and data capacity, normally with writes disabled.Higher cost and more deployment, security, and operational state to keep synchronized.

These names are not perfectly standardized across providers. Map the actual resources, capacity, replication behavior, and failover actions in your service to the labels. A PostgreSQL hot standby can accept read-only queries, but it is not an independent writable primary until promoted. PostgreSQL high availability and replication overview

Keep a single authoritative writer unless the product has a carefully designed multi-writer consistency model. Active-passive makes ownership easier to reason about: a primary processes writes, the standby replays them, and a controlled failover transfers authority. Allowing both regions to accept writes during a partition creates conflict resolution, duplicate identifiers, and reconciliation problems that a DNS change cannot solve.

Understand PostgreSQL replication and data loss

PostgreSQL physical streaming replication sends write-ahead log (WAL) records from a primary to a standby. Streaming replication is asynchronous by default. The standby can be behind the primary, and transactions committed on the primary but not yet received or replayed may be missing if the primary is lost and the standby is promoted. PostgreSQL also supports synchronous replication modes that wait for standby acknowledgement, trading commit latency and availability behavior for stronger acknowledgement guarantees. PostgreSQL log shipping and streaming replication

Measure lag in a way that informs the decision. On the primary, inspect the connected standby’s write and replay positions. For example:

SELECT
    application_name,
    state,
    sync_state,
    pg_size_pretty(
        pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn)
    ) AS bytes_not_yet_replayed
FROM pg_stat_replication;

This view only shows connected standbys. Alert on missing replication connections, WAL send and replay distance, archive delay, and retained WAL. Replication slots can prevent required WAL from being removed before a standby catches up, but a stalled slot can also retain WAL until storage is exhausted. Monitor slot lag and free disk. A time-based replay lag can be misleading during an idle workload, so combine positions and service-level indicators.

Cross-region synchronous commit can add round-trip delay to writes and can block commits when the required synchronous standby is unavailable, depending on configuration. Evaluate the exact synchronous mode and failure policy. A policy that says “commit only after remote durable acknowledgement” must identify which standby qualifies and what the application does if that region or network path is down. PostgreSQL documents distinct synchronous commit levels and standby acknowledgement behavior in its replication chapter. PostgreSQL synchronous replication

Replication does not protect against every form of data loss. A mistaken delete, compromised credential, or destructive migration can be copied to the standby. Maintain backups and archived WAL that are isolated from the same credentials and failure modes. Test point-in-time recovery independently of failover. Use retention and access controls that make it possible to recover from an application-level mistake after both regions have faithfully replicated it.

Build a failover boundary across the whole service

A database promotion is one step in service recovery. List every component that must work in the secondary region:

  • Application images and compatible configuration for the last deployed release.
  • Database standby, archive access, replication monitoring, promotion and fencing tooling.
  • Secrets, encryption keys, certificate chains, and identity-provider client configuration.
  • Network routes, firewall rules, private endpoints, service discovery, and outbound allowlists.
  • Object storage, message brokers, caches, search indexes, and webhook delivery state.
  • DNS or global traffic routing, TLS certificates, connection draining, and health checks.
  • Runbooks, on-call access, audit logging, and an independent status communication path.

Classify each dependency as replicated, rebuilt, temporarily unavailable, or deliberately degraded. A cache may be safely cold-started. A search index may be rebuilt from the database. An object store may need cross-region replication or a restore process. An email provider may remain global, while a private identity endpoint may require a regional change. The failover plan should say which actions are automatic and which require an operator.

Use one controlled writer endpoint and keep connection pools ready to reconnect. DNS failover does not instantly replace established database connections, and application pools may retain broken sockets. Set health checks and pool connection lifetimes based on the platform’s behavior, then exercise a database endpoint change with live application processes. If a broker or worker fleet also changes region, make job handling idempotent because queued work can be replayed or observed more than once. See our worker quota guide and our durable workflow guide.

Prevent split brain before promoting a standby

The most dangerous failover mistake is promoting a standby while the old primary is still accepting writes. A network partition can make the primary unreachable from the standby without proving that the primary process is stopped. If both accept writes, their histories diverge. PostgreSQL warns that the former primary must be prevented from continuing as a primary after failover; fencing is required to avoid two servers believing they own writes. PostgreSQL failover and fencing guidance

Use an explicit fencing mechanism before promoting: terminate or isolate the old database, revoke its ability to accept application traffic, or use an infrastructure control that reliably removes it from service. A witness or quorum can reduce false failover in some designs, but it adds another component that needs independent placement and careful testing. A heartbeat alone can confuse a network partition with a failed host.

PostgreSQL provides promotion mechanisms such as pg_ctl promote and pg_promote(), but it does not supply the full system that detects failures and coordinates promotion. Choose and operate a failover manager or managed database mechanism that handles health detection, fencing, leader ownership, endpoint movement, and failover state. Confirm its behavior during control-plane outages, not only during a clean process shutdown.

When the old primary returns, keep it fenced. Do not let it rejoin as a writable node. Rebuild it as a standby from the new primary or use a supported rewind procedure after validating timeline and WAL conditions. PostgreSQL specifically calls out the need to recreate the former primary as a standby and recommends regular switching to test the procedure. PostgreSQL standby re-creation after failover

Write the recovery runbook as decision gates

A runbook should help an operator make safe choices under pressure. Avoid a list of commands that assumes every incident is identical. Define who declares a regional disaster, what evidence distinguishes a region outage from an application outage, and who may approve data-loss risk when the standby is behind.

  1. Declare and scope: Identify affected services and regions. Check the independent provider health source, application synthetic checks, database status, and network reachability. Do not promote based only on one failed health probe.
  2. Stop or fence writes: Disable writers in the old region and verify its database cannot accept application write traffic. If the original region may still be live, use the documented fencing action before proceeding.
  3. Assess the recovery point: Inspect the standby’s received and replayed WAL position, archive availability, and last known healthy replication time. Compare the possible data loss with the declared RPO and obtain the required decision when outside it.
  4. Promote once: Promote the chosen standby using the configured failover manager or the documented PostgreSQL procedure. Record the new timeline, region, and change owner.
  5. Move traffic and dependencies: Update the writer endpoint and application routing. Enable the secondary worker fleet and required credentials. Keep nonessential components read-only or degraded until their recovery is confirmed.
  6. Validate behavior: Run read and write synthetic checks, confirm transaction invariants, inspect queue and webhook backlogs, and verify error rates before increasing customer traffic.
  7. Protect the new primary: Confirm backups and WAL archiving work from the new region. Create a replacement standby and monitor replication before considering the environment restored.

Record timestamps for detection, declaration, fencing, promotion, routing, first successful write, and full recovery. These measurements reveal whether the RTO is spent waiting for human decisions, database replay, application boot, or routing. After the incident, compare the actual recovery point with the RPO and reconcile missing or duplicate side effects.

Test failover and failback, not just replica health

A replica streaming successfully proves that WAL is moving now. It does not prove that the region can take production traffic, that the promotion path is fenced, or that the application can reconnect. Schedule controlled exercises with production-like data size and a clear rollback plan. PostgreSQL recommends regular switching between primary and standby as a way to test the failover mechanism and keep procedures current. PostgreSQL failover testing recommendations

Exercise distinct scenarios: stop the database process, block the replication network, make the primary region unreachable, fail the routing control plane, and lose a dependency shared by both regions. A planned switchover is useful but is not equivalent to an unplanned failure. In a planned switchover, the old primary can usually be quiesced and the final WAL can be confirmed before promotion. An unplanned event may leave an uncertain replication gap.

Test backup restore to a clean environment and point-in-time recovery to a known timestamp. Test a failback separately: re-seed the old region from the new primary, ensure the replication direction is correct, validate lag, and schedule a controlled role switch only after readiness checks pass. Do not improvise reverse replication from a former primary with a divergent timeline.

Include the application layer. Confirm worker jobs do not apply duplicate charges, webhook deliveries retry safely, user sessions refresh, and the old region cannot accidentally reconnect with stale credentials. A database failover that corrupts external side effects is not a successful recovery.

Frequently asked questions

Does asynchronous PostgreSQL replication guarantee zero data loss?

No. Asynchronous streaming can leave committed WAL unapplied at the standby when the primary fails. Promotion may lose that unreplicated tail. Measure receive and replay positions, compare possible loss to the RPO, and choose synchronous replication only after evaluating its latency and availability tradeoffs.

Is a PostgreSQL standby a backup?

No. A standby follows changes from the primary, including accidental deletes and corrupting writes. Keep independent base backups and archived WAL with separate access controls, then rehearse point-in-time recovery as its own procedure.

Does PostgreSQL automatically promote the standby when the primary fails?

PostgreSQL supplies standby and promotion primitives, but not the complete failure detection and failover orchestration system. Use a managed database failover mechanism or an appropriately tested failover manager that includes fencing, promotion, and endpoint updates.

Can I fail back by simply changing DNS to the original region?

No. After promotion, the former primary has an older timeline and must be safely fenced and rebuilt or rewound as a standby from the new primary. Rejoin only after the direction of replication and data state are verified, then perform a planned switchover if desired.

Recovery readiness is an end-to-end property

Multi-region active-passive is effective when one writer remains authoritative, the standby’s replication behavior matches the RPO, the secondary region can run the service, and operators can fail over without split brain. Backups, WAL archives, application dependencies, routing, secrets, and job semantics all belong to the recovery design.

Set an objective, measure how closely the architecture meets it, and practice the full failover and failback path. If you are planning a regional recovery strategy for a PostgreSQL-backed product, talk with our engineering team about replication risk, fencing, recovery validation, and the operational runbook.

Dumb Potato Editorial

Putting this into practice?

Share the problem you’re solving and the tradeoffs you’re weighing with our engineering team.

See how we help with cloud and devops

Discuss your project