# bunqueue v2.9.23

bunqueue v2.9.23: 45 stability fixes, up to 321.78x faster multi-queue monitoring, 18.94x faster MessagePack decode, ~15 ms PG pruning, 1.95M-job torture.

Canonical: https://bunqueue.dev/blog/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.

![](https://github.com/egeominotti.png?size=64) [egeominotti](https://github.com/egeominotti)

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](#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

```bash title="bun"
bun add bunqueue@2.9.23
```

```bash title="npm"
npm install bunqueue@2.9.23
```

```bash title="docker"
TAG=2.9.23
docker run -p 6789:6789 -p 6790:6790 ghcr.io/egeominotti/bunqueue:$TAG
```

#### To upgrade bunqueue

```bash
bun add bunqueue@latest
```

## 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.

Total across all four waves: **45 bugs fixed**, **48 new regression tests** (3,151 lines), **72 source files** (+1,095 / -436 lines), and **16 updated internal docs**.

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. Disconnected `WaitJob` callers free their timers right away on memory/SQLite, and Cloud senders respect `useHttp: false` and preserve flush order.
- **Wave 2 (Core Queue Engine, 14 fixes):** Cleanup (`cleanOrphanedJobIndex`) and `obliterate()` can no longer race with active jobs or resurrect deleted queues. Four missing worker wakes (`stallDetection`, `lockManager`, `clientTracking`, `dlqRetry`) now fire reliably. `CronScheduler` serializes 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, `RateLimiter` handles backward clock jumps, and stale tokenless timeout ACKs can no longer complete a newer retry.
- **Wave 3 (SQLite & PostgreSQL, 12 fixes):** On SQLite, `WriteBuffer` now removes pending entries only *after* `safeWrite` commits, so a full disk (`SQLITE_FULL`) no longer drops buffered jobs silently. Startup applies `PRAGMA busy_timeout = 5000` before schema checks, `getJobs` returns `[]` on invalid bounds, corrupt blobs are isolated, and queries use deterministic `id` tie-breakers. On PostgreSQL, `removeChildDependency` checks `parentRow.state === 'waiting-children'`, priority/delay/retry mutations preserve ready states, `retryPostgresTerminalJob` acquires advisory locks before row locks, `forgetToken` verifies 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 or `forceReconnect()`, and `FrameSizeError` closes desynced sockets cleanly. In `Worker`, a failed auto-ACK or throwing `completed` listener no longer sends `FAIL` for an already finished job. `AckBatcher.queue()` rejects after `stop()`. Native batches cap at `min(batch.size, limiter.max)` instead of livelocking and check `groupLimiter` on every candidate. `SandboxedWorker` handles apostrophes in file paths and returns jobs pulled during `stop()`. `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](https://bunqueue.dev/blog/stability-hardening-45-bugs/).

## 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.

Each layer tests a different failure mode: deterministic bugs at the base, random state-machine histories in the middle, and real Linux endurance, hostile sockets, and multi-broker PostgreSQL at the top.

### 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.

During 410 seconds of mixed traffic, open file descriptors returned from 84 to exactly 12, the WAL stayed flat at 4.05 to 4.27 MiB on a 2.12 GiB database, and probe latency stayed at p50 7.00 → 5.35 ms (max p99 42.96 ms).

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 `/prometheus` scrapes**.
- **19 forced worker kills**, **6,465/6,465 DLQ verifications**, **450 Flow DAGs** (1,800 nodes), **3,000 `SandboxedWorker` jobs**, **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 `SIGKILL` crashes** 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 `SandboxedWorker` jobs (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 `/prometheus` scrapes, and 1,000/1,000 durable jobs recovered after `SIGKILL` (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 consecutive `SIGKILL` cycles** (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`)

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.

Left: a custom proxy built on `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 TLS `SIGHUP` certificate 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) survived `SIGKILL`.
- **Live backups & real Linux `ENOSPC`:** 3 live `VACUUM INTO` SQLite snapshots taken during active writes all passed `PRAGMA integrity_check = ok`. On a real **16 MiB `tmpfs`** mount, SQLite hit genuine Linux `ENOSPC`/`SQLITE_FULL` across all `DF1-DF9` tests (**9 pass / 0 fail**, 130 asserts in 879 ms).

### 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**, **0 `ackbFailures`**, **0 `transactionRetries`**) for **573/573 passing**.
- **All 6 official SDKs (`bun run test:sandbox:sdk`, SQLite + PostgreSQL C01-C18):** 0 anomalies on `6d7fd2e2` and 0 surviving processes: TypeScript 882/0/0 (Node 20/22, Deno, Bun, Cloudflare `workerd` 18/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_64` Bun 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 5` across 14 files (430/430, 2,675 asserts in 27.03 s).
- **Controlled A/B benchmarks (`53be601b` vs `6d7fd2e2`):** 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

Three focused performance fixes landed alongside the stability campaign.

Idle monitoring at 100 queues / 10,000 active jobs also dropped from 2.284235 ms to 0.090535 ms (25.23x faster); the 1-queue control moved from 0.169 to 0.193 µs (+24 ns, 14.29%). Small 32-byte TCP payloads were inconclusive.

- **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](https://bunqueue.dev/blog/faster-monitoring-and-msgpack/).
- **Native `__proto__` byte scan in MessagePack:** Decoding now uses native `Buffer.indexOf` over a zero-copy view of the input bytes while keeping the same safe prototype-preserving materialization.
- **Fast PostgreSQL completion pruning on fresh namespaces:** Before `ANALYZE` ran, 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), causing `lock_timeout` failures 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

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 with `cron:` deduplication keys survive disconnects, restarts, and scheduler registration.
- **Dependencies stay consistent:** Pushing a cached `customId` preserves jobs parked in `waiting-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.data` inside a handler still releases the original group concurrency slot.
- **Safer nested workflows:** Child rollback verifies the stored workflow definition hash (`WorkflowDefinitionMismatchError` on mismatch), retention keeps child history needed by a live parent, and child signal waits keep their deadlines across restarts.

## 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 `customId` guard:** Reusing a `customId` that matches a retained completed job with unresolved dependents now throws `Custom ID <id> still has unresolved dependency consumers`.
- **Manual `Worker.getNextJob()` leases and close:** Manually pulled jobs are no longer heartbeat-renewed outside `processJobManually()` (call `extendLock` / `jobHeartbeat` directly when managing manual leases), and `getNextJob()`/`processJob()` return `undefined` (releasing any concurrently pulled job) as soon as `close()` 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/WebSocket `reqId` values are normalized to `undefined`.
- **`CloudAgent.stop()` with `useHttp: false`:** Stopping `CloudAgent` skips the final HTTP snapshot when `useHttp` is `false`.
- **`WaitJob` disconnect cancellation:** Disconnected HTTP, WebSocket, and TCP callers release `WaitJob` waiters and timers immediately on memory/SQLite (PostgreSQL `waitForJobResult` is unchanged).
- **`CronScheduler` error backoff and exhausted schedules:** `persistCron` failures back off by 1,000 ms instead of spinning at 0 ms, and exhausted schedules (`nextRun <= 0`) stay out of `cronHeap`.
- **SQLite `getJobs` bounds and `busy_timeout`:** `getJobs` returns `[]` for `NaN`, `Infinity`, `end <= 0`, or `end <= start` (clamping negative `start` to `0`). `PRAGMA busy_timeout = 5000` now runs before schema checks.
- **PostgreSQL `removeChildDependency` and deferred failure cap:** `removeChildDependency` returns `false` unless the parent is in `'waiting-children'` (and emits `'updated'` on the child when removed). `PostgresDeferredWriteQueue` caps retained failures at 1,000.
- **Worker errors, `close()`, `AckBatcher`, and native batches:** Failed auto-ACKs and throwing `completed` listeners no longer `FAIL` finished jobs. They emit fresh `Error` objects (`cause` + `context: 'ack' | 'ack-stale' | 'completed-listener'`), logging via `console.error('[Worker] Processor error:', ...)` when no `'error'` listener is attached. `Worker.close()` stops emitting `ClientClosedError` from in-flight `Heartbeat`, `JobHeartbeat`, and `RegisterWorker` calls. `AckBatcher.queue()` rejects with `'AckBatcher stopped'` after `stop()`. Native batches cap at `min(batch.size, limiter.max)` and enforce `groupLimiter` across all candidates.
- **TLS unix-socket rollback:** A `chown` error during rollback logs `HTTP unix socket owner not restored after a TLS reload` and still restores `chmod`.
- **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

- **Cleaner `Worker.close()` shutdown:** Fire-and-forget `Heartbeat`, `JobHeartbeat`, and `RegisterWorker` calls cancelled during Worker pool teardown no longer trigger unhandled `ClientClosedError` events.
- **TLS unix-socket rollback mode fix:** Always restores the previous socket mode even when `chown` fails with an error other than `EPERM`.
- **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.json` `files` uses `!dist/benchmark/**` for `bun pm pack` parity, 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 hardened `machine-gate.sh` (retiring exit 3) landed in repository tooling.

## 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 (`53be601b` vs `6d7fd2e2`):** 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 for `getJobs`).
- **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!

- [@egeominotti](https://github.com/egeominotti)

---

[← bunqueue v2.9.22](https://bunqueue.dev/blog/bunqueue-v2-9-22/) · [Release on GitHub](https://github.com/egeominotti/bunqueue/releases/tag/v2.9.23) · [Commits since v2.9.22](https://github.com/egeominotti/bunqueue/compare/v2.9.22...v2.9.23) · [Full changelog](https://bunqueue.dev/changelog/) · [All posts](https://bunqueue.dev/blog/)
