← Back to Node.js, page 5

nodejs-0092 · Hard senior

When does AsyncLocalStorage lose context, and how do AsyncResource, bind and snapshot fix it?

Context follows the asynchronous resource that was created inside run(). It is lost or wrong when work is queued and executed later by shared code (a connection pool, a job queue, an event emitter listener registered elsewhere). Capture the context when you queue the work with AsyncLocalStorage.bind, AsyncResource.bind or AsyncLocalStorage.snapshot, and restore it when the work runs.

Full answer

AsyncLocalStorage attaches the store to async resources as they are created. That works for promises, timers and most I/O. Problems appear when the code that runs a callback is not in the same context as the code that scheduled it.

Typical cases:

  1. EventEmitter listeners. A listener runs in the context of the code that calls emit(), not the code that called on(). A listener added during request A but triggered during request B sees B's store.
  2. Pools and queues. A connection pool or job queue starts its worker loop once, in some context. Callbacks queued later by many requests run in the loop's context (often none), and the request's store is gone.
  3. Callback APIs of libraries that keep their own queue of callbacks and call them later.
  4. als.enterWith(store): sets the store for the rest of the current execution without a run() scope. It is easy to leak into unrelated code, so prefer run().

Fixes:

  • AsyncLocalStorage.bind(fn): returns a function that always runs in the context captured when bind was called.
  • AsyncLocalStorage.snapshot(): captures all active contexts and returns a runner (runInAsyncScope style) function. Good for queues: take the snapshot when enqueuing, call snapshot(fn) when executing.
  • AsyncResource: new AsyncResource('JobQueue') captures the current context, and resource.runInAsyncScope(fn) or AsyncResource.bind(fn) runs inside it. This is what library authors use.
  • als.exit(fn) runs fn with no store, useful for background work that should not inherit the request.

Design advice: capture context at the boundary where work leaves the request (enqueue, add listener), not inside the library. Test with two overlapping requests, as one request alone hides most problems.

javascript
const { AsyncLocalStorage, AsyncResource } = require('node:async_hooks');
const { EventEmitter } = require('node:events');

const als = new AsyncLocalStorage();
const who = () => als.getStore()?.user ?? 'nobody';

// 1. EventEmitter: the listener sees the context of emit(), not of on().
const events = new EventEmitter();
als.run({ user: 'Asha' }, () => {
  events.on('result', () => console.log('1. plain listener sees:', who()));
  events.on('result', AsyncLocalStorage.bind(() => console.log('1. bound listener sees:', who())));
});
als.run({ user: 'Ravi' }, () => events.emit('result')); // triggered in Ravi's request

// 2. exit(): run without the store
als.run({ user: 'Zoya' }, () => {
  console.log('2. before exit:', who());
  als.exit(() => console.log('2. inside exit:', who()));
});

// 3. A shared queue that runs jobs later, from its own loop.
const queue = [];
const enqueue = (job) => queue.push(job);
als.run({ user: 'Meera' }, () => {
  enqueue(() => console.log('3. job without capture sees:', who()));
  enqueue(AsyncLocalStorage.bind(() => console.log('3. job with bind sees:   ', who())));
  const snapshot = AsyncLocalStorage.snapshot();
  enqueue(() => snapshot(() => console.log('3. job with snapshot sees:', who())));
});
setImmediate(() => { while (queue.length) queue.shift()(); }); // the queue loop starts outside any request

// 4. AsyncResource: capture once, run many times.
let resource;
als.run({ user: 'Kabir' }, () => { resource = new AsyncResource('ReportJob'); });
setTimeout(() => {
  console.log('4. outside:', who());
  resource.runInAsyncScope(() => console.log('4. inside the captured resource:', who()));
}, 10);

The plain listener and the plain job show the wrong or missing user. The bound versions restore the context captured when the work was queued. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): 1. plain listener sees: Ravi 1. bound listener sees: Asha 2. before exit: Zoya 2. inside exit: nobody 3. job without capture sees: nobody 3. job with bind sees: Meera 3. job with snapshot sees: Meera 4. outside: nobody 4. inside the captured resource: Kabir

Key points

  • Context follows creation, not execution, for async resources.
  • emit() runs listeners in the emitter's calling context.
  • Queues and pools need the context captured when work is added.
  • Use bind, snapshot or AsyncResource to restore it.
  • Prefer run() over enterWith().

Common mistakes

  • Assuming a listener runs in the context where it was registered.
  • Using enterWith() in a shared function.
  • Testing with only one request at a time.
  • Capturing context inside the queue library instead of at the call site.

Follow-ups

  • How does als.run differ from enterWith?
  • How would you propagate the context into a worker thread?
  • What does a library need to do to support ALS in its pool?

Tips

  • Say 'creation context, not execution context'.
  • Offer the three fixes and when each fits.
  • Mention testing with overlapping requests.