What is async context tracking in Node.js?

Why Interviewers Ask This

Senior Node.js engineers are expected to reason about architecture, performance, and edge cases. This question separates mid-level from senior candidates by testing deep system-level understanding.

Answer

Async context tracking allows you to maintain contextual data (like a request ID, user info, or trace ID) across asynchronous boundaries without passing it as function parameters. In synchronous code, you could use a global variable, but async code jumps between different contexts. AsyncLocalStorage (introduced in Node.js 12.17 as a stable API) solves this: const { AsyncLocalStorage } = require("async_hooks"); const storage = new AsyncLocalStorage();. Start a context: storage.run({ requestId: uuid() }, () => { /* all async code here can access the store */ });. Access anywhere in the async chain: const ctx = storage.getStore(); ctx.requestId;. Common uses: (1) Request-scoped logging: automatically include request ID in every log line without thread-locals; (2) Distributed tracing: propagate trace context through async operations; (3) Per-request database transactions. AsyncLocalStorage replaced the older, lower-level async_hooks API which was complex and had significant performance overhead. Express.js example: in a middleware, create the store with storage.run({ requestId: req.id }, () => next()).

Pro Tip

If you're unsure about a detail, say so honestly and explain your reasoning. Interviewers respect candidates who can think through uncertainty rather than bluffing.