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:
| Component | Purpose |
|---|---|
| Primary PostgreSQL server | Accepts application writes |
| Standby server | Replays WAL and remains ready for promotion |
| Replication mode | Defines durability and latency trade-offs |
| Failure detector / orchestrator | Determines when the primary is no longer safe to use |
| Fencing mechanism | Prevents the old primary from continuing to accept writes |
| Writer endpoint | Routes applications to the active primary |
| Connection retry logic | Allows clients to recover after the writer changes |
| Monitoring | Tracks health, lag, replication, failover, and degraded redundancy |
| Backups / PITR | Provides 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:
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:
- Who decides the primary is actually unavailable?
- Which standby is eligible for promotion?
- How is the old primary prevented from returning as a writer?
- How does the writer endpoint move?
- How do application connections recover?
- 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 role | Primary objective | Main operating priority |
|---|---|---|
| HA standby | Become the next writer safely | Promotion readiness, low lag, predictable recovery |
| Read replica | Offload application reads | Read capacity and query usefulness |
| Reporting replica | Run analytical or long queries | Query availability, sometimes more tolerated lag |
| DR replica | Survive a wider failure boundary | Geographic/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:
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
DELETEorDROPoperations; - 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:
| Control | Main purpose |
|---|---|
| HA standby | Fast continuity after primary failure |
| Read replica | Read scaling |
| Backup | Independent recovery copy |
| PITR | Restore to a point before an unwanted change |
| DR architecture | Recover 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.
| Requirement | Recommended posture |
|---|---|
| Several hours of database downtime are acceptable | Prioritize tested backup/recovery first |
| Primary failure must recover quickly | Use a promotion-ready standby and tested failover path |
| Read traffic is the main constraint | Add read replicas; do not assume they are HA targets |
| Continuity and read scaling both matter | Separate HA and read-scaling roles unless intentionally combined |
| Application cannot reconnect safely | Fix reconnect/retry behavior before relying on automatic failover |
| Team cannot operate fencing/routing/orchestration | Prefer managed HA when the service fits |
| Custom topology or host-level control is mandatory | Self-host with an explicit orchestration and testing model |
Small teams should usually sequence reliability work in this order:
- establish reliable backups and PITR;
- prove restore procedures;
- make connection recovery and retries safe;
- define availability and data-loss targets;
- 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 responsibility | Managed PostgreSQL | Self-hosted PostgreSQL |
|---|---|---|
| Standby provisioning | Platform-managed within service scope | Team-owned |
| Replication configuration | Platform-managed | Team-owned |
| Failure detection | Platform-managed when HA is enabled | Team/orchestrator-owned |
| Promotion | Platform-managed | Team/orchestrator-owned |
| Old-primary fencing | Platform HA layer | Team-owned |
| Writer routing | Managed endpoint behavior | Team-designed |
| Application reconnects | Application team | Application team |
| Query/schema correctness | Application team | Application team |
| Backup/PITR | Separate recovery layer | Team-designed unless provided separately |
| Failover validation | Shared operating responsibility | Team-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.