Why PostgreSQL failover testing decides whether a cluster is ready
Failover testing shows what actually happens to writes, clients and the operator when a server fails, and a passing design document is not evidence. A diagram can show a primary, two standbys and a load balancer, but it cannot show whether a committed transaction survives the switch, how long an application waits before it reconnects, or whether the on-call engineer knows which command to run at 3 a.m. Those answers only come from breaking the cluster on purpose and measuring what follows.
PostgreSQL does not detect a failed primary or promote a standby by itself. The PostgreSQL failover documentation is explicit that software to detect the failure and notify the standby must come from outside the server, so the tests have to cover the external failover tooling, the connection path that clients use after promotion, and the people who run the cluster. In practice that means checking how the failover manager decides the primary is gone, how the proxy or virtual IP moves to the new primary, whether connection poolers such as PgBouncer drop and rebuild their server connections correctly, and whether runbook steps match what the tools actually do.
Teams need this work at three points. The first is before go-live, when a cluster has never been exercised under failure. The second is after any change to topology, PostgreSQL major version, failover tooling, proxy configuration or network layout, since each change can quietly alter promotion behavior. The third is before an audit that asks for evidence of tested recovery. Confirm with your auditor which artifacts they expect, such as dated test records, measured reconnection times and signed runbook reviews, because those expectations decide how the test plan should be written and retained.
How a planned switchover and an unplanned failover move through the cluster
The diagram starts with a client sending writes through a routing layer to the current primary, which streams WAL to a standby. A planned switchover is initiated by the operator, while an unplanned failover begins when the external failover tool detects that the primary is gone and promotes a standby. Each path ends in checks: the new primary must accept writes, clients must reconnect through the router, and the old primary must be fenced or rejoin as a standby. The exact tool is chosen in sibling pages, so the diagram names roles rather than products.
Planned and unplanned failover paths, with the checks a failover test verifies.
What the tests must cover beyond PostgreSQL itself
PostgreSQL gives you the replication half of high availability: hot standby servers, synchronous replication where a commit waits for standbys, and asynchronous replication. It does not detect that the primary has failed, decide which standby should take over, prevent the old primary from accepting writes, or move client connections to the new primary. Those jobs belong to external components, whether that is an HA manager, a fencing mechanism, a virtual IP or load balancer, and a connection pooler. A failover test that only checks PostgreSQL has a new writable primary has verified the easy part. Before testing, write down which component owns each of the four jobs in your design, and confirm with its vendor or documentation what it does when the network splits rather than when a process simply stops.
A cluster can pass every replication check and still fail its clients. Replication health tells you that standbys are streaming and lag is small, but it says nothing about where applications send their writes. A load balancer or DNS record that still points at the old primary, a health check that only tests for a listening port, or a pooler that keeps server connections open to a host that no longer accepts writes can all keep serving errors or, worse, stale reads for minutes. Illustrative case: the old primary is isolated but still reachable from some application subnets, so half the clients reconnect to the new leader while the rest keep writing to a node that has been fenced in name only. The test therefore has to measure what the client sees, using the same DNS names, routing and pooler settings that production uses, and confirm that the old primary rejects writes from every path. Ask your pooler and routing vendors how they detect a dead backend and how quickly they drop cached connections, and record the answers in the runbook.
Which fault scenarios to test and what each one proves
This table maps each failure scenario to what it simulates, what a passing test proves, and what the operator should measure. Agree the pass criterion for every row before the test runs, or the result will be argued after the fact. Use it to decide which tests belong in the go-live gate and which can wait for a scheduled game day.
| Scenario | What it simulates | What the test proves | What to measure |
|---|---|---|---|
| Planned switchover | An operator promotes a standby on purpose during a maintenance window, with the primary still healthy. | The runbook works as written, the old primary rejoins as a standby, and no committed writes are lost. Pass criterion: agreed before the run, for example zero lost writes and no manual data repair. | Time to new primary accepting writes, client reconnection time, replication state after rejoin, runbook steps that needed improvisation. |
| Killing the PostgreSQL primary process | The postmaster or backend crashes abruptly, as from an out-of-memory kill or a bad restart. | Automation detects the failure, promotes the correct standby, and fences the old primary so it cannot accept writes. Pass criterion: one primary at all times and a defined maximum outage agreed with the business. | Detection time, promotion time, count of primaries observed, WAL position of the new leader versus the last acknowledged commit. |
| Killing the failover tool or its agent | The Patroni, repmgrd or pg_auto_failover process stops on the primary or a standby while PostgreSQL keeps running. | The cluster does not split or promote unnecessarily, and the tool recovers or alerts operators. Pass criterion: no unplanned promotion and a monitored alert fires within the agreed window. | Whether the database stays writable, time until the agent restarts, alert delivery, any unexpected role changes. |
| Network partition between primary and standbys | Traffic is blocked between the primary and some or all standbys, while clients may still reach the primary. | The side that loses quorum does not keep accepting writes, and the cluster has one leader after the partition heals. Pass criterion: no dual primaries and no acknowledged commits lost. | Primaries seen by each node during the fault, client errors, replication lag before and after healing, timeline changes. |
| Loss of the distributed configuration store quorum | Enough etcd, Consul or ZooKeeper members fail that the store has no leader, where the failover design depends on one. | The database keeps its current leader safely or stops writing as designed, and recovers without manual edits. Pass criterion: documented behavior confirmed by the tool vendor's docs and the test. | Whether writes continue, leader lock expiry timing, recovery steps needed after the store returns. |
| Disk full or slow I/O on the primary | The WAL or data volume fills, or storage latency rises sharply, without the PostgreSQL process crashing. | Failover logic handles a degraded but running primary as designed, and alerts fire before the volume is exhausted. Pass criterion: the agreed action is taken and no corruption occurs. | Free space at alert and at failure, WAL directory growth, I/O latency, whether the tool promotes or keeps a degraded leader. |
| Lagging or disconnected synchronous standby | A synchronous standby falls behind or drops, so commits must wait or fall back under the configured policy. | Commit behavior matches the chosen synchronous setting, and the cluster recovers its sync set without manual steps. Pass criterion: agreed write latency ceiling and a confirmed outcome for commits during the fault. | Commit latency during the fault, synchronous standby state, time to restore full synchronous replication, any blocked client sessions. |
The test sequence from rehearsal to a signed-off runbook
The sequence turns a cluster design into evidence: a verified backup, measured baseline, planned switchovers, then unplanned faults of rising severity, with timestamps that let the team reconstruct every client reconnection.
Confirm a recent verified backup exists
Before any fault is injected, the team confirms a recent base backup and archived WAL are present and that a restore of them has been tested on a separate host. The test lead, usually the DBA or platform engineer on the cluster, records the backup label, the time it was taken and the archive position it covers. Done means a restore to a scratch environment reaches a consistent state, so a destructive test can be rolled back if the cluster does not recover as designed. Ask your team to confirm the restore path in writing before the window opens.
Record baseline lag and client behavior
Before testing, the team records replication lag on every standby, the replication state reported by the primary, and how long a client takes to connect and run a write through the routing layer. The load generator should run a steady, known workload that exercises the same connection path applications use, including any pooler. The output is a baseline sheet with lag figures, connection timings and error counts. Without this baseline, a later result cannot be judged as normal or degraded.
Run planned switchovers first
The team performs one planned switchover to each standby in turn, using the failover tool's documented switchover procedure rather than stopping the server by hand. After each switchover, the test lead checks that the new primary accepts writes, that the old primary refuses writes, and that every remaining replica is streaming from the new primary. Done means all three checks pass, the routing layer points at the new primary, and the workload resumes. Planned switchovers prove the procedure and the client path before the cluster sees faults.
Inject unplanned faults in increasing severity
Unplanned tests follow a fixed order, starting with the least disruptive: stopping the PostgreSQL process cleanly, then killing it, then isolating the primary from the network, then faulting its disk or its consensus store. Each fault is run once per cycle with the same workload. For each fault the team checks that exactly one primary exists, that the failover completed without manual steps, and that the fenced former primary cannot accept writes. Any fault that needs manual intervention is a finding, not a pass.
Capture timestamps and logs for every action
Every action, including fault injection, detection, promotion, routing change and client recovery, is recorded with a timestamp from a synchronized clock on each host. The team collects PostgreSQL server logs, failover tool logs, routing layer logs and the load generator output into one place, keyed by a test identifier. Done means the reconnection time for each fault can be rebuilt from the first failed client request to the first successful write. A timing figure that cannot be traced to these logs should not be reported.
Document findings and fix the runbook
The team turns each test into a written result with the fault, the expected behavior, the observed behavior and the measured reconnection time. Each gap between the runbook and the observed behavior is either fixed in the cluster configuration or corrected in the procedure. Operators who did not design the cluster should perform the steps from the runbook alone, with the test lead observing. Done means the runbook matches what happened, and every step has a check that an operator can confirm.
Rerun the full set after any change
Any change to PostgreSQL settings, the failover tool, the consensus store, the pooler, network paths or the routing layer invalidates earlier results for the affected tests. The team reruns the complete set, from the backup check through the unplanned faults, and compares timings with the baseline. Sign-off is given only after a full pass on the current configuration, recorded with the software versions in use and the date of the run. Ask the platform owner to confirm the sign-off criteria before the first test.
Operational risks of failover tests and how to contain them
Failover tests are useful only if they do not cause the outage they are meant to rehearse. The cards below cover the risks that most often turn a planned switchover or fault injection into a data or access incident, and the containment step for each.
Data loss during live-write tests
Killing a primary or cutting its replication while the application is writing can lose transactions that were acknowledged but not yet replicated, depending on the synchronous_commit and standby settings in use. Before any test, confirm the replication mode, record the replay position of each standby, and run the test on a staging copy with production-like topology and synthetic write load. Compare the committed transaction IDs on the old and new primary after each run.
Split-brain from incomplete fencing
If the old primary is still accepting writes when a standby is promoted, two servers accept writes and the data diverges. Confirm that the fencing method, such as a watchdog, a DCS leader lock or a power-off action, works before killing any process, and verify that the old primary refuses writes after the test. Treat a test that produces two writable primaries as a failed test and stop it immediately.
Tests against production traffic
Running switchovers or fault injection on production without a tested rollback path turns a rehearsal into an incident. Agree a rollback point in the runbook, such as restoring the original primary role with a planned switchover, and define the stop conditions in advance. Schedule tests in a window where the operators who can make decisions are present and reachable.
Credentials and certificates in test scripts
Failover test scripts often contain replication passwords, superuser credentials or private keys pasted in for convenience, and those files then sit in shared repositories or shell histories. Keep secrets in your secrets manager or a protected file readable only by the test operator, and rotate any credential that appeared in a script. Use the pgpass file or environment variables rather than inline passwords, and review scripts before they are committed.
Test artifacts exposing data
Logs from failover tests, including postgresql.log, client error output and connection traces, can contain query text, row values or user identifiers. Set a retention period for test output, restrict who can read it, and redact application payloads before sharing results with other teams. Record reconnection times and error counts, not sample rows.
Passing tests under light load
A switchover that completes in seconds with no client traffic says little about how long reconnection takes under real connection counts and write rates. Run the test at a load close to peak, with the pooler and application connection settings you will use in production, and measure client reconnection time from the application side. Record the load profile with each result so the outcome can be compared with later runs.
Measuring client reconnection time without guessing
Define reconnection time as the interval from fault injection to the first successful write issued by a real application client, not the moment a failover tool reports that a standby was promoted. A tool's promotion timestamp tells you when the database changed role, but it says nothing about whether the application got back in. Record the fault start (the moment you kill the process, drop the network path or fill the disk), then timestamp each later point: detection by the failover tool, promotion of the new primary, the routing change in HAProxy or the virtual IP move, recovery of the connection pooler, and the first committed write from the application. Each gap shows where the time went, which matters more than the total when a number looks wrong.
Connection poolers such as PgBouncer sit in this path, so they change the result. A pooler can keep client sessions attached to dead server connections until its own timeouts expire, or it can reconnect quickly once the routing target changes. Pin the PgBouncer version under test and record it in the test report, because pooler behavior changes between releases. PgBouncer 1.26.1, released October 14, 2026, is one current release to confirm against the project's site before you choose a version. Run the same fault with the pooler in place and bypassed, so the difference is visible rather than assumed.
Confirm how long each client library and application retries before it gives up, and whether the retry logic reconnects on a new connection or reuses a stale one. Set those values in the test plan, not from memory. Use a probe that writes a timestamped row at a fixed interval and logs failures with their error text, then run the fault several times and compare the spread of results. A single run that looks fast often reflects luck in timing. If the retry window is shorter than the measured recovery, the cluster may be working as designed while users still see errors, and the runbook has to say so.
Writing runbooks for the people who will use them under pressure
The operator needs a short, ordered procedure that works without the person who wrote it. Start by confirming the outage is real and not a monitoring or client-side fault, then read the cluster state before changing anything.
- Confirm the outage: Check from two vantage points, such as an application host and an external probe, and record the time the first symptom was seen.
- Check cluster state: Run
SELECT pg_is_in_recovery();on each node to see which one is the primary, then runSELECT * FROM pg_stat_replication;on the primary to see which standbys are attached and how far behind they are. - Decide between waiting and switching over: Use the thresholds the platform team wrote into the runbook so the decision does not depend on judgment made at 3 a.m. Waiting suits a brief fault that is already being resolved, while switching over suits a primary that will not return within the agreed window.
- Run the agreed commands: Execute only the steps in the runbook for your failover tool, log each command with its timestamp, and escalate if the output differs from the documented expected result.
Before any shift uses the runbook, confirm each command and its expected output on a test cluster running the same PostgreSQL major version.
The platform engineer owns the decisions the operator should not have to make alone: which faults trigger a switchover, how to roll back, and how a failed node returns to service as a standby. Write these as explicit branches, each with a named owner and a verification step.
- Decision points: For each fault type, such as a killed process, a network partition, a full disk or storage latency, define whether the cluster should wait, fail over or fence the old primary first, and who approves a manual switchover.
- Rollback path: Document how to return the original primary to service if the switchover completes but the new primary shows problems. Include whether writes accepted by the new primary must be reconciled before the old node rejoins.
- Rebuild a failed node: Take a new base backup from the current primary with
pg_basebackup, start the node as a standby with replication configured, and confirm it reports streaming status before counting it as redundant again. The high availability documentation describes the standby types and their trade-offs. - Replication slots and WAL: Confirm that the rebuilt standby's replication slot exists and that the primary has enough disk headroom to hold WAL while the standby catches up.
Check that every branch names a decision owner and a verification step, because a branch without an owner stalls during a real incident.
The reviewer does not run the failover but needs evidence that the procedure works, was tested as written and is retested after changes. Ask for records that an independent reader can follow from the test plan to the result.
- Test dates and versions: Each test record should show the date, the PostgreSQL version, the cluster topology and the runbook revision used. Confirm the PostgreSQL version is still within the community support window when the test was run.
- Pass criteria: Each test should state its expected result before it runs, such as the new primary accepting writes and client reconnection completing within the agreed time. Pass or fail should be settled by the written criteria, not by the team after the fact.
- Timestamps and logs: Keep the fault injection time, the detection time, the promotion time and the first successful client write. Pull these from PostgreSQL logs and application logs whose clocks are synchronized.
- Retest record: After each change to PostgreSQL, the failover tool, the network or the runbook, record which tests were rerun and their results. Reviewers look for any gap between the last change and the last passing test.
Confirm that the evidence is stored outside the cluster it describes, so it survives an incident on that cluster.
Limits to confirm in your environment before scheduling tests
Failover tests only prove something when the behavior under test is the behavior you actually run. The cards below cover the facts that change test results, and each one is a question to settle with the vendor, the project or your own environment before a test window is booked.
Tool and version failover behavior
Confirm exactly how your chosen failover tool and its version promote a standby, fence the old primary and update routing. Behavior differs between releases, and a test written against documentation for one version can pass or fail for reasons that do not apply to the version you run. Ask the project which default settings change promotion timing, and record the version string in every test report so results can be repeated.
PostgreSQL failover docsPostgreSQL version and support end date
Check which PostgreSQL major version you run and when its support ends. A runbook written for a version that is near end of life will need rework during the same quarter it is adopted. Confirm the version against the supported-versions list, note the end-of-support date in the runbook header, and plan any upgrade so it does not land in the middle of a failover test cycle.
- Oldest supported major
- 14
Synchronous replication and standby failure
Confirm whether synchronous_standby_names is set, which standbys it names and what synchronous_commit is set to. If a synchronous standby fails, commits may wait or the primary may stop accepting writes, depending on the configuration. Test the case where the synchronous standby disappears, not only the primary, and record how long client writes stall before the cluster accepts them again.
Network paths and firewall rules
List every path between cluster members, the consensus store, the load balancer or virtual IP and the clients, including the ports for replication, the coordination service and health checks. Failover tools rely on those paths to detect failure and to decide which node may lead. Confirm with the network team that firewall rules and routing allow the tool's health checks to reach each node during a simulated partition, not only during normal operation.
Backup and restore time available
Find out how long a full restore and point-in-time recovery take on your hardware, and how much time your recovery targets allow. A failover test proves that a standby takes over, but it does not prove that a corrupted or lost cluster can be rebuilt in time. Ask the backup owner for the most recent measured restore duration, the WAL archive retention in place, and who approves a restore decision during an incident.
Continuous archiving docsTest environment matching production
Confirm that the test cluster matches production in node count, PostgreSQL and tool versions, configuration, storage type, network path and data volume. Failover time depends on replay lag, connection counts and the size of the data that must be checked before promotion. A test that runs against an empty, single-network copy can report reassuring numbers that production will not reproduce, so write the known differences into the test report.
Questions buyers ask about PostgreSQL failover testing
How much effort does PostgreSQL failover testing take?
The effort depends mainly on how many fault scenarios you need to prove, how many nodes are in the cluster, and how many client applications must reconnect cleanly. A three-node cluster with planned switchovers, a process kill, a network partition and a disk fault is a bounded job. Each additional scenario adds setup, execution, evidence capture and a retest path. Each client application adds a reconnection measurement that needs its owner present. Ask for the scenario list, the node count, the list of applications in scope and the number of test rounds in the written scope. Effort is one-time for the first full test pass, then recurs with each retest after a change to the topology, the PostgreSQL version, the failover tooling or the connection layer. Ask whether retesting after minor changes is included or billed separately.
How long does failover testing take to schedule and complete?
The schedule is set by environment availability and change control more than by the test steps themselves. Test work needs a staging environment that matches production topology, a window where faults can be injected without affecting other users, and operators who can watch the cluster during each run. Application owners must also be available to confirm reconnection behavior. Ask for a written timeline that separates preparation, the test rounds, the findings period and the retest. Ask who approves each change window and how long a failed test takes to rerun. A fixed-scope agreement fixes deliverables and dates before work starts, so ask what happens to dates if a staging environment is late or a finding requires a configuration change first.
What does the client need to provide for failover testing?
The client provides staging access, change windows, named operators and application owners for reconnection tests. Staging access should include the database nodes, the load balancer or virtual IP layer, the distributed configuration store if one is used, and the monitoring that records failover events. Change windows must allow planned switchovers and fault injection, including network and disk faults that may affect shared hosts. Named operators should be people who can act on a runbook during a test and who will remain responsible for the platform afterward. Application owners need to describe how each client connects, which retry logic it uses and what error they expect during a switch. Ask for this list in writing before the scope is signed.
Can our own team run PostgreSQL failover tests without a partner?
Yes, a capable internal team can run failover tests, provided it has the access, tooling knowledge and time. The team needs to understand the replication topology, the failover tool in use, the fencing behavior and the client connection path. It also needs a way to inject faults safely and to record timings from the client side, not only from the database. Many teams find the hardest parts are designing scenarios that expose real gaps, keeping evidence consistent across rounds and writing runbooks that someone unfamiliar with the design can follow at 2 a.m. An outside partner adds an independent view and a second pair of hands. Decide which parts you will own and which you will buy, and document the split before testing starts.
How often should we retest PostgreSQL failover?
Retest whenever something changes that could alter failover behavior, and on a regular schedule set by your risk owner. Triggers include a PostgreSQL major upgrade, a change to the failover tool or its configuration, a change to synchronous replication settings, a new client application, a change to the connection pooler or load balancer, and a change in the network or storage layer. PostgreSQL supports each major version for a fixed period, so plan at least one retest around any version change in the upgrade schedule. Ask the provider to state the regular cadence they recommend, what a retest covers, and whether a minor PostgreSQL update requires the full scenario set or a smaller regression set.
What should a failover testing scope include?
A written scope should name the topology, the failover mechanism, each fault scenario, the client applications in scope, the evidence each test produces and the runbooks that will be delivered. Scenarios typically include a planned switchover, an unplanned loss of the primary process, a host failure, a network partition between nodes and the distributed store, and a disk fault on the primary. For each scenario, the scope should state the success criteria, such as the expected client reconnection time and the expected data state afterward. Ask whether findings are fixed by the same team, whether retesting is included, and who signs off that the cluster meets the criteria.
How do we know a failover test passed?
A test passes when the cluster meets the success criteria written before the test, and the evidence supports that claim. Evidence usually includes timestamps for the fault injection, the promotion of a new primary, the moment each client reconnects and the state of committed transactions after the switch. Measuring reconnection from the client side matters, because a healthy database can still leave applications waiting on stale connections. Ask the provider to show the evidence format, the logs retained and how results are handed over to your audit or change record. Note that DeployOpen prepares evidence for compliance assessments but does not issue audit reports or certifications, so independent auditors still judge controls.
How DeployOpen scopes and delivers PostgreSQL failover testing
DeployOpen plans, runs and documents failover tests for PostgreSQL clusters inside your own infrastructure. The work starts with a written scope that names the failure cases, the cluster design under test and the runbooks to be produced, then moves through controlled test execution, evidence capture and handover to your operators.
How we scope
- We inventory the cluster design, including replication mode, failover tooling, connection routing and the hosts or sites involved.
- We agree in writing which failure cases are in scope, such as planned switchover, process kill, network partition and disk fault.
- Engagements are fixed-scope, with deliverables and timelines agreed before any test runs against your environment.
How we build
- We prepare a test plan with pass criteria for each case, including the data-loss and client-reconnection measurements you need.
- We run tests in a staging copy or an agreed maintenance window, recording timings, logs and cluster state at each step.
- We write switchover and failover runbooks with exact commands, decision points, rollback steps and the checks an operator confirms.
How we hand over
- You receive test results with evidence for each case, including what passed, what failed and the fixes applied.
- Runbooks are reviewed with your operators in a walkthrough so they can follow them under pressure without us present.
- We retest the cases affected by any fix so the final documentation matches the tested behavior of your cluster.
How we support
- Ongoing support, periodic failover drills and upgrade retesting are available as retainers.
- Retainers can cover re-running the test suite after PostgreSQL minor updates, configuration changes or topology changes.
- Ask any quote to state which runbooks, drills and retest rounds are included, and which remain your team's responsibility.

