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.
To install bunqueue v2.9.25
Section titled “To install bunqueue v2.9.25”curl -fsSL https://bunqueue.dev/install.sh | sh -s -- --version 2.9.25& ([scriptblock]::Create((irm https://bunqueue.dev/install.ps1))) -Version 2.9.25bun add bunqueue@2.9.25npm install bunqueue@2.9.25TAG=2.9.25docker run -p 6789:6789 -p 6790:6790 ghcr.io/egeominotti/bunqueue:$TAGTo upgrade bunqueue
Section titled “To upgrade bunqueue”bun add bunqueue@latestHardened 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.
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
completedcounts are now exact past50,000: Previously,getJobCountsAsync(),Stats, HTTP/WS dashboards, andgetStats()counted only the in-memoryPostgresQueueSnapshothot cache, which evicts completed rows oncemaxCompletedJobs(50,000globally across all queues) is reached even though PostgreSQL stores every completed row inbunqueue_jobs.loadPostgresManagerSnapshotnow loads per-queue completed counts inside the same repeatable-read transaction,PostgresQueueSnapshottracks evicted completed counts per queue with a zero-leakknownByQueueindex, and TCP/HTTP/WS count and stats surfaces query PostgreSQL authoritatively viagetQueueJobCountsDurable()andgetStatsDurable()while reconciling the local snapshot. On live PostgreSQL19.0, a60,000-job burst (concurrency: 200) finished in39.68 s(39.677 s) with0duplicates and exactcompleted = 60,000. - Bounded broker snapshot memory (
maxCompletedPayloadBytes): Under large-payload workloads (800x128 KiB), counting only row count allowed cached completed rows and unpinned completion results to blow through512 MiBbroker pod limits and triggermaxSnapshotJobserrors on queue refreshes.PostgresQueueSnapshot,loadAllPostgresJobs,loadQueuePostgresJobs,loadPostgresCompletionResults, andassertPostgresSnapshotBudgetnow cap cached completed rows and unpinned completion results by bytes atmin(16 MiB, floor(maxSnapshotPayloadBytes / 4))(default16 MiBfor the default256 MiBsnapshot budget) while keeping per-queue completed counts exact. Under sustained chaos, all4broker pods stayed at171-183 MiB(92-142 MiBon800x128 KiBpayloads +20x42 slong jobs + cold pod replacement). - Safe multi-broker graceful drain (
SIGTERM) and fresh broker identity: During rolling deploys,bootstrap.tspreviously waited on cluster-widegetStats().active, hanging draining pods for30 swhenever sibling brokers had active jobs; worse, heartbeats on open sockets transferredlease_broker_idonto the draining pod, and shutdown released live leases back towaiting, causing duplicate runs. In v2.9.25,bootstrap.tswaits only on each broker’s own leases (countOwnedActiveLeases()),beginDrain()stops heartbeat renewals from reassigning ownership onto the draining broker, andreleasePostgresBrokerLeases()leaves actively renewed unexpired leases (lease_renewals > 0 AND lease_until > now) intact so workers finish cleanly via surviving brokers. Graceful drain dropped from30 sto4 s, rollingRecreatecompleted in8 swith0duplicates, and omitting staticBUNQUEUE_BROKER_ID=$(POD_NAME)in the Kubernetes deployment guide gives restarted containers an immediate<pod>:<pid>:<uuid>identity instead of a30 slockout. - Zero
clientJobsmemory leak:PostgresQueueManagerStatenow detachesclientJobs/clientJobOwnersentries whenever a lease token is forgotten, a terminal ACK/FAIL/discard/cancel commits, or a journal projection/queue reload observes the job inactive (clientJobs = 0after drain). - Fast
/readyrecovery after PostgreSQL restarts (5-6 s): Periodicdlq,event-retention,completion-retention,group-state-retention,recovery, andflow-failure-recoverysweeps now retry viaPostgresPostCommitMaintenance, transient non-fencedheartbeaterrors schedule bounded retries onpostgresRetryDelayMs, and PostgreSQL poolconnectionTimeoutis reduced from10 sto5 s. Across2consecutive livepostgres-0restarts (5 srollout), maximum/ready503duration fell from18-60 sdown to5 s, with4/4brokers back at200 OKatt = 6 sand4/4KubernetesReadybrokers 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, andbunqueue_jobs_fifo_ready_idx(registered in the v22 catalog fingerprint), andselectUngroupedCandidatestakes a pure index-ordered FIFO path whenever no ready LIFO job exists in the queue. Cold v21 -> v22 upgrade on171,955rows /242 MBbrought4/4brokers1/1 Readyin7 sat91-95 MiBRAM (loadAllPostgresJobs112.7 ms), eliminating temp-disk spills and dropping PostgreSQL heap fetches under chaos from326,000,000(326M) to303,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 count | Capped at 50,000 | Exact 60,000 (39.68 s, 0 duplicates) |
SQLite 60,000-job TCP burst (concurrency: 200) | ~50 s stall, 60 duplicate runs | 11.32 s, 0 duplicates, 0 lost ACKs |
480 s multi-broker chaos (143,820 jobs) | Drain hang, clientJobs growth, sort spills | 143,820 / 143,820, 0 lost, 0 dup, 171-183 MiB |
PULLB PostgreSQL heap fetches under chaos | 326,000,000 (326M) | 303,000 (303k, Schema v22 FIFO index) |
Graceful broker drain (SIGTERM) / rolling Recreate | 30 s cluster-wide wait | 4 s drain / 8 s Recreate |
/ready 503 recovery after postgres-0 restart | 18-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 pressure | 7 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:
- Lazy
TcpConnectionPoolconnection warming: A pool configured withpoolSize: 4previously funneled all commands through connection0instead of opening the remaining sockets. Once connection0succeeds,TcpConnectionPoolnow warms connections1..poolSize-1in the background so high-concurrency load spreads evenly across the pool. - 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. - Authenticated lease-settlement rate-limit exemption: Rejecting an
ACKorJobHeartbeatwithRate limit exceededdoes not shed load; it lets leases expire and forces duplicate execution. The TCP server now exempts authenticated connections fromRATE_LIMIT_MAX_REQUESTS(default10,000requests per60,000 msRATE_LIMIT_WINDOW_MS) for the10lease-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. - Failover-grade
AckBatcherretries:AckBatchernow fails fast on attempt1for permanent connection/auth errors while retrying transient outages up to10times with exponential backoff capped at2,000 ms(cancellable immediately onstop()) to bridge multi-second broker or database failovers. - Per-item
ACKisolation on batch errors: When a multi-itemACKBfails with an item-scoped permanent rejection (such as a single expired lock token),AckBatchernow falls back to individualACKdelivery 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(22commands) andQueueGroupsApi(13commands):BrokerAdminmaps all22broker-widev2.9.24TCP commands (ping,hello,getStats,getMetrics,getPrometheusMetrics,getStorageStatus,compactMemory,listQueues,listWorkers, cron CRUD, webhook CRUD, dashboard endpoints,getJobByCustomId,getProgress), andQueueexposes all13QueueGroupsApioperations alongsidegroupMaxSize,GetDeduplicationJobId, andv2.9.24non-empty lock-token enforcement inextendLock. - Node.js
20, Windows, inline PEM mTLS, SNI, and UnixsocketPath: Replaced ES2024Promise.withResolvers()and unguardedAbortSignal.any()inBatchExecutionwith an ES2022 fallback for Node.js20; added inlineca/cert/key,certFile/keyFile,passphrase, automatic SNIservername, and Unix domainsocketPathacross both nativesrc/client/tcp/and portablebunqueue-clienttransports (hashing inline PEM secrets in pool keys); fixed anAuthrace where socket teardown masked'Authentication failed'as'Connection lost'; hardenedSandboxedWorkerfor Windows paths and V8maxMemory; 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, andSerializationwith ES private#token, an Auth barrier, a64 MiBoutbound write-queue cap, an O(1) deadline semaphore, bounded DAG validation, cross-realmDateand re-entrantsanitizeguards, isolatedUnpackr, prototype-pollution-safeBunqueuemaps, and per-itemACKfallback on lease-fencing and serialization errors. - Native A/B verified hot-path optimizations: Single-pass copy-on-write
serialization.tswith ancestor stack (1.21x-1.42xfaster), zero-copyFrameParser.forEachFrame(), single-timerTcpClient.send()fast path, single-passACKBassembly withwaitForInFlight()drain loop, prototype-backedPublicJobinstances (100,000jobs in13.8 mswith private#ctx) plus cached stateless worker handlers, batch-drainingWorkerPolling.tryProcess(), and a single-delivery fast path inWorkerExecutionlifting Node.js Canonical Worker throughput by+23.2%(from7,319to9,019jobs/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 permanent308redirects 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).
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
38fragmented Queue, Worker, Cron, DLQ, and Flow guides into12scannable canonical pages with32permanent308redirects indocs/vercel.json, split the2,543-line HTTP API reference into an overview with an endpoint index plus5sub-pages, split SDK docs into/guide/sdks/plus4dedicated language guides (typescript,python,go,rust), and mergedtelemetry.mdintomonitoring.mdx. - Unified 2D diagrams and WCAG AA reading UX: Removed
65+dead v1 assets, legacy.bq-diagboxes, broken.bq-simloops, ASCII trees, and 3D isometric workflow cubes in favor of8theme-aware, container-queried 2D diagram and reading primitives (TldrCard,DecisionGrid,DiagramFrame,ArchDiagram,FlowDiagram,StateDiagram,SequenceDiagram,MetricBars). Simplified the sidebar from11sections to6, unified desktop and mobile navigation (docs/src/lib/siteNav.ts), added clickable breadcrumbs and one-clickCopy MarkdowninDocsContext.astro, defaulted/blog/to engineeringArticles, 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).
Before you upgrade
Section titled “Before you upgrade”- Automatic PostgreSQL Schema v22 migration: Startup automatically upgrades
POSTGRES_SCHEMA_VERSIONfrom21to22inside 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 inbunqueue_schema_migrations. No manual DDL is needed; allow a brief one-time index creation window on first boot (measured7 son171,955rows /242 MBon PostgreSQL19.0). - PostgreSQL snapshot byte cap (
maxCompletedPayloadBytes) and exact completed counts: Cached completed rows and unpinned completion results are now capped by bytes atmin(16 MiB, floor(maxSnapshotPayloadBytes / 4))(default16 MiBfor the default256 MiBsnapshot budget) in addition tomaxCompletedJobs(50,000), whilegetJobCountsAsync(),Stats, HTTP/WS dashboards, andgetStats()report authoritative PostgreSQL completed counts instead of plateauing at50,000. - Kubernetes
BUNQUEUE_BROKER_IDand graceful drain: Omit staticBUNQUEUE_BROKER_ID=$(POD_NAME)in Kubernetes manifests so restarted containers generate a fresh<pod>:<pid>:<uuid>identity immediately instead of waiting30 s. OnSIGTERM, 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
connectionTimeoutreduced from10 sto5 s:createPostgresConnection()now uses a5 sconnection timeout (down from10 s), and transient background maintenance and non-fenced heartbeat failures retry onpostgresRetryDelayMs, recovering/readyin5-6 sinstead of18-60 s. - TCP rate-limit exemption for authenticated lease settlement: Authenticated connections bypass
RATE_LIMIT_MAX_REQUESTS(default10,000requests per60,000 msRATE_LIMIT_WINDOW_MS, returningRate limit exceeded) for the10lease-settlement and heartbeat commands (ACK,ACKB,FAIL,JobHeartbeat,JobHeartbeatB,Heartbeat,ExtendLock,ExtendLocks,MoveToWait,UnregisterWorker). Unauthenticated connections and all intake/query commands stay rate-limited. AckBatcherfailover retries and per-item fallback: DefaultmaxRetriesincreases from3to10(2,000 mscapped exponential backoff, immediately cancellable onstop()), permanent connection/auth errors fail fast on attempt1, and item-scoped permanent rejections inACKBfall back to individualACKcalls.- Client
socketPath, inline PEM TLS, SNI,Autherrors,AddBatcher, andPublicJobshape:ConnectionOptions.socketPathis validated as a non-empty string when set (TypeError/RangeError);ClientTlsOptionssupports inlineca/cert/key,certFile/keyFile,passphrase, andservername(automatic SNI from DNShost), with inline PEM secrets hashed into shared pool keys.TcpClientsurfaces'Authentication failed'directly instead of'Connection lost'.AddBatcherthrowsAddBatcher response length mismatch: expected <n>, got <m>on short responses.createPublicJobandtoPublicJobreturn prototype-backedPublicJobinstances with ES private#ctx(methods live on the prototype;{ ...job },toJSON(), andasJSON()expose all data fields including mutatedreturnvalue). - Focused
4-SDK lineup: PHP (sdk/php) and Elixir (sdk/elixir) SDKs have been removed (with308redirects from/guide/sdks/php/and/guide/sdks/elixir/to/guide/sdks/). TypeScript SDKbunqueue-client0.2.4is published separately throughsdk-release.yml.