InterviewHubPRO
Section Overview
Q35

Question 35 of 60

Part 3: Streams, Buffers & Core Modules (21 - 35)

58%
Node.js & Libuv•Part 3: Streams, Buffers & Core Modules (21 - 35)

`AsyncLocalStorage` and Distributed Request Tracing.

In Simple Words: Provides thread-local-style storage across asynchronous operations, allowing Trace IDs and user session context to be accessible anywhere in the codebase without passing them through every function parameter:

javascript
const { AsyncLocalStorage } = require('async_hooks');
const asyncLocalStorage = new AsyncLocalStorage();

// In Middleware:
app.use((req, res, next) => {
  const traceId = req.headers['x-trace-id'] || crypto.randomUUID();
  asyncLocalStorage.run({ traceId }, () => next());
});

// Deep inside a repository without passing req:
function logQuery(sql) {
  const store = asyncLocalStorage.getStore();
  console.log(`[${store?.traceId}] SQL: ${sql}`);
}