Engineering Labs

PostgreSQL failover on Kubernetes, measured

Three PostgreSQL instances under CloudNativePG, a client that writes twice a second, and a deleted primary: how long writes fail, what the client has to do, and whether any committed row is lost.

The question#

“Highly available” needs numbers. When the primary goes, how long are writes refused, does the client need to change anything, and does every write it was told had committed survive?

The setup#

                      writer pod
                          |
                    Service pg-rw  ---- always points at the primary
                          |
        +-----------------+------------------+
     pg-1 (primary) --WAL--> pg-2 (replica)  pg-3 (replica)
                          |
               CloudNativePG operator

A writer inserts a row through the pg-rw service twice a second and logs which pod accepted it. The demo deletes the primary pod and records every status change, with seconds since the kill, until the cluster is healthy again.

What it shows#

  • Writes fail for roughly 15 to 30 seconds while the operator detects the loss, promotes the replica with the most WAL and repoints pg-rw.
  • The client needs no change and no restart, because it connects to a service, never to a pod.
  • The old primary rejoins as a replica on its own volume, rewinding anything the new primary never saw.
  • No committed row is lost in this test, and the demo checks every one. Deleting a pod lets PostgreSQL shut down cleanly, so this is the favourable case.

Reproduce it#

git clone https://github.com/caelus-engineering-labs/postgresql-ha-in-k8s.git
cd postgresql-ha-in-k8s
./demo.sh            # Docker Desktop, minikube, OrbStack or kind; ./demo.sh down to clean up

Where it stops#

Replication is asynchronous, so a primary that crashes rather than shuts down can take its last commits with it. Requiring one replica to confirm every commit (synchronous: method: any) closes that gap at the cost of write latency; the trade-off, and a crash test rather than a pod deletion, are the next experiment.

Repository