Skip to content
Get started
Get started
bunqueue v2.9.25
View Markdown
blog · release

bunqueue v2.9.25

Kubernetes and PostgreSQL 19 production hardening proven under live 4-broker chaos (143,820/143,820 jobs, 0 lost, 0 duplicates, Schema v22), high-concurrency TCP worker ACK safety, bunqueue-client 0.2.4 (+23.2% Node.js worker throughput, BrokerAdmin, mTLS, Node.js 20), 9 TLA+ / TLC formal models across 356,615 states, and a redesigned documentation site.

Unit tests prove that code works when everything goes right. Production Kubernetes clusters do not go right: pods hit 512 MiB memory limits, brokers take SIGTERM while hundreds of leases are active, PostgreSQL restarts underneath live traffic, a single worker drives concurrency: 200 straight into a protocol rate limit, and completed job tables grow well past 50,000 rows.

In bunqueue v2.9.25, we put a 4-broker Kubernetes cluster on Proxmox VE 9.2, k3s v1.37.2, and PostgreSQL 19.0 through sustained chaos testing, fixed every production defect it uncovered across 80 runtime source files (+2,255 / -780 lines), hardened the standalone TypeScript SDK bunqueue-client 0.2.4 across 68 files (+5,401 / -1,221 lines) with a +23.2% worker throughput gain, formally verified 9 concurrent state machines with TLA+ / TLC (356,615 states, 0 errors), focused official SDK support on 4 official SDKs (TypeScript, Python, Go, Rust), and shipped a complete documentation simplification with a unified 2D diagram system.

Every observable behavior change and automatic migration note is documented in Before you upgrade.

curl -fsSL https://bunqueue.dev/install.sh | sh -s -- --version 2.9.25
& ([scriptblock]::Create((irm https://bunqueue.dev/install.ps1))) -Version 2.9.25
bun add bunqueue@2.9.25
npm install bunqueue@2.9.25
TAG=2.9.25
docker run -p 6789:6789 -p 6790:6790 ghcr.io/egeominotti/bunqueue:$TAG
bun add bunqueue@latest

Hardened on live Kubernetes and PostgreSQL 19: 143,820/143,820 chaos jobs, 0 lost

Section titled “Hardened on live Kubernetes and PostgreSQL 19: 143,820/143,820 chaos jobs, 0 lost”

We ran a live 4-broker Kubernetes cluster (512 MiB pod memory limit) backed by PostgreSQL 19.0 on Proxmox VE 9.2 + k3s v1.37.2 through rolling restarts, SIGKILL crashes, hard VM power-offs (qm stop 203), large-payload waves (800 x 128 KiB), long-running leases (20 x 42 s), and back-to-back postgres-0 restarts. The live cluster exposed real production failure modes that synthetic single-process tests miss, and v2.9.25 resolves every single one.

Before and after Kubernetes multi-broker and PostgreSQL 19 hardening scorecard in bunqueue v2.9.25 Live Kubernetes + PostgreSQL 19 Chaos Scorecard (4 Brokers, 512 MiB Limit) Proxmox VE 9.2 · k3s v1.37.2 · PostgreSQL 19.0 · 480 s Chaos (143,820 / 143,820 Jobs) PULLB Heap Fetches (Schema v22) 303k down from 326M bunqueue_jobs_fifo_ready_idx PG /ready Recovery After Restart 5-6 s down from 18-60 s 4/4 Ready kept across 2 restarts Graceful Broker Drain (SIGTERM) 4 s down from 30 s hang Rolling Recreate in 8 s · 0 dup PG Completed Counts (60,000 Burst) 60,000 was 50,000 cap Authoritative PG durable counts Broker Pod RAM Under Chaos 171-183 MiB / 512 MiB 16 MiB cap · clientJobs = 0 SQLite 60,000 TCP Burst (conc=200) 11.32 s 0 dup · 0 lost Was ~50 s stall + 60 duplicates 480 s Continuous Production Chaos Result (Test C) 143,820 / 143,820 settled · 0 lost · 0 duplicates · 0 delay violations · 0 lost ACKs Exact queue counts (100,675 / 41,707 / 1,438) · Cold v21 -> v22 upgrade on 171,955 rows / 242 MB in 7 s (91-95 MiB)
Measured directly on Proxmox VE 9.2 + k3s v1.37.2 + PostgreSQL 19.0 with 4 broker pods capped at 512 MiB RAM.

Here is what changed across the PostgreSQL multi-broker engine:

  • PostgreSQL completed counts are now exact past 50,000: Previously, getJobCountsAsync(), Stats, HTTP/WS dashboards, and getStats() counted only the in-memory PostgresQueueSnapshot hot cache, which evicts completed rows once maxCompletedJobs (50,000 globally across all queues) is reached even though PostgreSQL stores every completed row in bunqueue_jobs. loadPostgresManagerSnapshot now loads per-queue completed counts inside the same repeatable-read transaction, PostgresQueueSnapshot tracks evicted completed counts per queue with a zero-leak knownByQueue index, and TCP/HTTP/WS count and stats surfaces query PostgreSQL authoritatively via getQueueJobCountsDurable() and getStatsDurable() while reconciling the local snapshot. On live PostgreSQL 19.0, a 60,000-job burst (concurrency: 200) finished in 39.68 s (39.677 s) with 0 duplicates and exact completed = 60,000.
  • Bounded broker snapshot memory (maxCompletedPayloadBytes): Under large-payload workloads (800 x 128 KiB), counting only row count allowed cached completed rows and unpinned completion results to blow through 512 MiB broker pod limits and trigger maxSnapshotJobs errors on queue refreshes. PostgresQueueSnapshot, loadAllPostgresJobs, loadQueuePostgresJobs, loadPostgresCompletionResults, and assertPostgresSnapshotBudget now cap cached completed rows and unpinned completion results by bytes at min(16 MiB, floor(maxSnapshotPayloadBytes / 4)) (default 16 MiB for the default 256 MiB snapshot budget) while keeping per-queue completed counts exact. Under sustained chaos, all 4 broker pods stayed at 171-183 MiB (92-142 MiB on 800 x 128 KiB payloads + 20 x 42 s long jobs + cold pod replacement).
  • Safe multi-broker graceful drain (SIGTERM) and fresh broker identity: During rolling deploys, bootstrap.ts previously waited on cluster-wide getStats().active, hanging draining pods for 30 s whenever sibling brokers had active jobs; worse, heartbeats on open sockets transferred lease_broker_id onto the draining pod, and shutdown released live leases back to waiting, causing duplicate runs. In v2.9.25, bootstrap.ts waits only on each broker’s own leases (countOwnedActiveLeases()), beginDrain() stops heartbeat renewals from reassigning ownership onto the draining broker, and releasePostgresBrokerLeases() leaves actively renewed unexpired leases (lease_renewals > 0 AND lease_until > now) intact so workers finish cleanly via surviving brokers. Graceful drain dropped from 30 s to 4 s, rolling Recreate completed in 8 s with 0 duplicates, and omitting static BUNQUEUE_BROKER_ID=$(POD_NAME) in the Kubernetes deployment guide gives restarted containers an immediate <pod>:<pid>:<uuid> identity instead of a 30 s lockout.
  • Zero clientJobs memory leak: PostgresQueueManagerState now detaches clientJobs / clientJobOwners entries whenever a lease token is forgotten, a terminal ACK/FAIL/discard/cancel commits, or a journal projection/queue reload observes the job inactive (clientJobs = 0 after drain).
  • Fast /ready recovery after PostgreSQL restarts (5-6 s): Periodic dlq, event-retention, completion-retention, group-state-retention, recovery, and flow-failure-recovery sweeps now retry via PostgresPostCommitMaintenance, transient non-fenced heartbeat errors schedule bounded retries on postgresRetryDelayMs, and PostgreSQL pool connectionTimeout is reduced from 10 s to 5 s. Across 2 consecutive live postgres-0 restarts (5 s rollout), maximum /ready 503 duration fell from 18-60 s down to 5 s, with 4/4 brokers back at 200 OK at t = 6 s and 4/4 Kubernetes Ready brokers maintained throughout.
  • PostgreSQL Schema v22 partial indexes and sort-free FIFO claims: Automatic startup migration adds bunqueue_jobs_completed_recent_idx, bunqueue_jobs_non_completed_idx, and bunqueue_jobs_fifo_ready_idx (registered in the v22 catalog fingerprint), and selectUngroupedCandidates takes a pure index-ordered FIFO path whenever no ready LIFO job exists in the queue. Cold v21 -> v22 upgrade on 171,955 rows / 242 MB brought 4/4 brokers 1/1 Ready in 7 s at 91-95 MiB RAM (loadAllPostgresJobs 112.7 ms), eliminating temp-disk spills and dropping PostgreSQL heap fetches under chaos from 326,000,000 (326M) to 303,000 (303k).
Live cluster scenario (4 brokers, 512 MiB limit)Before (v2.9.24)After (v2.9.25)
PG 60,000-job burst (concurrency: 200) completed countCapped at 50,000Exact 60,000 (39.68 s, 0 duplicates)
SQLite 60,000-job TCP burst (concurrency: 200)~50 s stall, 60 duplicate runs11.32 s, 0 duplicates, 0 lost ACKs
480 s multi-broker chaos (143,820 jobs)Drain hang, clientJobs growth, sort spills143,820 / 143,820, 0 lost, 0 dup, 171-183 MiB
PULLB PostgreSQL heap fetches under chaos326,000,000 (326M)303,000 (303k, Schema v22 FIFO index)
Graceful broker drain (SIGTERM) / rolling Recreate30 s cluster-wide wait4 s drain / 8 s Recreate
/ready 503 recovery after postgres-0 restart18-60 s (trips readiness probes)5-6 s (4/4 200 OK at t = 6 s, 4/4 Ready)
Cold schema upgrade (171,955 rows / 242 MB)Full completed snapshot pressure7 s (91-95 MiB RAM, loadAllPostgresJobs 112.7 ms)

Additional live cluster resilience checks (Exp 2-7) verified FIFO groups + rate limits + broker SIGKILL, 120 three-level FlowProducer DAGs surviving a hard VM power-off (qm stop 203), thundering herd + pause/resume + cron, and 20,000-job burst ceilings (5,517 push/s on PostgreSQL and 11,383 push/s on SQLite).

High-concurrency TCP workers no longer drop ACKs or duplicate-run jobs under rate limits

Section titled “High-concurrency TCP workers no longer drop ACKs or duplicate-run jobs under rate limits”

A single TCP worker running concurrency: 200 against either SQLite or PostgreSQL previously hit a nasty cascade as soon as connection traffic crossed 10,000 commands per minute: 60 jobs ran twice and the worker stalled for roughly 50 s. Tracing the wire traffic revealed five interacting bugs, all fixed together in v2.9.25:

  1. Lazy TcpConnectionPool connection warming: A pool configured with poolSize: 4 previously funneled all commands through connection 0 instead of opening the remaining sockets. Once connection 0 succeeds, TcpConnectionPool now warms connections 1..poolSize-1 in the background so high-concurrency load spreads evenly across the pool.
  2. Delta-only lock heartbeats on pull: WorkerBuffer.bufferPulledJobs() previously sent heartbeats for every active job in the worker on every pull batch. It now renews locks only for the newly pulled delivery IDs, cutting redundant heartbeat traffic dramatically.
  3. Authenticated lease-settlement rate-limit exemption: Rejecting an ACK or JobHeartbeat with Rate limit exceeded does not shed load; it lets leases expire and forces duplicate execution. The TCP server now exempts authenticated connections from RATE_LIMIT_MAX_REQUESTS (default 10,000 requests per 60,000 ms RATE_LIMIT_WINDOW_MS) for the 10 lease-settlement and heartbeat commands (ACK, ACKB, FAIL, JobHeartbeat, JobHeartbeatB, Heartbeat, ExtendLock, ExtendLocks, MoveToWait, UnregisterWorker) while keeping unauthenticated connections and all intake/query commands (PUSH, PUSHB, PULL, PULLB) strictly rate-limited.
  4. Failover-grade AckBatcher retries: AckBatcher now fails fast on attempt 1 for permanent connection/auth errors while retrying transient outages up to 10 times with exponential backoff capped at 2,000 ms (cancellable immediately on stop()) to bridge multi-second broker or database failovers.
  5. Per-item ACK isolation on batch errors: When a multi-item ACKB fails with an item-scoped permanent rejection (such as a single expired lock token), AckBatcher now falls back to individual ACK delivery so one stale job never poisons valid siblings in the same batch.

On a 60,000-job SQLite TCP burst with concurrency: 200, the worker completed in 11.32 s (11.317 s) with 0 duplicates and 0 lost ACKs.

TypeScript SDK (bunqueue-client 0.2.4): full v2.9.24 parity, Node.js 20, mTLS, and +23.2% faster workers

Section titled “TypeScript SDK (bunqueue-client 0.2.4): full v2.9.24 parity, Node.js 20, mTLS, and +23.2% faster workers”

The standalone cross-runtime TypeScript SDK (sdk/typescript, bunqueue-client 0.2.4 for Bun, Node.js 20 & 22, Deno, and Cloudflare Workers) underwent a four-wave production hardening and performance pass covering 68 files (+5,401 / -1,221 lines) and 1,071 / 0 passing SDK sandbox tests (including 20/20 Cloudflare Workers workerd routes and 18/18 SQLite + PostgreSQL conformance):

import { BrokerAdmin, Queue, Worker } from 'bunqueue-client';
const tls = {
ca: process.env.BUNQUEUE_CA_PEM!,
cert: process.env.BUNQUEUE_CLIENT_CERT_PEM!,
key: process.env.BUNQUEUE_CLIENT_KEY_PEM!,
servername: 'bunqueue.internal',
};
const admin = new BrokerAdmin({ host: 'bunqueue.internal', port: 6789, tls });
const stats = await admin.getStats();
const queue = new Queue('orders', { connection: { host: 'bunqueue.internal', port: 6789, tls } });
const groups = await queue.listGroups();
const worker = new Worker('orders', async (job) => ({ processed: job.id }), {
connection: { socketPath: '/var/run/bunqueue.sock' },
concurrency: 32,
});
  • Full BrokerAdmin (22 commands) and QueueGroupsApi (13 commands): BrokerAdmin maps all 22 broker-wide v2.9.24 TCP commands (ping, hello, getStats, getMetrics, getPrometheusMetrics, getStorageStatus, compactMemory, listQueues, listWorkers, cron CRUD, webhook CRUD, dashboard endpoints, getJobByCustomId, getProgress), and Queue exposes all 13 QueueGroupsApi operations alongside groupMaxSize, GetDeduplicationJobId, and v2.9.24 non-empty lock-token enforcement in extendLock.
  • Node.js 20, Windows, inline PEM mTLS, SNI, and Unix socketPath: Replaced ES2024 Promise.withResolvers() and unguarded AbortSignal.any() in BatchExecution with an ES2022 fallback for Node.js 20; added inline ca/cert/key, certFile/keyFile, passphrase, automatic SNI servername, and Unix domain socketPath across both native src/client/tcp/ and portable bunqueue-client transports (hashing inline PEM secrets in pool keys); fixed an Auth race where socket teardown masked 'Authentication failed' as 'Connection lost'; hardened SandboxedWorker for Windows paths and V8 maxMemory; and pruned broken "src" packaging entries and server config imports from the client bundle.
  • Transport, framing, and Simple Mode safety: Hardened Connection, ConnectionPool, FrameParser, Backpressure, and Serialization with ES private #token, an Auth barrier, a 64 MiB outbound write-queue cap, an O(1) deadline semaphore, bounded DAG validation, cross-realm Date and re-entrant sanitize guards, isolated Unpackr, prototype-pollution-safe Bunqueue maps, and per-item ACK fallback on lease-fencing and serialization errors.
  • Native A/B verified hot-path optimizations: Single-pass copy-on-write serialization.ts with ancestor stack (1.21x-1.42x faster), zero-copy FrameParser.forEachFrame(), single-timer TcpClient.send() fast path, single-pass ACKB assembly with waitForInFlight() drain loop, prototype-backed PublicJob instances (100,000 jobs in 13.8 ms with private #ctx) plus cached stateless worker handlers, batch-draining WorkerPolling.tryProcess(), and a single-delivery fast path in WorkerExecution lifting Node.js Canonical Worker throughput by +23.2% (from 7,319 to 9,019 jobs/s).
  • Focused 4-SDK official lineup: Removed the PHP (sdk/php) and Elixir (sdk/elixir) SDKs, their conformance drivers, Docker targets, CI/mutation/security jobs, Dependabot entries, and docs pages (with permanent 308 redirects from /guide/sdks/php/ and /guide/sdks/elixir/ to /guide/sdks/). Official SDK engineering now focuses on TypeScript (1,071 / 0), Python (219 / 0), Go (114 / 0), and Rust (92 / 0).

Formally verified with TLA+ / TLC across 356,615 states

Section titled “Formally verified with TLA+ / TLC across 356,615 states”

Concurrent client pools, batchers, lease-drain handoffs, and circuit breakers fail in subtle interleavings that ordinary unit tests rarely hit. In v2.9.25, we verified 9 concurrent state machines with TLA+ / TLC (356,615 total generated states, 0 invariant violations) and codified mandatory TLA+ / TLC verification rules across the repository harness (CLAUDE.md, AGENTS.md, docs/testing.md, sdk/CLAUDE.md).

Formal verification across 9 TLA+ / TLC models (356,615 states, 0 errors) and hot-path SDK speedups Formal Verification (9 TLA+ / TLC Models) & Client Hot-Path Gains Broker & Worker Models (4 models · 123,777 states) PgCompletedCounts 34,666 states · 0 err BrokerDrainLeaseOwnership 81,175 states · 0 err AckBatcherPool 4,443 states · 0 err AckBatcherFallback 3,493 states · 0 err Exact counts, drain fencing, pool warming, per-item isolation TypeScript SDK Models (5 models · 232,838 states) 4 real concurrency races caught & fixed: 1. Connection stale bpEpoch fencing on reconnect 2. AddBatcher overlapping activeFlushes race 3. AddBatcher short-response undefined guard 4. WorkerCircuitBreaker epoch + destroy() guard 85,439 distinct states · 0 invariant violations Node.js Canonical Worker +23.2% (7,319 -> 9,019/s) serializeCommand Hot Path 1.21x-1.42x faster Prototype-Backed PublicJob 100,000 jobs in 13.8 ms
Total formal state-space checked across all 9 models: 356,615 states with 0 errors, backed by 17 new regression suites (3,975 lines).

Simplified documentation and a unified 2D visual system

Section titled “Simplified documentation and a unified 2D visual system”

Alongside runtime and SDK hardening, v2.9.25 ships a ground-up documentation simplification focused on clarity and speed:

  • Fewer pages, zero dead URLs: Consolidated 38 fragmented Queue, Worker, Cron, DLQ, and Flow guides into 12 scannable canonical pages with 32 permanent 308 redirects in docs/vercel.json, split the 2,543-line HTTP API reference into an overview with an endpoint index plus 5 sub-pages, split SDK docs into /guide/sdks/ plus 4 dedicated language guides (typescript, python, go, rust), and merged telemetry.md into monitoring.mdx.
  • Unified 2D diagrams and WCAG AA reading UX: Removed 65+ dead v1 assets, legacy .bq-diag boxes, broken .bq-sim loops, ASCII trees, and 3D isometric workflow cubes in favor of 8 theme-aware, container-queried 2D diagram and reading primitives (TldrCard, DecisionGrid, DiagramFrame, ArchDiagram, FlowDiagram, StateDiagram, SequenceDiagram, MetricBars). Simplified the sidebar from 11 sections to 6, unified desktop and mobile navigation (docs/src/lib/siteNav.ts), added clickable breadcrumbs and one-click Copy Markdown in DocsContext.astro, defaulted /blog/ to engineering Articles, moved table scroll wrapping to build time (rehypeTableLabels.ts), tightened prose measure (--sl-content-width: 56rem, 70ch), and raised button and selection contrast to WCAG AA (>= 4.5:1).
  • Automatic PostgreSQL Schema v22 migration: Startup automatically upgrades POSTGRES_SCHEMA_VERSION from 21 to 22 inside an advisory-locked transaction and creates three partial B-tree indexes (bunqueue_jobs_fifo_ready_idx, bunqueue_jobs_completed_recent_idx, bunqueue_jobs_non_completed_idx), fingerprinting all three in bunqueue_schema_migrations. No manual DDL is needed; allow a brief one-time index creation window on first boot (measured 7 s on 171,955 rows / 242 MB on PostgreSQL 19.0).
  • PostgreSQL snapshot byte cap (maxCompletedPayloadBytes) and exact completed counts: Cached completed rows and unpinned completion results are now capped by bytes at min(16 MiB, floor(maxSnapshotPayloadBytes / 4)) (default 16 MiB for the default 256 MiB snapshot budget) in addition to maxCompletedJobs (50,000), while getJobCountsAsync(), Stats, HTTP/WS dashboards, and getStats() report authoritative PostgreSQL completed counts instead of plateauing at 50,000.
  • Kubernetes BUNQUEUE_BROKER_ID and graceful drain: Omit static BUNQUEUE_BROKER_ID=$(POD_NAME) in Kubernetes manifests so restarted containers generate a fresh <pod>:<pid>:<uuid> identity immediately instead of waiting 30 s. On SIGTERM, brokers drain only their own active leases (countOwnedActiveLeases()), stop taking over heartbeats once draining (beginDrain()), and preserve actively renewed unexpired leases so healthy workers finish on surviving brokers without duplicate execution.
  • PostgreSQL pool connectionTimeout reduced from 10 s to 5 s: createPostgresConnection() now uses a 5 s connection timeout (down from 10 s), and transient background maintenance and non-fenced heartbeat failures retry on postgresRetryDelayMs, recovering /ready in 5-6 s instead of 18-60 s.
  • TCP rate-limit exemption for authenticated lease settlement: Authenticated connections bypass RATE_LIMIT_MAX_REQUESTS (default 10,000 requests per 60,000 ms RATE_LIMIT_WINDOW_MS, returning Rate limit exceeded) for the 10 lease-settlement and heartbeat commands (ACK, ACKB, FAIL, JobHeartbeat, JobHeartbeatB, Heartbeat, ExtendLock, ExtendLocks, MoveToWait, UnregisterWorker). Unauthenticated connections and all intake/query commands stay rate-limited.
  • AckBatcher failover retries and per-item fallback: Default maxRetries increases from 3 to 10 (2,000 ms capped exponential backoff, immediately cancellable on stop()), permanent connection/auth errors fail fast on attempt 1, and item-scoped permanent rejections in ACKB fall back to individual ACK calls.
  • Client socketPath, inline PEM TLS, SNI, Auth errors, AddBatcher, and PublicJob shape: ConnectionOptions.socketPath is validated as a non-empty string when set (TypeError / RangeError); ClientTlsOptions supports inline ca/cert/key, certFile/keyFile, passphrase, and servername (automatic SNI from DNS host), with inline PEM secrets hashed into shared pool keys. TcpClient surfaces 'Authentication failed' directly instead of 'Connection lost'. AddBatcher throws AddBatcher response length mismatch: expected <n>, got <m> on short responses. createPublicJob and toPublicJob return prototype-backed PublicJob instances with ES private #ctx (methods live on the prototype; { ...job }, toJSON(), and asJSON() expose all data fields including mutated returnvalue).
  • Focused 4-SDK lineup: PHP (sdk/php) and Elixir (sdk/elixir) SDKs have been removed (with 308 redirects from /guide/sdks/php/ and /guide/sdks/elixir/ to /guide/sdks/). TypeScript SDK bunqueue-client 0.2.4 is published separately through sdk-release.yml.

← bunqueue v2.9.24 · Full changelog · All posts