← Back to Node.js, page 5

nodejs-0091 · Medium mid

What is AsyncLocalStorage, and how do you use it to keep a request id available across async calls?

AsyncLocalStorage stores a value for the duration of an asynchronous operation chain. als.run(store, fn) makes the store available to fn and to everything it starts through promises, timers and callbacks, and als.getStore() reads it anywhere in that chain. It carries a request id or user without passing parameters through every function.

Full answer

Problem: a log line deep in the code should show the request id, but the id enters at the HTTP handler, and ten functions and several awaits lie between. Passing a context argument through every function is noisy. Global variables break, because concurrent requests overwrite each other.

AsyncLocalStorage (from node:async_hooks) solves this. It works like thread-local storage, but for asynchronous call chains:

const als = new AsyncLocalStorage(); als.run({ requestId: 'r1' }, () => { ... }); // everything started inside sees this store als.getStore(); // returns the store, or undefined outside a run

How it works: Node tracks which asynchronous resource (promise, timer, socket callback) was created while which store was active, and restores that store when the callback runs. So the store follows await, setTimeout, process.nextTick, fs callbacks and most I/O.

Typical uses: request ids and trace ids for logs, the current user or tenant, per-request database transactions, timing and metrics, feature flags per request.

Rules:

  • Call als.run at the entry point (middleware), once per request.
  • Each run gets its own store, so concurrent requests stay separate.
  • Store small objects. Mutating the store object is visible to everything inside the same run.
  • als.getStore() returns undefined outside a run, so code must handle that (for example in start-up code or tests).
  • Performance cost is small on current Node versions, but not zero. Do not use it for things you could pass as a plain argument in a small code base.

Frameworks use it internally for the same purpose, and OpenTelemetry context propagation is built on it.

javascript
const http = require('node:http');
const { AsyncLocalStorage } = require('node:async_hooks');

const context = new AsyncLocalStorage();
const logLines = [];

// A logger that needs no request argument.
function log(message) {
  const store = context.getStore();
  logLines.push(`[${store ? store.requestId : 'no request'}] ${message}`);
}

const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

async function loadMarks(studentId) {
  log('loading marks for ' + studentId);
  await wait(studentId === 1 ? 30 : 10); // the two requests finish in a different order
  log('marks loaded for ' + studentId);
  return 70 + studentId;
}

let counter = 0;
const server = http.createServer((req, res) => {
  const store = { requestId: 'req-' + ++counter };
  context.run(store, async () => {
    log('request started: ' + req.url);
    const studentId = Number(req.url.slice(1));
    const marks = await loadMarks(studentId);
    setTimeout(() => { log('response sent'); res.end(String(marks)); }, 5); // a timer keeps the store too
  });
});

server.listen(0, '127.0.0.1', async () => {
  const base = 'http://127.0.0.1:' + server.address().port;
  // Two overlapping requests.
  const [a, b] = await Promise.all([fetch(base + '/1'), fetch(base + '/2')]);
  console.log('responses:', await a.text(), await b.text());

  const byRequest = {};
  for (const line of logLines) {
    const id = line.slice(1, line.indexOf(']'));
    (byRequest[id] ||= []).push(line.slice(line.indexOf(']') + 2));
  }
  for (const id of Object.keys(byRequest).sort()) console.log(id, '->', byRequest[id].join(' | '));

  log('outside any request');
  console.log('last line:', logLines.at(-1));
  server.close();
});

Although the two requests overlap and finish in a different order, each keeps its own log lines because each has its own store. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): responses: 71 72 req-1 -> request started: /1 | loading marks for 1 | marks loaded for 1 | response sent req-2 -> request started: /2 | loading marks for 2 | marks loaded for 2 | response sent last line: [no request] outside any request

Key points

  • als.run(store, fn) sets the context. getStore() reads it.
  • The store follows promises, timers and callbacks.
  • Each request gets its own run.
  • getStore() is undefined outside a run.

Common mistakes

  • Using a module-level variable for the request id.
  • Calling getStore() in start-up code and assuming a value.
  • Forgetting that the store object is shared by reference inside one run.
  • Calling als.run in many nested places and creating confusing contexts.

Follow-ups

  • How do you add the request id to every log line automatically?
  • What is the performance cost?
  • How does OpenTelemetry use this mechanism?

Tips

  • Open with the problem: passing context through ten functions.
  • Say 'follows await, timers and callbacks'.
  • Mention one store per request.