# Verifying Active-Active HA on Kubernetes: TLA+, Trace Validation, DST, and Jepsen

How we verified bunqueue's stateless Active-Active Kubernetes + PostgreSQL 19.0 architecture across four formal-to-real layers—catching 3 real production bugs and passing 10/10 3-AZ chaos suites with 0 lost jobs.

Canonical: https://bunqueue.dev/blog/kubernetes-active-active-ha-verification/

---

Before recommending bunqueue's stateless multi-broker mode for mission-critical Kubernetes clusters, we verified the protocol across four independent layers—exhaustive TLA+ model checking, live PostgreSQL trace validation, 10,000-seed Deterministic Simulation Testing, and a 3-AZ bare-metal Proxmox Jepsen campaign checked by Porcupine.

"High availability" is easy to put on a landing page and hard to hold under real failure. Most queue defects only surface when three bad things happen in the same second: a pod is blackholed by a top-of-rack firewall without sending TCP `RST`, a worker finishes a job whose lease already expired on another broker, and a rolling update drains an Availability Zone while PostgreSQL restarts.

TypeScript does not have a mature line-by-line formal verifier. The high-leverage path used by distributed storage engines is to **formally verify the protocol first, prove that the running implementation conforms to the spec, torture the state machine deterministically across thousands of seeded fault schedules, and then inject real kernel, hypervisor, and database failures on a multi-AZ Kubernetes cluster**.

That four-layer campaign caught **three real production bugs** that standard unit and integration tests missed—a PostgreSQL MVCC heartbeat lock convoy, an `O(N²)` full-queue reload on `FlowProducer.add()`, and a silent TCP packet-drop readiness blind spot. Every one of them was reproduced deterministically (`RED`), fixed, proved (`GREEN`), and re-verified live on our 3-AZ Proxmox cluster until **all four layers and all 10 live Kubernetes suites passed with `0` lost jobs and `0` double completions**.

## The four-layer verification pyramid

| Layer | Tooling & target | Scale verified | Result |
| --- | --- | --- | --- |
| **1. Formal Protocol Verification** | TLA+ / TLC 2.19 (`BunqueueHAFailover.tla`) | **`193,690,957`** safety states (`20,238,308` distinct, 7 invariants) + **`4,844,798`** liveness states (`705,108` distinct) | **`0` errors** |
| **2. Trace Validation** | TLC against real `PostgresQueueStore` JSON traces on PostgreSQL 19.0 | **`15 / 15`** live transitions (`drain-handoff`, `heartbeat-keyshare`, `crash-reclaim-fence`) + mutated negative control | **Accepted · mutant rejected** |
| **3. Deterministic Simulation Testing (DST)** | Virtualized cluster (`test/dst-ha-failover.test.ts` + `fast-check`) | **`10,000`** seeded runs · **`1,586,311`** simulated ops in **`595 ms`** (500-seed CI gate in `< 120 ms`) | **`0` violations · bit-exact replay** |
| **4. Real Jepsen + 3-AZ K8s Campaign** | Proxmox 3-AZ `k3s v1.37.3` + `PostgreSQL 19.0` + Go **`porcupine v1.3.1`** | **`759`** concurrent Jepsen ops (`5` live nemeses) + **`345,990`** unique jobs + **`200`** multi-pod workflows across **`10`** suites | **`LINEARIZABLE` · `10 / 10 PASS` · `0` lost** |

---

## Layer 1: Exhaustive TLA+ model checking (193.69M states, 0 errors)

We modeled bunqueue's active-active PostgreSQL HA protocol in `BunqueueHAFailover.tla` covering broker registration and session UUID fencing, `FOR KEY SHARE` / `FOR NO KEY UPDATE` / `FOR UPDATE` row-lock concurrency on `bunqueue_brokers`, `FOR UPDATE SKIP LOCKED` job claims, cross-broker lease renewals and handoffs, graceful `SIGTERM` drains (`beginDrain()` + `releasePostgresBrokerLeases()` preserving actively renewed leases), stale-broker purging, expired-lease recovery, and crash/restart interleavings.

We checked seven safety invariants exhaustively with TLC 2.19 (depth `24`, `02m08s`):

- **`TypeOK`**: all broker, session, token, and job state domains remain well-typed across every interleaving.
- **`NoDoubleCompletion`**: no job can commit a terminal completion more than once, even when delayed stale-token ACKs race with lease reclamation and redelivery on a surviving broker.
- **`ExactConservation`**: `waiting + active + completed + failed` equals total admitted jobs at every reachable state (`0` jobs created or vanished).
- **`UniqueActiveTokens`**: no two active leases ever hold the same fencing token.
- **`NoKeyShareOnDeadBroker`**: once a broker session is unregistered, purged, or taken over via `FOR UPDATE`, zero in-flight `FOR KEY SHARE` transactions can remain attached to the dead session.
- **`MonotonicHeartbeat`**: broker heartbeats advance monotonically under database time.
- **`BoundedAttempts`**: lease expiry recovery never exceeds `maxAttempts` before settling to DLQ.

| TLC Check | States generated | Distinct states | Max depth | Errors |
| --- | ---: | ---: | ---: | ---: |
| **Safety (7 invariants)** | `193,690,957` | `20,238,308` | `24` | **`0`** |
| **Liveness (`EventualSettlement`)** | `4,844,798` | `705,108` | `19` | **`0`** |

The temporal liveness check (`EventualSettlement`) proved under weak fairness of recovery and broker restarts that **every admitted job eventually terminates as `completed` or settles in DLQ**—no deadlock, livelock, or permanently orphaned active lease exists in the protocol.

---

## Layer 2: TLA+ trace validation against live PostgreSQL 19.0

A formal specification disconnected from running code can drift silently. To bridge the TLA+ model to the actual TypeScript + SQL implementation, we instrumented a live trace capture against real `PostgresQueueStore` running on PostgreSQL 19.0 covering three core HA sequences (`drain-handoff`, `heartbeat-keyshare`, and `crash-reclaim-fence`) and fed the recorded JSON trace directly into `BunqueueHAFailoverTrace.tla`.

1. **Positive validation**: TLC matched all **`15 / 15`** real runtime steps (`traceIdx = 1 → 16`, `1,148` states explored, `0` safety violations) as a valid behavior permitted by the formal specification.
2. **Negative control**: we mutated a single recorded transition (`TraceDataMutated.tla`) so a stale token (`token = 2`) illegally completed a reclaimed job (`j2`). TLC exhausted all `1,599` reachable states and **rejected the trace**, confirming the validator genuinely enforces token fencing rather than vacuously passing.

---

## Layer 3: Deterministic Simulation Testing (DST)

Following the FoundationDB and TigerBeetle approach, we built a seeded deterministic simulator in `test/support/dst-ha-sim.ts` driven by `fast-check` in `test/dst-ha-failover.test.ts` (part of the permanent test suite). Time, broker clock skew (`-4s` to `+4s`), PostgreSQL restarts, network partitions, delayed/reordered/duplicate ACK packets, crash-after-commit sockets, `FOR KEY SHARE` / `FOR UPDATE` row locks, graceful drains, `SIGKILL` crashes, FIFO groups, and live deduplication all execute deterministically from a single seed.

A **10,000-seed marathon** (`DST_SEED=20261204`, completed in **`595 ms`**) exercised:

| Metric | 10,000-seed DST total |
| --- | ---: |
| **Simulated cluster operations** | **`1,586,311`** |
| **Unique jobs admitted** | `50,836` (`48,028` completed + `2,808` DLQ · **`0` lost**, **`0` double-completed**) |
| **Duplicate submissions rejected by dedup** | `37,055` |
| **Stale / duplicate ACKs fenced** | `32,366` |
| **Cross-broker drain handoffs** | `3,516` |
| **Expired leases reclaimed** | `29,673` |
| **Heartbeats completed under active `FOR KEY SHARE`** | `5,102` |
| **Crash-after-commit socket recoveries** | `3,817` |
| **Injected faults (`SIGKILL` / partitions / PG restarts)** | `39,214` / `21,973` / `20,543` |
| **Bit-for-bit identical seed replay** | **Verified (`seed = 424242`)** |

Every CI run executes the 500-seed schedule (`> 50,000` operations, `< 120 ms`) plus the bit-exact replay check.

---

## Three real production bugs caught live on Proxmox Kubernetes

Formal models verify the protocol; running high-concurrency workloads and kernel fault injection on a real 3-AZ cluster exposes implementation details where PostgreSQL MVCC, read-model caches, and Linux TCP timers interact in unexpected ways. Our campaign caught **three real production defects**, all fixed with reproduce-first `RED → GREEN` regression tests:

### Bug #1 — PostgreSQL `bunqueue_brokers` MVCC heartbeat lock convoy (`55P03`)

- **What broke on K8s**: Under sustained worker claim and renewal traffic, healthy broker pods intermittently threw `55P03: canceling statement due to lock timeout` on their own broker heartbeats, flipping `/ready` to `503`.
- **Root cause**: `lockPostgresBrokerSession()` (`src/infrastructure/persistence/postgres/brokerSessions.ts`) locked the broker's row in `bunqueue_brokers` with `SELECT ... FOR SHARE`. In PostgreSQL MVCC, `FOR SHARE` **conflicts** with `heartbeatPostgresBroker()`'s `UPDATE bunqueue_brokers SET heartbeat_at = $1` (which acquires `FOR NO KEY UPDATE`). Whenever overlapping claim/renewal transactions held `FOR SHARE` continuously, the broker's own heartbeat starved past `lock_timeout` (`5 s`) and queued every subsequent transaction behind it in a lock convoy.
- **Fix**: Changed `lockPostgresBrokerSession()` to `FOR KEY SHARE` (which does **not** conflict with non-key `UPDATE heartbeat_at`), and added an explicit `SELECT ... FOR UPDATE` inside `registerPostgresBroker()`'s transaction ahead of the stale-takeover upsert. Because `unregisterPostgresBroker()` and `purgeStalePostgresBrokers()` execute `DELETE` (`FOR UPDATE`), every revocation path retains strict mutual exclusion with `FOR KEY SHARE` while steady-state heartbeats never block.
- **Proof**: `test/repro-postgres-broker-heartbeat-lock-convoy.test.ts` failed `RED` with `55P03` in `421 ms` before the fix and passes `GREEN` proving both non-blocking heartbeats and strict takeover/purge/unregister fencing.

### Bug #2 — `PostgresQueueManager.pushFlow()` O(N²) full-queue read-model reload

- **What broke on K8s**: During the Black Friday scenario (`2,000` concurrent multi-child sagas alongside a deep backlog), `FlowProducer.add()` latency degraded quadratically as queue depth grew.
- **Root cause**: `PostgresQueueManagerDelivery.pushFlow()` (`src/application/postgres-queue-manager/delivery.ts`) called `this.refreshQueueAfterCommit(queue)` on every touched queue after each flow insert—reloading and decoding **every** job row in those queues instead of refreshing only the newly inserted flow nodes like `pushBatch()` already did.
- **Fix**: Replaced full-queue reloads in `pushFlow()` with per-queue `this.refreshJobs(ids, queue)` (plus any external `parentId`s).
- **Proof**: `test/repro-postgres-pushflow-no-full-queue-reload.test.ts` failed `RED` (`Expected: 0, Received: 2` full-queue reloads) before the fix and passes `GREEN` with `0` full-queue reloads while keeping snapshot counts and parent/child relationships authoritative.

### Bug #3 — Silent TCP packet-drop (`iptables -j DROP`) readiness blindness

- **What broke on K8s**: In scenario `S4`, we installed real `iptables -I FORWARD 1 ... -j DROP` rules on `k8s-w3` to silently blackhole a broker pod from PostgreSQL 19.0 for 18 seconds without sending TCP `FIN`/`RST`. Although `0` jobs were lost, **`GET /ready` returned `200 OK` for all 18 seconds** and Kubernetes never evicted the partitioned pod from `Service/bunqueue` Endpoints.
- **Root cause**: `Bun.SQL`'s `connectionTimeout: 5` applies only when establishing **new** TCP connections, and PostgreSQL's `statement_timeout` is server-side (its error packet cannot cross a silent drop). Already-open pooled sockets executing `PostgresEventStream.drain()` and `heartbeatBroker()` hung silently on Linux TCP exponential retransmit backoff (`tcp_retries2 = 15`, up to ~15 minutes). Because neither promise had rejected yet, `PostgresStorageHealthTracker.snapshot()` reported `ok: true`.
- **Fix**: Added lightweight in-flight stall tracking (`beginFlight` / `endFlight`) to `PostgresStorageHealthTracker` (`src/infrastructure/persistence/postgres/storageHealth.ts`), wired into `PostgresEventStream.drainLoop()` (`events.ts`, resetting the stall clock on each catch-up batch so legitimate multi-batch drains never false-trigger) and `heartbeatBroker()` (`runtime.ts`). If an active `event-stream` or `heartbeat` query receives no PostgreSQL response for `postgresHealthStallMs(config)` (`5 s` at defaults, floored at `1 s`, bounded by `leaseDurationMs` and `statementTimeoutMs`), `snapshot()` immediately marks storage degraded (`GET /ready` returns `503`) with zero background timers, zero extra database queries, and atomic zero-flicker handoff on `record()` / `clear()`.
- **Proof**: `test/repro-postgres-partition-readiness.test.ts` (using a real local TCP blackhole proxy that drops bytes without closing sockets) failed `RED` before the fix and passed `GREEN` (`503` in `1.5 s`, then automatic self-heal to `200 OK`). On the unchanged live Proxmox `S4` `iptables -j DROP` run, the partitioned pod flipped **`NotReady` in `8.11 s`**, was **evicted from Kubernetes Endpoints**, and **self-healed back to `Ready` in `9.47 s`** after `iptables -D` without restarting the container.

---

## Layer 4: Bare-metal Proxmox 3-AZ Kubernetes + Jepsen campaign (10/10 PASS)

### Cluster topology

All live experiments ran on five freshly provisioned Proxmox VMs (`local-zfs`, isolated `vmbr1` `10.30.0.60–64/24`):

- **`k8s-cp`** (`10.30.0.60`, 4 vCPU / 6 GiB): `k3s v1.37.3+k3s1` control plane (tainted `CriticalAddonsOnly`).
- **`k8s-w1` (`az-a`)**, **`k8s-w2` (`az-b`)**, **`k8s-w3` (`az-c`)** (`10.30.0.61–63`, 6 vCPU / 12 GiB each): three Availability Zone worker nodes running 4 stateless `bunqueue` broker pods (`readOnlyRootFilesystem: true`, UID `1001`, `PodDisruptionBudget minAvailable: 2`, `RollingUpdate maxUnavailable: 0`).
- **`k8s-infra`** (`10.30.0.64`, 6 vCPU / 12 GiB): **PostgreSQL 19.0** (`postgres:19-alpine`, `synchronous_commit=on`, `shared_buffers=2GB`, `max_connections=300`), local OCI registry, Bun `1.4.5`, and Go `1.22.2` running **`github.com/anishathalye/porcupine v1.3.1`**.

### Jepsen + Porcupine linearizability verification

In `JEPSEN_3AZ_K8s_Porcupine_Linearizability` (`122.77 s`), concurrent producers, workers, and adversarial stale-ACK injectors ran against the 4-pod cluster while we injected **five real nemeses** live:

1. **`tc netem`** (`eth0 delay 80ms ± 30ms loss 10%`) on `k8s-w1`
2. **`iptables -j DROP`** silent split-brain partition (`14 s`) between a broker pod on `k8s-w2` and PostgreSQL 19.0
3. **`SIGKILL`** (`kubectl delete pod --force --grace-period=0`) on a live broker pod
4. **Bare-metal AZ VM power-off** (`qm stop 203` on Proxmox host for `k8s-w3 / az-c`, then `qm start 203`)
5. **PostgreSQL 19.0 primary restart** (`docker restart pg-prod`)

The complete recorded operation history was checked offline by **`porcupine v1.3.1`**:

- **Verdict**: **`LINEARIZABLE`** across **`759`** concurrent operations (`negativeControlMutatedRejected: true` — injecting a single double-completion into the history caused Porcupine to reject it as non-linearizable).
- **Conservation & fencing**: **`150 / 150`** acknowledged pushes completed (`0` lost, `0` double-completed); **`151 / 151`** stale/forged ACKs fenced (`0` bypassed).
- **Deduplication under active nemeses**: `600` concurrent submissions across `300` keys produced **`300 / 300`** unique executions (`0` duplicate charges).

### Complete 10-suite enterprise scorecard

Across all 10 live Proxmox 3-AZ suites, bunqueue settled **`345,990` unique completed jobs** (+ `90` intentional permanent DLQ jobs) and **`200` multi-pod Workflow executions** with **`0` lost jobs** and **`10 / 10 PASS`**:

| Suite | Real-world scenario & injected faults | Workload settled | Key verified metrics | Status |
| --- | --- | ---: | --- | --- |
| **Jepsen** | `tc netem` + `iptables DROP` + `SIGKILL` + `qm stop 203` + `docker restart pg-prod` | `450` jobs (`759` linearizability ops) | **`LINEARIZABLE`** (`porcupine v1.3.1`, mutant rejected) · `151/151` stale ACKs fenced · `0` lost · `0` dupes | **PASS** |
| **S1** | Black Friday flash sale: VIP preemption + 200-customer FIFO + 30k webhook dedup + 2,000 multi-child sagas | `90,910` completed + `90` DLQ (`106,000` submitted) | `10,000/10,000` FIFO (`0` out-of-order) · `15,000/15,000` dedup (`0` dupes) · `2,000/2,000` sagas (`0` mismatch) · `0` pod restarts | **PASS** |
| **S2** | Multi-tenant noisy neighbor (`100k` rate-limited flood) + 49 FIFO tenants + live `kubectl scale 4 → 6 → 4` | `77,800` completed | `9,800/9,800` FIFO (`0` violations) · scale `4→6` in **`2.25 s`** (`78` PG conns) · `6→4` in **`0.09 s`** (`52` PG conns) · `0` restarts | **PASS** |
| **S3** | Zero-downtime `RollingUpdate` (`maxUnavailable: 0`) + real K8s `PDB` `429` Eviction API + `3× SIGKILL` | `40,000` completed | Rollout **`10.29 s`** (`minReady: 4`) · K8s `PDB` **`429 TooManyRequests`** enforced · `0` lost | **PASS** |
| **S4** | Real Linux kernel `iptables -I FORWARD 1 ... -j DROP` silent split-brain (`18 s` on `k8s-w3`) | `15,000` completed | Pod flipped **`NotReady` in `8.11 s`** · **`evictedFromEndpoints: true`** · auto-healed **`Ready` in `9.47 s`** · `0` lost | **PASS** |
| **S5** | Hard Proxmox bare-metal AZ outage (`qm stop 203` for `35 s` killing 2 broker pods on `k8s-w3`, then `qm start 203`) | `40,000` completed | Surviving pods on `az-a`/`az-b` reclaimed leases automatically · `0` lost · `4/4 Ready` restored | **PASS** |
| **S6** | Hard PostgreSQL 19.0 primary restart (`docker restart pg-prod`) + `65`-sample Linux `VmRSS` leak soak (`379 s`) | `80,000` completed | `/ready` flipped `503` and recovered **`4/4 Ready` in `11.6 s`** · steady `VmRSS` `161 → 199 MiB` avg · `0` lost | **PASS** |
| **S7** | Complete K8s feature matrix (`7/7` subsystems across all 4 pods) | `330` jobs | Delayed/promote · cross-pod progress/logs · single-fire cron (`0` double-fires) · global concurrency (`peak 4 === limit 4`) · pause/resume · DLQ retry · cross-node `QueueEvents` | **PASS** |
| **S8** | Multi-pod Workflow Engine (`3` independent `Engine`s sharing PG 19.0) | `200` workflows | `300 → 100` concurrent idempotent starts · `60/60` `parallel(3)+branch+sleep+cross-pod signal` · `40/40` reverse-order compensating rollbacks | **PASS** |
| **S9** | Security & ops: HTTP/TCP auth rejection, `/prometheus`, zero-downtime `AUTH_TOKENS` rotation (`old → new,old → new`) | `1,500` jobs | `401 → 200` auth · bad TCP rejected · `1,500/1,500` during rotation (`0` lost) · old token `401` post-revocation | **PASS** |

---

## Empirically measured Kubernetes + PostgreSQL 19.0 tuning rules

Running 346,000+ jobs under `synchronous_commit=on` ZFS storage produced five concrete production sizing rules that we have also added to the [Kubernetes Deployment Guide](https://bunqueue.dev/guide/kubernetes/):

1. **Use `batchSize: 10` on high-throughput PostgreSQL workers.** On live PG 19.0 with `synchronous_commit=on`, `batchSize: 10` delivered **`1,697 jobs/s`** versus `1,306 jobs/s` at `batchSize: 32` and `699 jobs/s` at `batchSize: 50` (2.4× faster than oversized batches): it amortizes WAL `fsync` 10× while minimizing `FOR UPDATE SKIP LOCKED` row-lock contention across concurrent pods.
2. **Set `removeOnComplete: true` on high-volume queues.** Retained completed rows consume broker read-model snapshot memory (`~600 MiB` per `100,000` live retained jobs if left unbounded).
3. **Size snapshot and concurrency ceilings for bursty clusters.** For `2 GiB` broker pods handling `> 100k` job bursts, raise `BUNQUEUE_POSTGRES_POOL_SIZE=12`, `BUNQUEUE_POSTGRES_MAX_CONCURRENT_OPERATIONS=32`, `BUNQUEUE_POSTGRES_MAX_QUEUED_OPERATIONS=512`, `BUNQUEUE_POSTGRES_MAX_SNAPSHOT_JOBS=250000`, and `BUNQUEUE_MAX_COMPLETED_JOBS=5000` (keeping `replicas × (POOL_SIZE + 1)` comfortably below PostgreSQL `max_connections`; embedded/programmatic `PostgresQueueStore` users can also tune `maxQueueEvents`).
4. **Never leave `livenessProbe.timeoutSeconds` at `1 s`.** Set `livenessProbe.timeoutSeconds: 5` so GC or burst load does not falsely restart a healthy pod, while pairing `readinessProbe` (`periodSeconds: 2–5`, `failureThreshold: 2–3`) with bunqueue's built-in 5-second in-flight stall detector for fast split-brain eviction.
5. **PostgreSQL 18+ / 19.0 Docker volume path.** Official `postgres:18+` and `postgres:19` images mount persistent storage at `/var/lib/postgresql` (not `/var/lib/postgresql/data`).

> **Tip: Try the failover mechanics yourself**
>
> Deploy the copy-ready manifests from the [Kubernetes Guide](https://bunqueue.dev/guide/kubernetes/), experiment interactively with drains, `SIGKILL`, and split-brain fencing in the [Kubernetes Cluster Simulator](https://bunqueue.dev/k8s-simulator/), or run the deterministic simulation suite locally with `BUNQUEUE_EMBEDDED=1 bun test test/dst-ha-failover.test.ts`.
