Skip to content
jshacks.dev
Async

Async Context: Carrying State Across await

Learn how AsyncLocalStorage carries request-scoped state across await and callbacks in Node.js 24, with request ids, logging and the pitfalls to avoid.

7 min read
Summarize in AI
Flat illustration of jobs on a conveyor heading to a rack of workers, with the Node.js, Redis, RabbitMQ and Apache Kafka logos.

In a synchronous program, a thread-local variable is a way to carry per-request state, such as a request id or the current user, without passing it through every function. JavaScript has no threads to hang that on, and a plain global is shared by every request that is in flight, so two requests overlapping through an await would trample each other's values. AsyncLocalStorage, from node:async_hooks, solves this: it stores a value that stays attached to the logical flow of execution, following promises, timers and callbacks wherever they go, and is invisible to unrelated flows. It is stable in Node.js and the standard behind request-scoped loggers and tracing libraries. This post shows how to use it on Node.js 24 with printed output, explains how the value follows an await, builds a request id logger, covers the pitfalls with callbacks that lose context and mentions the TC39 AsyncContext proposal that aims to standardize the idea.

The problem

JavaScript
let currentUser = null;

async function handle(user, delay) {
  currentUser = user;
  await new Promise((r) => setTimeout(r, delay));
  console.log(`handling ${user}, global says ${currentUser}`);
}

await Promise.all([handle("ada", 20), handle("linus", 5)]);
Text
handling linus, global says linus
handling ada, global says linus

Ada's request woke up after Linus's request had overwritten the global, so it believed the current user was Linus. This is the stale shared state described in the post on races. The fix without async context is to pass user as an argument through every function that needs it, which is correct and tedious, since logging helpers deep in the call tree would all need the extra parameter.

AsyncLocalStorage

run(store, callback) runs the callback with store attached. Anything the callback starts, including await continuations, timers and promise handlers, can read the store with getStore().

JavaScript
import { AsyncLocalStorage } from "node:async_hooks";

const context = new AsyncLocalStorage();

async function handle(user, delay) {
  await context.run({ user }, async () => {
    await new Promise((r) => setTimeout(r, delay));
    console.log(`handling ${user}, context says ${context.getStore().user}`);
  });
}

await Promise.all([handle("ada", 20), handle("linus", 5)]);
Text
handling linus, context says linus
handling ada, context says ada

Each call has its own store, and the values stayed correct across the wait. The store is not a global. It is attached to the asynchronous execution that run started, and Node.js tracks that attachment through promises and callbacks.

A request id logger

The standard use is to give every log line the id of the request that produced it, from any depth of the call tree.

JavaScript
import { AsyncLocalStorage } from "node:async_hooks";

const requestContext = new AsyncLocalStorage();

function log(message) {
  const id = requestContext.getStore()?.requestId ?? "no-request";
  console.log(`[${id}] ${message}`);
}

async function loadFromDatabase() {
  await new Promise((r) => setTimeout(r, 5));
  log("query finished");
}

async function handleRequest(requestId) {
  await requestContext.run({ requestId }, async () => {
    log("request started");
    await loadFromDatabase();
    log("request finished");
  });
}

await Promise.all([handleRequest("req-1"), handleRequest("req-2")]);
log("outside any request");
Text
[req-1] request started
[req-2] request started
[req-1] query finished
[req-2] query finished
[req-1] request finished
[req-2] request finished
[no-request] outside any request

loadFromDatabase and log never received the id as an argument, and yet each line shows the right one. In a web server, the middleware calls run once at the start of each request, and everything downstream benefits. Express and Fastify have middleware and plugins that do this, and tracing libraries such as OpenTelemetry use the same mechanism to attach a span to the current flow.

enterWith and exit

run scopes the store to a callback. enterWith(store) sets it for the remainder of the current synchronous execution and everything it starts, which is convenient in places where you cannot wrap code in a callback, and is easier to misuse because there is no clear end to the scope. exit(callback) runs a callback with no store, for code that should not inherit the context.

JavaScript
import { AsyncLocalStorage } from "node:async_hooks";

const als = new AsyncLocalStorage();

als.run("outer", () => {
  console.log("inside run:", als.getStore());

  als.exit(() => {
    console.log("inside exit:", als.getStore());
  });

  console.log("back in run:", als.getStore());
});

console.log("after run:", als.getStore());
Text
inside run: outer
inside exit: undefined
back in run: outer
after run: undefined

Prefer run. It makes the lifetime of the value visible in the code, and it is restored automatically.

Where it follows and where it does not

The store follows promises, async/await, setTimeout, setImmediate, process.nextTick, queueMicrotask, event emitter callbacks fired from within the flow, and I/O callbacks registered inside it.

JavaScript
import { AsyncLocalStorage } from "node:async_hooks";
import { readFile } from "node:fs";

const als = new AsyncLocalStorage();

als.run({ id: 7 }, () => {
  setTimeout(() => console.log("timer sees", als.getStore().id), 1);

  Promise.resolve().then(() => console.log("promise sees", als.getStore().id));

  readFile(process.argv[1], () => console.log("callback sees", als.getStore().id));
});
Text
promise sees 7
callback sees 7
timer sees 7

The order of the lines depends on I/O timing, and the point is that all three saw 7. It can fail to follow in a few cases, mostly with code that queues work in one flow and runs it in another.

Connection pools and queues. If a callback is registered in request A's flow and later triggered from a pool's internal code that runs in request B's flow, the callback may see B's context. Libraries that pool connections need to bind callbacks explicitly. AsyncResource.bind(fn) captures the current context and returns a function that restores it when called.

JavaScript
import { AsyncLocalStorage, AsyncResource } from "node:async_hooks";

const als = new AsyncLocalStorage();
const queue = [];

als.run("request A", () => {
  queue.push(AsyncResource.bind(() => console.log("bound sees:", als.getStore())));
  queue.push(() => console.log("unbound sees:", als.getStore()));
});

als.run("request B", () => {
  queue.forEach((job) => job());
});
Text
bound sees: request A
unbound sees: request B

The unbound callback ran in B's flow and saw B, which is the classic way for a library to leak one request's identity into another. A queue, a batch, a debounce or a cache that runs callbacks later from a shared place needs binding.

Thenables and old promise libraries. Context follows native promises. A custom thenable that calls its callbacks from an unrelated place may break the link.

Mutable stores

The store can be any value, including an object that you mutate to accumulate information during a request.

JavaScript
import { AsyncLocalStorage } from "node:async_hooks";

const als = new AsyncLocalStorage();

function addTiming(label) {
  als.getStore().timings.push(label);
}

await als.run({ timings: [] }, async () => {
  addTiming("auth");
  await new Promise((r) => setTimeout(r, 1));
  addTiming("db");
  console.log(als.getStore().timings);
});
Text
[ 'auth', 'db' ]

Since the store is one object shared by the whole flow, mutating it is visible everywhere in the flow, and invisible outside. That is useful for collecting metrics, error context or a per-request cache.

Cost and restraint

AsyncLocalStorage has a cost, since the runtime has to propagate the context through every asynchronous hop. Recent Node.js versions have optimized it considerably, and an application that uses it in the request path pays a small overhead per asynchronous operation, which is rarely the bottleneck. Use it for cross-cutting concerns such as request ids, tracing, locale and transactions, and not as a general substitute for function arguments. Business logic that needs a value should still receive it explicitly, since a hidden dependency on getStore() makes code harder to test and to read. A good test of restraint is whether the value would appear in the function's signature if the language had thread-locals. If the answer is no, because it is infrastructure, async context fits.

The standard direction

TC39 has a proposal called AsyncContext, with AsyncContext.Variable and AsyncContext.Snapshot, that standardizes this for browsers and servers alike, building on the experience of AsyncLocalStorage. It is at an early stage and not yet available without a polyfill. When it arrives, code written against AsyncLocalStorage will map across with small changes, so adopting the Node.js API now is a safe bet.

Using it with frameworks and tests

Most Node.js web frameworks give you one clear place to start the context, the earliest middleware or hook that wraps request handling. Start it there, put the minimum into the store, usually a request id and perhaps the authenticated user, and give the rest of the code small helper functions such as currentRequestId() instead of letting every module call getStore() and know the shape of the store. That keeps the dependency on async context in one file.

In tests, run the code under test inside als.run with a fake store, the same as the framework would. If you forget, getStore() returns undefined, and code that assumes a store will throw. Writing helpers that tolerate a missing store, as the logger above does with ?., makes functions usable from scripts, startup code and tests, where no request exists.

Also inNode.js
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.