Skip to the page

Errors, memory and request context · senior

AsyncLocalStorage: request context

AsyncLocalStorage keeps a value (like a request ID or the current user) available through every await, timer and callback that starts inside one request, without passing it as an argument.

The notes

What you must know

  • als.run(store, fn): inside fn and everything it schedules (promises, timers, I/O callbacks), als.getStore() returns that store; outside, it returns undefined.
  • Main uses: request-scoped logging (every log line gets the request ID) and tracing; OpenTelemetry and APM tools rely on it.
  • Each concurrent request gets its own store, even though all requests share one thread.
  • AsyncLocalStorage (node:async_hooks) is stable; the low-level createHook API is not recommended for apps.
  • Alternatives: pass a context object explicitly (simple and clear) or attach data to req (only reachable where req is).

The red pen

Common traps: mistake → fix

  • Mistake: A global variable can hold the current user

    Fix: requests interleave at every await, so another request overwrites it.

  • Mistake: AsyncLocalStorage is thread-local storage

    Fix: there is one thread; it follows async call chains.

Easy to hard

Questions interviewers ask, easy to hard

  1. How do you add a request ID to every log line without passing it everywhere?
  2. Why is a global 'currentUser' variable a bug in Node?
  3. How does tracing know which request a DB call belongs to?

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview