Cloud

Azure PostgreSQL: validate HA readiness before a planned failover

A production runbook for validating HA health, application reconnection, pools and logical replication before an Azure Database for PostgreSQL planned failover.

17 Oct 2026 azurepostgresqlflexible-serverhigh-availabilityfailoverpgbouncerobservabilityautomationrunbookvalidationrollbackproduction

An Azure Database for PostgreSQL Flexible Server is configured for high availability. Maintenance, a resilience exercise or a return to the preferred zone requires a planned failover. The action is available and a standby exists, but neither fact proves that applications will renew their connections or that secondary data flows will survive the primary change.

The running case is an order API with a connection pool, asynchronous workers and a small set of logical replication slots. The goal is not to promise an invisible failover. It is to prove service readiness, bound the expected interruption and end with an explicit decision: fail over, postpone or return to the last qualified placement.

Separate HA from a read replica

Start by separating two mechanisms. The HA standby receives commits synchronously and supports failover for the same server. A read replica is a distinct asynchronous target used for reads or recovery. Replica lag and promotion require a different runbook.

Freeze the contract before changing the server.

yaml 01-postgresql-failover-contract.yml
change_id: CHG-DB-417
window_utc: 2026-10-17T20:00:00Z/2026-10-17T20:30:00Z
server: pg-orders-prod-we
resource_group: rg-data-prod
ha_mode: ZoneRedundant
expected_endpoint: pg-orders-prod-we.postgres.database.azure.com
clients:
- orders-api
- billing-worker
- reporting-exporter
connection_layers:
application_pool: true
managed_pgbouncer: false
logical_replication:
enabled: true
slots: [orders_cdc]
success:
- same_fqdn_accepts_new_connections
- write_canary_commits_once
- workers_resume_without_duplicate_effect
- error_rate_returns_to_baseline
rollback_owner: database-on-call

The server FQDN remains the connection contract. An IP resolved before failover and then stored in configuration or directly allowed by a network component turns an HA mechanism into a brittle dependency.

Prove HA health before the window

An HA configuration is not evidence of current readiness. Inspect server state, HA mode and observed availability early enough to postpone without consuming the change window.

bash 02-ha-state-and-metrics.sh
set -eu

RG="rg-data-prod"
SERVER="pg-orders-prod-we"
RESOURCE_ID=$(az postgres flexible-server show --resource-group "$RG" --name "$SERVER" --query id -o tsv)

az postgres flexible-server show --resource-group "$RG" --name "$SERVER" --query '{state:state,version:version,ha:highAvailability,zone:availabilityZone}' --output json

az monitor metrics list --resource "$RESOURCE_ID" --metric is_db_alive active_connections connections_failed --interval PT1M --aggregation Average Total --output json

Read these signals together. A reachable server whose HA state is initializing or replicating is not ready for a voluntary exercise. Existing failed connections or saturation would also make it impossible to separate failover impact from pre-existing noise.

Add a Resource Health alert for HA state changes. Metrics and logs must exist before the incident: telemetry enabled during an outage cannot reconstruct the missing history.

Inspect dependencies that do not move automatically

The stable server name hides the node change, not client assumptions. Inspect pools, runtime DNS, timeouts, retries and consumer idempotency.

text 03-client-readiness.txt
Connection
Every client uses the server FQDN
No configuration file contains a PostgreSQL IP
connect_timeout and command timeout are bounded
The pool discards broken connections and opens new ones
Retries have backoff, jitter and a limit

Business effects
An interrupted request can be replayed without a duplicate write
Workers have an idempotency key or deduplication
Long transactions are identified before the window
Migrations and batch jobs are paused during the exercise

Observability
SQLSTATE errors and timeouts are retained
Connection opens are separated from business queries
Useful throughput, latency and duplicates are measured
The stop owner is reachable

When managed or external PgBouncer is present, observe client connections, server connections, waiting clients and authentication errors separately. A pool can accept clients while retaining dead backend connections. Success therefore requires a new transaction, not only an open socket.

Check logical replication failover readiness

Slots visible on the primary do not by themselves prove readiness on the HA standby. When logical replication must survive failover, validate the required parameters and the Azure Monitor slot synchronization signal.

sql 04-logical-replication-inventory.sql
SELECT slot_name,
     plugin,
     slot_type,
     active,
     restart_lsn,
     confirmed_flush_lsn
FROM pg_replication_slots
ORDER BY slot_name;

SELECT name, setting
FROM pg_settings
WHERE name IN ('sync_replication_slots', 'hot_standby_feedback');

Complete the primary-side inventory with logical_replication_slot_sync_status when the feature is in use. A non-ready value means postponing the exercise or explicitly accepting a manual consumer recovery. Do not discover after failover that a CDC connector retained a position the new primary cannot serve.

Canary reconnection through the real path

Before the window, run a probe from the same network and with the same TLS chain as the application. It should verify DNS, a new connection, a read, an idempotent write and a confirmation read.

sql 05-failover-canary.sql
CREATE TABLE IF NOT EXISTS ops_failover_canary (
change_id text PRIMARY KEY,
observed_at timestamptz NOT NULL DEFAULT now(),
observer text NOT NULL
);

INSERT INTO ops_failover_canary(change_id, observer)
VALUES ('CHG-DB-417', 'orders-api-canary')
ON CONFLICT (change_id)
DO UPDATE SET observed_at = now(), observer = EXCLUDED.observer;

SELECT change_id, observed_at, observer
FROM ops_failover_canary
WHERE change_id = 'CHG-DB-417';

Timestamp every attempt during failover. Retain the DNS answer seen by the runtime, connection duration, transaction status and retry count. Stop the canary if it sees a non-idempotent write, an unexpected endpoint or unbounded accumulation.

Execute without confusing failover and restart

Use planned mode only after the readiness gate. The command mutates production and should be attached to the change record and executed by the intended identity.

bash 06-planned-failover.sh
set -eu

RG="rg-data-prod"
SERVER="pg-orders-prod-we"

az postgres flexible-server restart --resource-group "$RG" --name "$SERVER" --failover Planned

az postgres flexible-server wait --resource-group "$RG" --name "$SERVER" --custom "state=='Ready'" --interval 15 --timeout 900

ARM returning to Ready is only a platform signal. Wait for the application canary, worker recovery and error rates to return to their normal envelope. Do not rerun the command because an application has not renewed its pool yet.

Decide go, postpone or controlled return

text 07-failover-gate.txt
FAIL OVER
HA state is healthy and stable before the window
Pre-failover canary is green through the application path
Pools and retries are bounded, processing is idempotent
Logical slots are synchronized or explicitly out of scope
Observability and stop owner are available

POSTPONE
Standby is initializing, replicating or degraded
Baseline already contains connection failures
A fixed IP exists in a client or rule
A logical slot is not ready and has no recovery procedure
A long batch or migration is still running

CONTROLLED RETURN
New primary is healthy but client errors persist
Client cause is isolated and previous placement remains qualified
Second planned failover is approved after stabilization
The same canary and thresholds validate the return

ESCALATE
HA state is stuck or Resource Health is degraded
Writes are ambiguous, duplicated or inconsistent
Endpoint resolves but no new transaction can commit
Evidence is insufficient to attribute the failure

A reverse failover is not an Undo operation. It is another failover with its own risk. If the new primary is healthy and only clients fail, repair connection renewal first. Do not multiply failovers to hide a pool that retains dead sockets.

Validate and close

Final validation joins platform and application evidence: stable HA state, fresh connections through the FQDN, one canary write, workers without duplicate effects, errors and latency back within baseline, and resumed logical replication when used.

Retain the actual timeline: outage start, first useful DNS answer, first connection, first commit and SLO recovery. Those measurements should drive the next maintenance window and client timeouts. They are more useful than a generic duration quoted outside your workload context.

Conclusion

PostgreSQL high availability does not end with the presence of a standby. It includes the clients’ ability to discard dead connections, resolve the same FQDN, retry without duplicate effects and restore secondary flows.

The runbook ends with an observable decision: fail over when both standby and clients are ready, postpone while any dependency remains ambiguous, or schedule a second failover only after proving that the new placement is the cause. The real validation is not Azure reporting Ready; it is a successful business transaction through the production path.