QA
Intermediate LevelNode JS

How does AsyncLocalStorage track request-scoped context across asynchronous call chains?

❓ Interview Prompt: Explain `AsyncLocalStorage` from `node:async_hooks`, tracking request context (Trace IDs, User sessions) across async operations without parameter drilling.

'AsyncLocalStorage' (from 'node:async_hooks') creates asynchronous store contexts that persist across asynchronous call chains:

Primary Use Case:

Storing Request Trace IDs, tenant IDs, or authenticated user sessions at the HTTP entry point and accessing them anywhere deep inside services without threading arguments through every function!

Code Implementation Example

javascript
import { AsyncLocalStorage } from 'node:async_hooks';
import http from 'node:http';
import crypto from 'node:crypto';

const asyncLocalStorage = new AsyncLocalStorage();

function logWithTraceId(msg) {
  const store = asyncLocalStorage.getStore();
  const traceId = store ? store.get('traceId') : 'N/A';
  console.log('[TraceID: ${traceId}] ${msg}');
}

http.createServer((req, res) => {
  const store = new Map([['traceId', crypto.randomUUID()]]);
  asyncLocalStorage.run(store, () => {
    logWithTraceId('Processing HTTP request...');
    res.end('OK');
  });
}).listen(3000);
💡Tracking request Trace IDs using AsyncLocalStorage.
🎯 Interview Key Takeaway

Use AsyncLocalStorage to maintain request-scoped context like Trace IDs across async operations without parameter drilling.

#AsyncLocalStorage#async_hooks#Context Tracking#Intermediate
Back to all Node JS Questions→

More Node JS Interview Questions

Beginner LevelNode JS

How does the Node.js Event Loop work? Explain the 6 execution phases (Timers, Pending, Poll, Check, Close).

Beginner LevelNode JS

What does 'Single-Threaded, Event-Driven, Non-Blocking I/O' mean in Node.js?

Beginner LevelNode JS

What is the difference between process.nextTick() and setImmediate()?