[BUG] addTransactionCapability leaks one enabled AsyncLocalStorage per socket — heap cost grows with every socket ever created
Describe the bug
addTransactionCapability() (src/Utils/auth-utils.ts) does const txStorage = new AsyncLocalStorage<TransactionContext>(), and it is called once per socket from makeSocket (src/Socket/socket.ts). The first transaction() call runs txStorage.run(ctx, work), which enables the storage — and nothing in the codebase ever calls .disable() (grep count: 0, still true on master today).
Enabling an AsyncLocalStorage pushes it onto a module-global list inside node:async_hooks that holds a strong reference, and Node walks that entire list on every async resource creation, stamping one symbol-keyed property onto each new Timeout/Promise/etc. Only .disable() removes it. So every socket ever opened keeps charging rent on every object created afterwards, forever, and GC cannot reclaim it (verified with WeakRef: an enabled-and-never-disabled storage survives repeated forced GC; a disabled one is collected immediately).
The cost is live async resources × sockets ever created — quadratic in uptime. Single-session bots barely notice. Long-running multi-session servers get eaten alive: it idles fine for hours and then runs away, and a process restart always "fixes" it, which makes it very hard to attribute.
Production evidence (server hosting ~250 concurrent sockets, heap snapshot after 25h uptime, Node v22.22.2, Baileys 7.0.0-rc13):
- 2,130 MB heap; 89.5% (1,907 MB) sits in 49,302
(object properties)backing stores - Owners:
Timeout1,011.8 MB / 21,580 objects +Promise861.2 MB / 18,393 objects = 98% - Dictionary sizes are degenerate: p50 = p90 = p99 = max = 48.1 KB (fixed-capacity dictionaries, not organic growth)
- Exactly 1,818 unique symbol nodes exist (~40 KB total) — one per socket created over those 25h. The gigabytes are the property dictionaries holding them, not the symbols
- Mean ~912 symbols/object ≈ half of 1,818 — exactly what you expect when objects are born uniformly over time and inherit the ALS count at birth
- Arithmetic check: 21,580 × 912 × ~48 B ≈ 945 MB vs 1,011 MB observed ✓
Even after bounding it to concurrent sockets (see fix below), ~250 enabled storages still amplify every allocation burst: a single send fan-out creating tens of thousands of promises briefly costs ~1 GB of property dictionaries.
To Reproduce
No WhatsApp connection needed — the mechanism is pure Node:
const { AsyncLocalStorage } = require('async_hooks');
const stores = [];
for (let i = 0; i < 1000; i++) {
const s = new AsyncLocalStorage();
s.run({}, () => {}); // what txStorage.run() does on the first transaction()
stores.push(s); // Baileys keeps each socket's storage reachable and never disables it
}
const t = setTimeout(() => {}, 1000);
console.log(Object.getOwnPropertySymbols(t).length); // 1005 = 5 baseline + 1 per enabled ALS
clearTimeout(t);Measured on Node v22.22.2: 100 storages → 105 symbols, 600 → 605, 1600 → 1605, 3400 → 3405. With Baileys itself: create and end() sockets in a loop and watch Object.getOwnPropertySymbols(setTimeout(...)) grow by exactly 1 per socket ever created, never shrinking on end().
Expected behavior
sock.end() should release everything the socket allocated. The per-object symbol count should be bounded by concurrent sockets, not by sockets ever created.
Environment (please complete the following information):
- Baileys: 7.0.0-rc13 (bug still present on master)
- Node: v22.22.2, Linux
- Is this on a server? Yes, long-running multi-tenant service
- Multiple clients on same IP: yes, ~250 concurrent sockets (this is what makes the leak visible)
- Proxy: mixed (irrelevant to this bug)
Additional context
We've been running this fix in production for a week via patch-package. addTransactionCapability exposes a dispose method that socket.ts calls on end:
--- a/src/Utils/auth-utils.ts (addTransactionCapability return object)
+++ b/src/Utils/auth-utils.ts
},
+ disposeTransactionStorage: () => {
+ try {
+ txStorage.disable();
+ } catch (err) {
+ logger.warn({ err }, 'failed to disable transaction storage');
+ }
}
--- a/src/Socket/socket.ts (after registerSocketEndHandler is defined)
+++ b/src/Socket/socket.ts
+ registerSocketEndHandler(() => {
+ keys.disposeTransactionStorage?.();
+ });registerSocketEndHandler is the right hook: end() is idempotent, runs every handler in a try/catch loop unconditionally, and is reached from ws.on('close') — so it also fires for abnormal closes (code 1006), which is how most sockets die in practice. Verified against real Baileys code: 1000 sockets → 1005 symbols; disposing 750 of them → 255; all 1000 transactions still committed to their own store with zero cross-socket bleed, and a live socket still commits after the others are disposed.
Deliberately not the one-line alternative of hoisting txStorage to module scope: a single shared ALS could let getStore() return another socket's transaction context if one socket's key work ever runs inside another's async context, committing client B's key mutations into client A's store.
Side note for anyone hitting this today: the Node flag --experimental-async-context-frame (default behavior in Node ≥ 24) eliminates the per-resource symbol stamping entirely and is a valid stopgap, but the storage itself still leaks — the real fix is disabling it on teardown.
Happy to open a PR with the patch above if maintainers agree with the approach.
Source: WhiskeySockets/Baileys