TLA+ to bare-metal Jepsen: proving Active-Active HA on Kubernetes.
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
Section titled “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)
Section titled “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 + failedequals total admitted jobs at every reachable state (0jobs 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 viaFOR UPDATE, zero in-flightFOR KEY SHAREtransactions can remain attached to the dead session.MonotonicHeartbeat: broker heartbeats advance monotonically under database time.BoundedAttempts: lease expiry recovery never exceedsmaxAttemptsbefore 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
Section titled “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.
- Positive validation: TLC matched all
15 / 15real runtime steps (traceIdx = 1 → 16,1,148states explored,0safety violations) as a valid behavior permitted by the formal specification. - Negative control: we mutated a single recorded transition (
TraceDataMutated.tla) so a stale token (token = 2) illegally completed a reclaimed job (j2). TLC exhausted all1,599reachable states and rejected the trace, confirming the validator genuinely enforces token fencing rather than vacuously passing.
Layer 3: Deterministic Simulation Testing (DST)
Section titled “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
Section titled “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)
Section titled “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 timeouton their own broker heartbeats, flipping/readyto503. - Root cause:
lockPostgresBrokerSession()(src/infrastructure/persistence/postgres/brokerSessions.ts) locked the broker’s row inbunqueue_brokerswithSELECT ... FOR SHARE. In PostgreSQL MVCC,FOR SHAREconflicts withheartbeatPostgresBroker()’sUPDATE bunqueue_brokers SET heartbeat_at = $1(which acquiresFOR NO KEY UPDATE). Whenever overlapping claim/renewal transactions heldFOR SHAREcontinuously, the broker’s own heartbeat starved pastlock_timeout(5 s) and queued every subsequent transaction behind it in a lock convoy. - Fix: Changed
lockPostgresBrokerSession()toFOR KEY SHARE(which does not conflict with non-keyUPDATE heartbeat_at), and added an explicitSELECT ... FOR UPDATEinsideregisterPostgresBroker()’s transaction ahead of the stale-takeover upsert. BecauseunregisterPostgresBroker()andpurgeStalePostgresBrokers()executeDELETE(FOR UPDATE), every revocation path retains strict mutual exclusion withFOR KEY SHAREwhile steady-state heartbeats never block. - Proof:
test/repro-postgres-broker-heartbeat-lock-convoy.test.tsfailedREDwith55P03in421 msbefore the fix and passesGREENproving both non-blocking heartbeats and strict takeover/purge/unregister fencing.
Bug #2 — PostgresQueueManager.pushFlow() O(N²) full-queue read-model reload
Section titled “Bug #2 — PostgresQueueManager.pushFlow() O(N²) full-queue read-model reload”- What broke on K8s: During the Black Friday scenario (
2,000concurrent 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) calledthis.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 likepushBatch()already did. - Fix: Replaced full-queue reloads in
pushFlow()with per-queuethis.refreshJobs(ids, queue)(plus any externalparentIds). - Proof:
test/repro-postgres-pushflow-no-full-queue-reload.test.tsfailedRED(Expected: 0, Received: 2full-queue reloads) before the fix and passesGREENwith0full-queue reloads while keeping snapshot counts and parent/child relationships authoritative.
Bug #3 — Silent TCP packet-drop (iptables -j DROP) readiness blindness
Section titled “Bug #3 — Silent TCP packet-drop (iptables -j DROP) readiness blindness”- What broke on K8s: In scenario
S4, we installed realiptables -I FORWARD 1 ... -j DROPrules onk8s-w3to silently blackhole a broker pod from PostgreSQL 19.0 for 18 seconds without sending TCPFIN/RST. Although0jobs were lost,GET /readyreturned200 OKfor all 18 seconds and Kubernetes never evicted the partitioned pod fromService/bunqueueEndpoints. - Root cause:
Bun.SQL’sconnectionTimeout: 5applies only when establishing new TCP connections, and PostgreSQL’sstatement_timeoutis server-side (its error packet cannot cross a silent drop). Already-open pooled sockets executingPostgresEventStream.drain()andheartbeatBroker()hung silently on Linux TCP exponential retransmit backoff (tcp_retries2 = 15, up to ~15 minutes). Because neither promise had rejected yet,PostgresStorageHealthTracker.snapshot()reportedok: true. - Fix: Added lightweight in-flight stall tracking (
beginFlight/endFlight) toPostgresStorageHealthTracker(src/infrastructure/persistence/postgres/storageHealth.ts), wired intoPostgresEventStream.drainLoop()(events.ts, resetting the stall clock on each catch-up batch so legitimate multi-batch drains never false-trigger) andheartbeatBroker()(runtime.ts). If an activeevent-streamorheartbeatquery receives no PostgreSQL response forpostgresHealthStallMs(config)(5 sat defaults, floored at1 s, bounded byleaseDurationMsandstatementTimeoutMs),snapshot()immediately marks storage degraded (GET /readyreturns503) with zero background timers, zero extra database queries, and atomic zero-flicker handoff onrecord()/clear(). - Proof:
test/repro-postgres-partition-readiness.test.ts(using a real local TCP blackhole proxy that drops bytes without closing sockets) failedREDbefore the fix and passedGREEN(503in1.5 s, then automatic self-heal to200 OK). On the unchanged live ProxmoxS4iptables -j DROPrun, the partitioned pod flippedNotReadyin8.11 s, was evicted from Kubernetes Endpoints, and self-healed back toReadyin9.47 safteriptables -Dwithout restarting the container.
Layer 4: Bare-metal Proxmox 3-AZ Kubernetes + Jepsen campaign (10/10 PASS)
Section titled “Layer 4: Bare-metal Proxmox 3-AZ Kubernetes + Jepsen campaign (10/10 PASS)”Cluster topology
Section titled “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+k3s1control plane (taintedCriticalAddonsOnly).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 statelessbunqueuebroker pods (readOnlyRootFilesystem: true, UID1001,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, Bun1.4.5, and Go1.22.2runninggithub.com/anishathalye/porcupine v1.3.1.
Jepsen + Porcupine linearizability verification
Section titled “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:
tc netem(eth0 delay 80ms ± 30ms loss 10%) onk8s-w1iptables -j DROPsilent split-brain partition (14 s) between a broker pod onk8s-w2and PostgreSQL 19.0SIGKILL(kubectl delete pod --force --grace-period=0) on a live broker pod- Bare-metal AZ VM power-off (
qm stop 203on Proxmox host fork8s-w3 / az-c, thenqm start 203) - PostgreSQL 19.0 primary restart (
docker restart pg-prod)
The complete recorded operation history was checked offline by porcupine v1.3.1:
- Verdict:
LINEARIZABLEacross759concurrent operations (negativeControlMutatedRejected: true— injecting a single double-completion into the history caused Porcupine to reject it as non-linearizable). - Conservation & fencing:
150 / 150acknowledged pushes completed (0lost,0double-completed);151 / 151stale/forged ACKs fenced (0bypassed). - Deduplication under active nemeses:
600concurrent submissions across300keys produced300 / 300unique executions (0duplicate charges).
Complete 10-suite enterprise scorecard
Section titled “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 Engines 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
Section titled “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:
- Use
batchSize: 10on high-throughput PostgreSQL workers. On live PG 19.0 withsynchronous_commit=on,batchSize: 10delivered1,697 jobs/sversus1,306 jobs/satbatchSize: 32and699 jobs/satbatchSize: 50(2.4× faster than oversized batches): it amortizes WALfsync10× while minimizingFOR UPDATE SKIP LOCKEDrow-lock contention across concurrent pods. - Set
removeOnComplete: trueon high-volume queues. Retained completed rows consume broker read-model snapshot memory (~600 MiBper100,000live retained jobs if left unbounded). - Size snapshot and concurrency ceilings for bursty clusters. For
2 GiBbroker pods handling> 100kjob bursts, raiseBUNQUEUE_POSTGRES_POOL_SIZE=12,BUNQUEUE_POSTGRES_MAX_CONCURRENT_OPERATIONS=32,BUNQUEUE_POSTGRES_MAX_QUEUED_OPERATIONS=512,BUNQUEUE_POSTGRES_MAX_SNAPSHOT_JOBS=250000, andBUNQUEUE_MAX_COMPLETED_JOBS=5000(keepingreplicas × (POOL_SIZE + 1)comfortably below PostgreSQLmax_connections; embedded/programmaticPostgresQueueStoreusers can also tunemaxQueueEvents). - Never leave
livenessProbe.timeoutSecondsat1 s. SetlivenessProbe.timeoutSeconds: 5so GC or burst load does not falsely restart a healthy pod, while pairingreadinessProbe(periodSeconds: 2–5,failureThreshold: 2–3) with bunqueue’s built-in 5-second in-flight stall detector for fast split-brain eviction. - PostgreSQL 18+ / 19.0 Docker volume path. Official
postgres:18+andpostgres:19images mount persistent storage at/var/lib/postgresql(not/var/lib/postgresql/data).