PostgreSQL High Availability: Architecture, Failover & Replication

Serdar Tekin
Serdar Tekin
Co-Founder & CTO
Updated Sep 14, 202618 min read
Written for: Developers, founders, database operators, and small platform teams designing PostgreSQL high availability, replication, failover, and production continuity.
PostgreSQLHigh AvailabilityPostgreSQL HAFailoverReplicationRead ReplicasManaged Databases
Last reviewed:
Guide
PostgreSQL High Availability: Architecture, Failover & Replication
rafftechnologies.com/learn
On this page

Key Takeaways

PostgreSQL high availability requires more than a replica: safe failure detection, promotion, fencing, writer routing, application reconnects, monitoring, and redundancy restoration all matter. Synchronous replication can reduce failover data loss but adds latency and availability dependencies; asynchronous replication lowers coupling but can leave recent acknowledged transactions at risk. Read replicas and HA standbys have different operating goals. Managed HA transfers more of the failover control plane to the provider, while self-hosted HA requires the team to operate orchestration, fencing, routing, monitoring, recovery, and testing.

PostgreSQL high availability (HA) is an architecture for keeping database service available when the current primary fails. A reliable design needs more than replication: it needs a promotion-ready standby, failure detection, safe failover, protection against split brain, a stable writer endpoint, application reconnect behavior, and a process for restoring redundancy after the incident.

For most small teams, the practical question is not simply “do we have a replica?” It is whether the database can establish one safe writable primary and resume application traffic within the required recovery window.

Raff Technologies supports both operating models: teams can build PostgreSQL HA themselves on cloud VMs or use Managed PostgreSQL when they want the platform to own more of the standby, failover, monitoring, and recovery path.

PostgreSQL high availability: quick answer

A basic PostgreSQL HA architecture normally includes these components:

ComponentPurpose
Primary PostgreSQL serverAccepts application writes
Standby serverReplays WAL and remains ready for promotion
Replication modeDefines durability and latency trade-offs
Failure detector / orchestratorDetermines when the primary is no longer safe to use
Fencing mechanismPrevents the old primary from continuing to accept writes
Writer endpointRoutes applications to the active primary
Connection retry logicAllows clients to recover after the writer changes
MonitoringTracks health, lag, replication, failover, and degraded redundancy
Backups / PITRProvides historical recovery outside the HA path

The most important distinction is this:

Replication copies database state. High availability turns that replica into a safe, tested service-continuity system.

A read replica may be useful without being a valid HA target. A standby becomes part of HA only when promotion, fencing, routing, reconnects, and recovery are deliberately designed and tested.

PostgreSQL HA architecture starts with the failure boundary

High availability should begin with the failure you are trying to survive.

Common targets include:

  • PostgreSQL process failure;
  • primary VM or host failure;
  • storage failure affecting the primary;
  • planned maintenance that requires replacing the writer;
  • loss of connectivity to one database node;
  • a zone-level failure when nodes are placed in separate failure domains.

Different failures require different architecture.

A standby on the same host protects against a PostgreSQL process problem but not host loss. A standby on another VM improves host resilience. A standby in another failure domain can protect against a wider infrastructure failure, but replication latency and network behavior become more important.

Before choosing topology, define two targets:

  • How long can writes be unavailable? This shapes the failover and reconnect path.
  • How much recent committed data can be lost? This shapes synchronous versus asynchronous replication and recovery decisions.

Those targets are related to RTO and RPO, but HA does not replace backup and disaster-recovery planning. Use PostgreSQL Replication vs Backups vs Snapshots for the historical recovery layer.

A common PostgreSQL high-availability architecture

A production HA topology can be represented as:

Text
Application | | writer endpoint / service discovery v +-------------------+ | Current primary | | PostgreSQL writer | +-------------------+ | | WAL streaming v +-------------------+ | HA standby | | promotion-ready | +-------------------+ Monitoring / orchestrator | detects failure | fences old primary | promotes standby | updates writer route v Application reconnects to new primary

The exact implementation may use a managed database service or a self-hosted orchestration layer, but the responsibilities are similar.

The architecture is incomplete if it answers only “where is the replica?” It must also answer:

  1. Who decides the primary is actually unavailable?
  2. Which standby is eligible for promotion?
  3. How is the old primary prevented from returning as a writer?
  4. How does the writer endpoint move?
  5. How do application connections recover?
  6. How is a new standby created after failover?

If any of those answers depends on manual improvisation during an outage, the system is not yet fully operationalized as HA.

Synchronous vs asynchronous replication changes the HA trade-off

PostgreSQL can use synchronous or asynchronous replication, and the choice affects durability, latency, and availability behavior.

Asynchronous replication

With asynchronous replication, the primary can acknowledge a commit before a standby has confirmed that change.

Advantages:

  • lower write latency;
  • less dependency on standby/network responsiveness;
  • simpler performance characteristics across slower links.

Trade-off:

  • if the primary fails before recent WAL reaches the standby, promotion may lose some recently acknowledged transactions.

This can be acceptable when a small amount of recent data loss is within the business recovery target.

Synchronous replication

With synchronous replication, commit acknowledgement can wait for the configured synchronous standby condition.

Advantages:

  • reduces the risk that a successfully acknowledged transaction is missing after failover;
  • makes the standby a stronger candidate for low-data-loss HA.

Trade-offs:

  • write latency includes the synchronous replication path;
  • a slow or unreachable synchronous standby can affect write availability depending on configuration;
  • topology and network quality matter more.

PostgreSQL's documentation explicitly describes the functional-versus-performance trade-off: synchronous designs improve failover consistency but can impose meaningful latency when the replication path is slow.

The correct question is not “is synchronous better?” It is:

Does the workload need the additional durability enough to accept the latency and availability dependency it creates?

HA standby and read replica are different roles

A hot standby can serve read-only queries while replaying WAL, which makes it possible to use replicas for both availability and read scaling. But the two roles optimize for different things.

Replica rolePrimary objectiveMain operating priority
HA standbyBecome the next writer safelyPromotion readiness, low lag, predictable recovery
Read replicaOffload application readsRead capacity and query usefulness
Reporting replicaRun analytical or long queriesQuery availability, sometimes more tolerated lag
DR replicaSurvive a wider failure boundaryGeographic/failure-domain separation and recoverability

A reporting replica may intentionally tolerate more lag or run queries that interfere with replay. That makes it useful for analytics but potentially poor as an immediate failover target.

A useful operating rule is:

Use read replicas to scale reads. Use an HA standby to protect writer continuity. Combine the roles only when lag, query workload, promotion behavior, and recovery are designed for both.

PostgreSQL failover is more than promotion

Promotion is only one stage in a complete failover.

A safe failover path normally includes:

1. Detect the primary failure

Monitoring or orchestration must determine whether the primary is actually unusable.

A short packet-loss event, overloaded host, failed health check, or monitoring outage should not automatically create a second writer.

2. Confirm an eligible standby

The candidate should be healthy, replaying WAL, and inside the accepted lag or durability threshold.

3. Fence the old primary

Fencing means preventing the old writer from continuing to accept writes.

This may involve powering down the old node, revoking its network path, removing it from routing, or another mechanism appropriate to the platform.

4. Promote the standby

The selected standby becomes writable.

5. Move the writer endpoint

Applications need a stable way to find the new writer. Depending on the architecture this may be handled by a managed service endpoint, proxy, virtual IP, load-balancing layer, DNS, or service discovery.

6. Reconnect applications

Existing PostgreSQL connections do not magically become connections to the new primary. Pools, workers, APIs, and scheduled jobs must reconnect.

7. Validate writes

The failover is not complete until the application can successfully perform critical database operations against the new writer.

8. Restore redundancy

After promotion, the system may temporarily have only one healthy database node. A replacement standby needs to be created and replication health restored.

A high-availability design therefore needs both a failover procedure and a post-failover recovery procedure.

Fencing prevents split brain

One of the most important HA concepts is preventing two PostgreSQL primaries from accepting writes independently.

Consider this failure:

Text
Primary A loses network connectivity ↓ Standby B is promoted ↓ Applications begin writing to B ↓ Primary A reconnects and still believes it is primary

If A can accept new writes after B is promoted, the database can develop two independent histories.

PostgreSQL streaming replication does not by itself solve this external coordination problem. A complete HA system therefore needs a method to ensure that the previous writer cannot return to service until it has been safely rejoined, rebuilt, or otherwise reconciled.

For self-hosted HA, this is one reason teams commonly use an orchestration layer rather than treating pg_ctl promote as the entire failover design.

Self-hosted PostgreSQL HA needs an orchestration layer

PostgreSQL provides replication, standby, promotion, and recovery primitives, but a self-hosted deployment still needs a system around them for automatic HA.

Common responsibilities include:

  • health checking;
  • leader/primary election or authority;
  • promotion decisions;
  • fencing or node isolation;
  • writer endpoint updates;
  • standby reconfiguration;
  • topology state;
  • alerting;
  • operator workflows after failover.

Self-hosted ecosystems often use tools such as Patroni, repmgr, Pgpool-II, HAProxy, Keepalived, or cloud-native service-discovery components in different combinations. These tools do not all solve the same problem, so architecture should be based on the exact responsibilities required rather than selecting one product name and assuming HA is complete.

For a small team, the operational question is important: who maintains the HA control plane itself?

If the team cannot confidently test and repair the orchestration layer during an outage, a managed HA service may be the lower-risk operating model.

Replication lag is a failover-readiness signal

Replication lag is the distance between the primary's current state and what the standby has received or replayed.

For HA, lag is important because promotion turns the standby's current state into the authoritative writable state.

Useful questions include:

  • Is WAL still reaching the standby?
  • Is replay keeping up under normal write traffic?
  • Is lag increasing steadily?
  • Are standby queries delaying WAL replay?
  • Is the candidate still within the acceptable failover threshold?
  • Would the system allow promotion at the current replication state?

Lag should be interpreted with the replication mode.

With asynchronous replication, increasing lag can directly increase the amount of recent data at risk during primary failure. With synchronous replication, lag and standby health can instead affect write performance or availability depending on configuration.

Do not treat lag as a single dashboard number. The underlying cause may be disk throughput, network latency, CPU pressure, long-running standby queries, checkpoint behavior, or primary workload growth.

Application reconnect behavior determines whether HA works for users

A database can complete failover correctly while the application still appears down.

When the writer changes, applications may experience:

  • broken database connections;
  • interrupted transactions;
  • connection-pool errors;
  • workers retrying simultaneously;
  • uncertain transaction outcome near commit time;
  • caches or services still pointing at old state.

A production HA plan should define:

  • writer discovery: how clients locate the current primary;
  • retry policy: which failures should trigger reconnects;
  • backoff: how clients avoid a reconnect storm;
  • transaction handling: what happens when the connection disappears during commit;
  • idempotency: whether retrying an operation can create duplicate side effects;
  • pool recovery: how dead connections are discarded;
  • health checks: whether application health tests include database writes where appropriate.

Connection-pool tuning itself belongs in PostgreSQL Connection Pooling: PgBouncer, Limits & SaaS Workloads. The HA requirement is that the pool can recover cleanly when the writer endpoint changes.

Database HA is complete only when application writes resume safely against the new primary.

PostgreSQL HA does not replace backups or PITR

A standby follows the primary's current state. That is useful for availability, but it also means valid-looking destructive changes can propagate.

Examples include:

  • accidental DELETE or DROP operations;
  • incorrect migrations;
  • application bugs that corrupt data;
  • compromised credentials performing destructive writes.

HA may keep the database online through those events while preserving the wrong state perfectly.

That is why production PostgreSQL should treat these as separate controls:

ControlMain purpose
HA standbyFast continuity after primary failure
Read replicaRead scaling
BackupIndependent recovery copy
PITRRestore to a point before an unwanted change
DR architectureRecover from a wider service or location failure

Use PostgreSQL Replication vs Backups vs Snapshots for the full recovery model.

When PostgreSQL high availability is worth the complexity

Not every production database needs automatic HA.

RequirementRecommended posture
Several hours of database downtime are acceptablePrioritize tested backup/recovery first
Primary failure must recover quicklyUse a promotion-ready standby and tested failover path
Read traffic is the main constraintAdd read replicas; do not assume they are HA targets
Continuity and read scaling both matterSeparate HA and read-scaling roles unless intentionally combined
Application cannot reconnect safelyFix reconnect/retry behavior before relying on automatic failover
Team cannot operate fencing/routing/orchestrationPrefer managed HA when the service fits
Custom topology or host-level control is mandatorySelf-host with an explicit orchestration and testing model

Small teams should usually sequence reliability work in this order:

  1. establish reliable backups and PITR;
  2. prove restore procedures;
  3. make connection recovery and retries safe;
  4. define availability and data-loss targets;
  5. add HA when the continuity requirement justifies the extra moving parts.

Adding a standby before proving recovery can create the appearance of reliability without covering destructive-data failures.

Managed vs self-hosted PostgreSQL HA

The PostgreSQL concepts stay the same, but the ownership boundary changes significantly.

HA responsibilityManaged PostgreSQLSelf-hosted PostgreSQL
Standby provisioningPlatform-managed within service scopeTeam-owned
Replication configurationPlatform-managedTeam-owned
Failure detectionPlatform-managed when HA is enabledTeam/orchestrator-owned
PromotionPlatform-managedTeam/orchestrator-owned
Old-primary fencingPlatform HA layerTeam-owned
Writer routingManaged endpoint behaviorTeam-designed
Application reconnectsApplication teamApplication team
Query/schema correctnessApplication teamApplication team
Backup/PITRSeparate recovery layerTeam-designed unless provided separately
Failover validationShared operating responsibilityTeam-owned

Raff's live Managed PostgreSQL product currently describes HA as a primary plus synchronous standby in separate zones with automatic failover. The product page also lists PostgreSQL 14–16, PITR, read replicas, connection pooling, monitoring, and private networking as current service capabilities.

Because product versions, pricing, and service limits change faster than editorial guidance, verify the live Raff Managed PostgreSQL page before making a production decision.

For self-hosted PostgreSQL on a Raff VM, the team gets deeper control over software, topology, storage, and orchestration choices, but also owns patching, monitoring, failover automation, fencing, routing, standby rebuilds, backups, and incident response.

PostgreSQL HA testing checklist

An HA diagram is not evidence that failover works.

A useful failover exercise should prove the full service path:

  • Primary failure is detected inside the expected window.
  • The intended standby is healthy and eligible for promotion.
  • Replication state is inside the accepted threshold.
  • The old primary cannot continue accepting writes.
  • The standby is promoted successfully.
  • The writer endpoint moves to the new primary.
  • Applications establish new connections.
  • Connection pools discard stale sessions.
  • In-flight transactions follow the expected retry behavior.
  • Background jobs and workers recover safely.
  • Critical application writes succeed after failover.
  • Monitoring identifies the new primary correctly.
  • A replacement standby is created.
  • Redundancy is restored.
  • The measured interruption matches the availability target.

Planned failover exercises are valuable because they test assumptions before a real infrastructure failure makes the test mandatory.

The strongest evidence of PostgreSQL HA is not “we have a replica.” It is a recently validated transition from one writable primary to another with correct application behavior afterward.

Conclusion

PostgreSQL high availability is an architecture for safe writer continuity, not simply a replication checkbox.

A production HA design needs a clear failure boundary, an appropriate synchronous or asynchronous replication model, a promotion-ready standby, reliable failure detection, fencing, writer routing, application reconnect logic, lag monitoring, and a process for rebuilding redundancy after failover.

Use read replicas for read scaling unless they are deliberately qualified as failover targets. Keep backups and PITR as a separate historical recovery layer. For small teams, choose managed HA when operating the failover control plane would consume engineering capacity without creating product value; self-host when deeper control is a real requirement and the team can own the entire operating model.

Compare Raff Managed PostgreSQL with self-hosted PostgreSQL when deciding who should own standby operations, failover, backups, and monitoring.

Was this article helpful?
Serdar Tekin
Serdar Tekin
Co-Founder & CTO

Co-Founder & CTO at Raff, focused on cloud infrastructure, systems architecture, security, reliability, and production operations.

Put it into practice

Spin up a Raff server, follow the steps above on real infrastructure, and you are live. Linux or Windows, backed by a 14-day money-back guarantee.

Frequently asked questions

What is PostgreSQL high availability?
PostgreSQL high availability is an architecture that keeps database service available through selected primary failures by combining a promotion-ready standby with failure detection, safe failover, fencing, writer routing, application reconnection, and redundancy restoration.
How do you make PostgreSQL highly available?
Use at least one suitable standby, define synchronous or asynchronous replication according to durability needs, add reliable failure detection and promotion orchestration, prevent the old primary from accepting writes after failover, provide a stable writer endpoint, and test application reconnection and failover regularly.
What is the difference between synchronous and asynchronous PostgreSQL replication?
Synchronous replication can wait for a standby before acknowledging commits, reducing failover data-loss risk but adding latency and a dependency on standby health. Asynchronous replication lets the primary acknowledge commits sooner, but recent acknowledged transactions may not yet exist on the standby when a failure occurs.
Is a PostgreSQL read replica the same as high availability?
No. A read replica primarily provides read capacity. It becomes a credible HA target only when lag, promotion, fencing, writer routing, application reconnects, and post-failover recovery are explicitly designed and tested.
Does PostgreSQL automatically fail over by itself?
PostgreSQL provides standby and promotion mechanisms, but a complete automatic HA system also needs external failure detection, coordination, fencing, routing, and operating logic or a managed service that provides those functions.
Why is fencing important in PostgreSQL failover?
Fencing prevents the previous primary from returning and accepting writes after another standby has been promoted. Without it, two writable primaries can create conflicting database histories.
Does PostgreSQL high availability replace backups?
No. HA protects service continuity after selected infrastructure failures. Backups and point-in-time recovery protect historical recovery after accidental deletion, bad migrations, corruption, or other unwanted data changes.
How does Raff Managed PostgreSQL handle high availability?
Raff's current Managed PostgreSQL product describes HA as a primary with a synchronous standby in separate zones and automatic failover. Check the live product page for current versions, pricing, availability, and service limits before production deployment.