bunqueue v2.9.23
45 stability bugs fixed from TCP sockets down to SQLite, PostgreSQL, workers, and workflow recovery. Up to 321.78x faster multi-queue monitoring, 18.94x faster 64 KiB MessagePack decoding, ~15 ms PostgreSQL pruning on stale stats, and a 6-layer torture suite that ran 1,952,622 jobs with zero loss.
A job queue is easy to trust when everything works. What matters is what happens when a disk fills up, a browser tab stops reading SSE events, a worker crashes mid-batch, or a broker gets killed with SIGKILL.
In v2.9.23, we audited every layer of bunqueue and fixed 45 stability bugs across 72 source files (+1,095 / -436 lines), backed by 48 new regression tests (3,151 lines in 10 test files). Public API signatures and normal scheduling behavior stay the same. Guardrails for broken inputs and error paths are listed in Before you upgrade.
This release also includes two targeted speedups (25.23x to 321.78x faster multi-queue idle monitoring and 18.94x faster 64 KiB MessagePack decoding, giving 12.38% faster end-to-end TCP), a PostgreSQL completion-prune fix that drops slow stale-stats queries from 10.4 s in CI / 12.9-17.3 s locally down to ~15 ms, cleaner Worker.close() error handling, and 10 lifecycle fixes for jobs, dependencies, and nested workflows.
To install bunqueue v2.9.23
Section titled “To install bunqueue v2.9.23”bun add bunqueue@2.9.23npm install bunqueue@2.9.23TAG=2.9.23docker run -p 6789:6789 -p 6790:6790 ghcr.io/egeominotti/bunqueue:$TAGTo upgrade bunqueue
Section titled “To upgrade bunqueue”bun add bunqueue@latestWhere the 45 stability fixes landed
Section titled “Where the 45 stability fixes landed”We split the audit into four waves, one per layer of the stack. Every single bug had to fail 3/3 times on Linux against the previous baseline (53be601b) before we wrote a fix, and pass 3/3 times after. No touched source file exceeds 299 lines.
Here is what each wave fixes in plain terms:
- Wave 1 (Server & Network, 9 fixes): A malformed
reqId(like a>64-bit BigInt) or a non-string queue name can no longer crash the broker or/prometheus. Stalled SSE dashboards are capped at 1 MiB (SSE_MAX_BACKPRESSURE_BYTES) so they cannot exhaust server RAM. DisconnectedWaitJobcallers free their timers right away on memory/SQLite, and Cloud senders respectuseHttp: falseand preserve flush order. - Wave 2 (Core Queue Engine, 14 fixes): Cleanup (
cleanOrphanedJobIndex) andobliterate()can no longer race with active jobs or resurrect deleted queues. Four missing worker wakes (stallDetection,lockManager,clientTracking,dlqRetry) now fire reliably.CronSchedulerserializes overlapping ticks, backs off 1,000 ms on persistence errors instead of spinning at 0 ms, and drops exhausted schedules (nextRun <= 0). Cleanup frees all owned keys,RateLimiterhandles backward clock jumps, and stale tokenless timeout ACKs can no longer complete a newer retry. - Wave 3 (SQLite & PostgreSQL, 12 fixes): On SQLite,
WriteBuffernow removes pending entries only aftersafeWritecommits, so a full disk (SQLITE_FULL) no longer drops buffered jobs silently. Startup appliesPRAGMA busy_timeout = 5000before schema checks,getJobsreturns[]on invalid bounds, corrupt blobs are isolated, and queries use deterministicidtie-breakers. On PostgreSQL,removeChildDependencychecksparentRow.state === 'waiting-children', priority/delay/retry mutations preserve ready states,retryPostgresTerminalJobacquires advisory locks before row locks,forgetTokenverifies ownership, and retained deferred failures cap at 1,000. - Wave 4 (Clients, Workers & Workflows, 10 fixes): Concurrent
TcpClient.connect()calls no longer hang on failure orforceReconnect(), andFrameSizeErrorcloses desynced sockets cleanly. InWorker, a failed auto-ACK or throwingcompletedlistener no longer sendsFAILfor an already finished job.AckBatcher.queue()rejects afterstop(). Native batches cap atmin(batch.size, limiter.max)instead of livelocking and checkgroupLimiteron every candidate.SandboxedWorkerhandles apostrophes in file paths and returns jobs pulled duringstop().BatchAccumulator.flush()never hangs on sync throws or bad getters, and restarted workflow parents resume children that crashed mid-compensation.
For the full root-cause analysis of all 45 bugs, read the stability hardening engineering post.
How we tested v2.9.23: six layers of test engineering
Section titled “How we tested v2.9.23: six layers of test engineering”Unit tests check single functions. They rarely catch slow file-descriptor leaks, SQLite WAL growth, split TCP packets under backpressure, zombie workers with expired locks, or a real Linux disk-full error.
Before cutting v2.9.23, we ran the hardened code (6d7fd2e2) through a 6-layer validation pipeline. Each layer looks for a class of bug that the layers below it cannot see.
5-minute production marathon: 1,952,622 jobs, zero leaks
Section titled “5-minute production marathon: 1,952,622 jobs, zero leaks”On a Debian 13.7 VM (x86_64, AMD Ryzen 9 9950X, 16 vCPU, 15 GiB RAM, Bun 1.4.5), a single broker ran 300 s of continuous mixed production traffic followed by full drain (410 s total) on a 2.12 GiB SQLite database. Every 5 s (59 samples), we recorded process RSS, kernel open file descriptors (/proc/<pid>/fd), SQLite DB and WAL size, and live probe latency.
What ran inside that single marathon:
- 1,952,622 jobs pushed and 100% drained (0 lost, 0 stuck), including 8 flash-sale waves (20,000 jobs each) and 362/362 HTTP pushes and
/prometheusscrapes. - 19 forced worker kills, 6,465/6,465 DLQ verifications, 450 Flow DAGs (1,800 nodes), 3,000
SandboxedWorkerjobs, 156 Workflows (72/72 compensations), and 604 cron ticks. - 59,025,290 WebSocket events, 30 rotated stalled SSE streams, 1,448 corrupt/hostile TCP frames rejected safely, and 3 consecutive
SIGKILLcrashes recovering 3,000/3,000 durable jobs.
On the same VM, we also ran:
- Multi-service simulation (Stage 1): 50,000 flash-sale jobs in 7.19 s (6,952 jobs/s, p50 1,620 ms, p99 1,994 ms), 11,500 multi-tenant jobs + 500 DLQ across 3 killed workers, 100 Flow DAGs (400 nodes), 150
SandboxedWorkerjobs (with an apostrophe in the path), 65 TCP Workflows (30 linear, 20 signal, 15 rollbacks = 30/30 child compensations), 5/5 exact cron ticks, 191,439 WS events, 20 stalled SSE streams, 43/43/prometheusscrapes, and 1,000/1,000 durable jobs recovered afterSIGKILL(RSS 63.6 → peak 461.2 → 419.5 MiB, FDs 12 → peak 75 → 55). - Chaos soak & crash fuzzing (Stages 2 to 4): A 45 s soak (
SOAK_MS=45000,SOAK_KILL_MS=250) completed 30,000/30,000 jobs (30,045 asserts) across 160 worker kills with WAL flat at 4.1 → 4.3 MB and probe latency p50 0.041 → 0.044 ms / p99 0.161 → 0.151 ms. That was followed by 35 consecutiveSIGKILLcycles (7/7, 4,473 asserts) and 83/83 (947 asserts) fault-injection, truncated/corrupt WAL, and write-contention tests.
Hostile networks, zombie workers, and real Linux disk-full (ENOSPC)
Section titled “Hostile networks, zombie workers, and real Linux disk-full (ENOSPC)”Clean localhost tests never split a TCP packet into 1-byte chunks or let a frozen worker wake up after its lock expired. We tested those scenarios directly.
SocketWriteQueue splits TCP frames into 1 to 3 byte fragments and triggers 2.5 s blackholes plus RST. Right: 40 expired workers wake up and try 80 stale mutations, and all 80 are rejected.- Extreme broker torture: 400-client TCP storm (FDs 12 → 12), 100 WebSocket + 60 stalled SSE streams across 10,000 jobs (1,842,200 WS messages, FDs 12 → 11, RSS 126.4 MiB), 200 concurrent
obliterate()/drain()/clean()/pause()/resume()calls across 6 active queues (postObliterateClean: true), 100,000-job 1-4 KiB backlog (push 1,593 ms / 62,775 ops/s, drain 7,819 ms / 12,789 ops/s, RSS 617.8 MiB, invalid bounds returning[]), and 10 live TLSSIGHUPcertificate rotations (8 valid + 2 corrupt pairs refused atomically). - Nested workflow crashes & DAG
SIGKILL: A 3-level workflow (parent → mid → leaf) crashed mid-rollback and resumed in exact reverse order (leaf-2 → leaf-1 → mid-1 → parent-1). Operator controls settled stuck runs (resumeCompensation()→failed/completed,abandonCompensation()→failed/stuck). 40 multi-queue DAGs across all 4 failure policies (10 normal, 10 ignore, 10 remove, 10 failParent→DLQ) survivedSIGKILL. - Live backups & real Linux
ENOSPC: 3 liveVACUUM INTOSQLite snapshots taken during active writes all passedPRAGMA integrity_check = ok. On a real 16 MiBtmpfsmount, SQLite hit genuine LinuxENOSPC/SQLITE_FULLacross allDF1-DF9tests (9 pass / 0 fail, 130 asserts in 879 ms).
Multi-broker PostgreSQL 18.7, all 6 SDKs, and zero-slowdown A/B benchmarks
Section titled “Multi-broker PostgreSQL 18.7, all 6 SDKs, and zero-slowdown A/B benchmarks”- PostgreSQL 18.7: 572 pass / 0 fail / 1 skip (12,674 asserts across 126 files) plus the 10-broker crash soak (
bun run test:postgres:ten-broker: 10 brokers, 40 consumers, 20,000 steady jobs at 6,546.55 jobs/s, 2 hard-crashed brokers, 5,000 recovery jobs, 200 recovered leases, 0 deadlocks, 0ackbFailures, 0transactionRetries) for 573/573 passing. - All 6 official SDKs (
bun run test:sandbox:sdk, SQLite + PostgreSQL C01-C18): 0 anomalies on6d7fd2e2and 0 surviving processes: TypeScript 882/0/0 (Node 20/22, Deno, Bun, Cloudflareworkerd18/18), Python 219/0/0, PHP 105/0/0, Go 114/0/1, Rust 92/0/1, Elixir 145/0/1, plus client parity (91 client and 39 workflow exports, 0 diffs, 133/133 parity tests). - Full native Linux
x86_64Bun 1.4.5 suites: embedded 43/43 (349/349), TCP 69/69 (553/553), WebSocket/SSE 8/8 (88/88), MCP 46/46 (576/576), Core Public API E2E (621/621), built-client/parity (149/0/2 across 17 files), and--rerun-each 5across 14 files (430/430, 2,675 asserts in 27.03 s). - Controlled A/B benchmarks (
53be601bvs6d7fd2e2): Adding 45 stability guards caused zero hot-path slowdown on either macOS or Linux.
| Benchmark (median) | macOS M5 Max (53be601b → 6d7fd2e2) | Linux 9950X (53be601b → 6d7fd2e2) |
|---|---|---|
| SQLite durable lifecycle (5,000 × 5) | 9,153 → 9,131 jobs/s (546.27 → 547.57 ms) | 23,173 → 23,258 jobs/s (215.77 → 214.98 ms) |
| TCP serde pipelined (20,000 × 5) | 18,282 → 17,825 ops/s (p50 50 → 52 µs) | 14,771 → 14,954 ops/s (p50 98 → 99 µs, p99 523 → 501 µs) |
TCP PUSHB bulk (20,000 × 5) | 91,328 → 90,271 ops/s | 90,903 → 90,568 ops/s |
getJobs 20,000 jobs (no filter, 500 runs) | 259.7 → 259.5 µs | 302.8 → 303.1 µs (all states 193.9 → 183.7 µs) |
| TCP 50,000 push / bulk (median of 3) | 62,769 → 63,056 / 62,848 → 63,650 ops/s | 73,545 → 74,470 / 74,551 → 77,684 ops/s |
Workflow Engine (tcp/linear, 5 runs) | 1,036 → 1,040 wf/s | 2,088 → 2,110 wf/s |
Faster monitoring, MessagePack decoding, and PostgreSQL pruning
Section titled “Faster monitoring, MessagePack decoding, and PostgreSQL pruning”Three focused performance fixes landed alongside the stability campaign.
- Count active jobs once per monitoring pass: Previously, idle monitoring rescanned every processing shard for every queue. Now it aggregates active counts once per pass and refreshes after any synchronous idle callback. See the full monitoring and MessagePack write-up.
- Native
__proto__byte scan in MessagePack: Decoding now uses nativeBuffer.indexOfover a zero-copy view of the input bytes while keeping the same safe prototype-preserving materialization. - Fast PostgreSQL completion pruning on fresh namespaces: Before
ANALYZEran, PostgreSQL estimated ~1 row and chose slow nested loops that took 10.4 s on 290 completions in CI and 12.9-17.3 s on 619 locally (PostgreSQL 16-18), causinglock_timeoutfailures on sibling brokers’ 60 s sweeps. The updated query avoids nested loops and probes each recheck row by its full key, finishing in ~15 ms with no schema change.
Safer job delivery, dependencies, and workflow rollbacks
Section titled “Safer job delivery, dependencies, and workflow rollbacks”Commit 53be601b also closed 10 subtle lifecycle issues across embedded, SQLite, and PostgreSQL modes:
- Ordinary jobs with
cron:keys are safe: The broker now tracks which scheduler created a cron tick, so regular user jobs withcron:deduplication keys survive disconnects, restarts, and scheduler registration. - Dependencies stay consistent: Pushing a cached
customIdpreserves jobs parked inwaiting-children. Canceling a dependent keeps its unfinished prerequisite intact, and waiting jobs still run even after an earlier completion left the in-memory cache. - Cleaner worker lifecycle: Graceful worker shutdown keeps active leases alive until jobs finish, pausing during a pull keeps the returned delivery, and changing
job.datainside a handler still releases the original group concurrency slot. - Safer nested workflows: Child rollback verifies the stored workflow definition hash (
WorkflowDefinitionMismatchErroron mismatch), retention keeps child history needed by a live parent, and child signal waits keep their deadlines across restarts.
Before you upgrade
Section titled “Before you upgrade”- In-flight cron ticks during upgrade: Active cron jobs created by an older broker have no scheduler origin and follow normal recovery, so an in-flight tick can run again once after upgrading.
- Retained completed
customIdguard: Reusing acustomIdthat matches a retained completed job with unresolved dependents now throwsCustom ID <id> still has unresolved dependency consumers. - Manual
Worker.getNextJob()leases and close: Manually pulled jobs are no longer heartbeat-renewed outsideprocessJobManually()(callextendLock/jobHeartbeatdirectly when managing manual leases), andgetNextJob()/processJob()returnundefined(releasing any concurrently pulled job) as soon asclose()starts. - Nested workflow definition guard: If a child workflow definition changed since execution started, rollback throws
WorkflowDefinitionMismatchError. Keep the old definition registered while draining active runs. - SSE 1 MiB backpressure cap:
SSE_MAX_BACKPRESSURE_BYTES(1024 * 1024) drops overflow chunks for stalled consumers (SseHandler.droppedMessages), stops replay under backpressure, and prunes dead streams via zero-byte heartbeats. - Strict wire queue names and
reqId: Non-string wire queue names return'Queue name must be a string'(omitted/null/''keep'Queue name is required'). Non-string TCP/WebSocketreqIdvalues are normalized toundefined. CloudAgent.stop()withuseHttp: false: StoppingCloudAgentskips the final HTTP snapshot whenuseHttpisfalse.WaitJobdisconnect cancellation: Disconnected HTTP, WebSocket, and TCP callers releaseWaitJobwaiters and timers immediately on memory/SQLite (PostgreSQLwaitForJobResultis unchanged).CronSchedulererror backoff and exhausted schedules:persistCronfailures back off by 1,000 ms instead of spinning at 0 ms, and exhausted schedules (nextRun <= 0) stay out ofcronHeap.- SQLite
getJobsbounds andbusy_timeout:getJobsreturns[]forNaN,Infinity,end <= 0, orend <= start(clamping negativestartto0).PRAGMA busy_timeout = 5000now runs before schema checks. - PostgreSQL
removeChildDependencyand deferred failure cap:removeChildDependencyreturnsfalseunless the parent is in'waiting-children'(and emits'updated'on the child when removed).PostgresDeferredWriteQueuecaps retained failures at 1,000. - Worker errors,
close(),AckBatcher, and native batches: Failed auto-ACKs and throwingcompletedlisteners no longerFAILfinished jobs. They emit freshErrorobjects (cause+context: 'ack' | 'ack-stale' | 'completed-listener'), logging viaconsole.error('[Worker] Processor error:', ...)when no'error'listener is attached.Worker.close()stops emittingClientClosedErrorfrom in-flightHeartbeat,JobHeartbeat, andRegisterWorkercalls.AckBatcher.queue()rejects with'AckBatcher stopped'afterstop(). Native batches cap atmin(batch.size, limiter.max)and enforcegroupLimiteracross all candidates. - TLS unix-socket rollback: A
chownerror during rollback logsHTTP unix socket owner not restored after a TLS reloadand still restoreschmod. - Python SDK requires Python 3.10+: Python 3.9 support is dropped in the repo for the next Python SDK release (existing PyPI 0.1.5 still installs on Python 3.9). Server, wire protocol, and other SDKs are unaffected.
- Minimum supported PostgreSQL is 16: CI tests PostgreSQL 16-18 (18.6 pinned and recommended). Existing PostgreSQL 15 deployments are not rejected at runtime, but are no longer tested in CI.
Other improvements and bugfixes
Section titled “Other improvements and bugfixes”- Cleaner
Worker.close()shutdown: Fire-and-forgetHeartbeat,JobHeartbeat, andRegisterWorkercalls cancelled during Worker pool teardown no longer trigger unhandledClientClosedErrorevents. - TLS unix-socket rollback mode fix: Always restores the previous socket mode even when
chownfails with an error other thanEPERM. - Faster test suite & flake fixes: Replacing fixed sleeps with condition polling across the 15 slowest unit files cut host time from 676 s to 117 s (about 140 s off 4-worker unit wall time), and tighter integration waits cut the full parallel sandbox from 8.92 to 6.83 minutes (TCP 8.91 → 5.94 min, embedded 4.13 → 1.58 min). 4 previously skipped PostgreSQL regression files (21 cases) now run under
test:postgres, and 3 unit flakes plus 2 PostgreSQL CI flakes are fixed. - Package & contributor tooling:
package.jsonfilesuses!dist/benchmark/**forbun pm packparity, dead internal files were removed (1,724 package files instead of 1,748, zero public API changes), and cross-client contributor Agent Skills (.agents/skills/),ci-watch.sh, and hardenedmachine-gate.sh(retiring exit 3) landed in repository tooling.
How these numbers were measured
Section titled “How these numbers were measured”- Idle monitoring & MessagePack (
bf559e5a): Serial measurements on native macOS (Apple M5 Max, 18 logical CPUs, 64 GiB RAM, Bun 1.4.4), 7 fresh-process runs per variant after 1 warm-up; TCP ran memory-only without auto-batching. - A/B stability benchmarks (
53be601bvs6d7fd2e2): Native macOS (Apple M5 Max, 18 logical CPUs, 64 GiB RAM, Bun 1.4.4) and diagnostic Debian 13.7 Linux VM (AMD Ryzen 9 9950X, 16 vCPU, 15 GiB RAM, Bun 1.4.5), 5 runs per scenario (3 for 50,000 push/bulk, 500 calls forgetJobs). - Endurance marathon, torture suite, fault proxy, and
ENOSPC: Executed on the Debian 13.7 VM (x86_64, Bun 1.4.5) against live TCP/HTTP/SQLite brokers. PostgreSQL 18.7 (postgres:18.7) and 6-SDK C01-C18 conformance ran in isolated containers. - PostgreSQL completion prune: Measured locally on PostgreSQL 16-18 (619 completions) and observed in CI (290 completions).
Thanks to 1 contributor!
Section titled “Thanks to 1 contributor!”← bunqueue v2.9.22 · Release on GitHub · Commits since v2.9.22 · Full changelog · All posts