Trending

World technology news

→
Keep concurrent request logs separate with Node.js AsyncLocalStorage
Software Engineering · 2026
Software Engineering

Keep concurrent request logs separate with Node.js AsyncLocalStorage

Attach the right request ID to every log line in a concurrent Node.js service. Use deterministic tests to verify context isolation, failure handling, and the boundary between processes.

Developer's JournalPublished: Nov 28, 20266 min read
Reading progress0%
In this article
  1. How a correct timeline can name the wrong request
  2. Open one scope at the incoming request boundary
  3. Control the finish order in a reproducible test
  4. Give background work its own context
  5. Propagate trace information at the service boundary
  6. Verify the schema and error records before rollout

How a correct timeline can name the wrong request

Imagine an order dashboard receiving two requests in quick succession. The first request waits for an inventory lookup while the second serves a cached response. If the final line from the first lookup names the second request, the timestamps still look plausible. An engineer following that log can assign a failure to the wrong request. JavaScript’s single main execution thread does not prevent this. Once a handler yields at await, another handler can change a temporary variable at module scope before the first operation resumes. Allocate a small context for each request and include a generated correlation ID. The logger can obtain that context where it writes the event, which avoids plumbing a correlation ID through functions that do no logging themselves. Pass application inputs explicitly. A product ID belongs in the inventory function’s parameters because it determines the result and should be visible in tests. The request identifier supports observability, and it can follow a different path.

Open one scope at the incoming request boundary

Create one AsyncLocalStorage instance for this logging context. At the HTTP entry point allocate a fresh object and call run(store, callback) to start the handler. While working inside that scope, and in compatible asynchronous work started there, use getStore() to read the object. A logger invoked outside any active request can emit null for the ID. That keeps a stable record shape when the same writer also records startup messages or maintenance work. Keep the object small. An access token, session cookie, or entire request object does not belong in this logging context. The example uses Object.freeze to guard one identifier against accidental edits. Freezing an object is shallow, so prefer a flat store with simple values if the context grows. Allocate a new store on each entry. Reusing a mutable object for several requests would reintroduce the very state sharing this pattern is meant to prevent.

Service architectureConceptual sketch · summary of the article's technical flow

Control the finish order in a reproducible test

Save the code as request-context.test.mjs and run node --test request-context.test.mjs with Node.js 24. The first test keeps one promise pending under test control. Request req-01 starts and waits. Request req-02 starts and finishes while the first is still pending. A log written outside shows no request ID. Releasing the first promise then lets the last line recover req-01. The test uses an explicit release function so no measured delay decides the order. On a slow machine the same five records still occur. The second test triggers an inventory failure, asserts the same error reaches the caller and checks which request was associated with the event. It then records another event outside the request. Both tests run without a network or a third-party package. They prove that the logger associates events with the correct request at the point of recording. A production log collector can still deliver lines asynchronously.

import assert from 'node:assert/strict';
import { AsyncLocalStorage } from 'node:async_hooks';
import { test } from 'node:test';

function createHarness() {
  const context = new AsyncLocalStorage();
  const records = [];

  function write(event) {
    records.push([event, context.getStore()?.requestId ?? null]);
  }

  function handle(requestId, load) {
    return context.run(Object.freeze({ requestId }), async () => {
      write('started');
      try {
        await load();
        write('finished');
      } catch (error) {
        write('failed');
        throw error;
      }
    });
  }

  return { records, write, handle };
}

test('overlapping requests retain separate IDs', async () => {
  const app = createHarness();
  let release;
  const slow = new Promise(resolve => { release = resolve; });

  const first = app.handle('req-01', () => slow);
  await app.handle('req-02', async () => { await Promise.resolve(); });
  app.write('outside');
  release();
  await first;

  assert.deepEqual(app.records, [
    ['started', 'req-01'],
    ['started', 'req-02'],
    ['finished', 'req-02'],
    ['outside', null],
    ['finished', 'req-01'],
  ]);
});

test('failed work keeps its own ID and leaves no caller context', async () => {
  const app = createHarness();
  const failure = new Error('inventory unavailable');

  await assert.rejects(app.handle('req-03', async () => { throw failure; }),
    error => error === failure);
  app.write('outside');

  assert.deepEqual(app.records, [
    ['started', 'req-03'],
    ['failed', 'req-03'],
    ['outside', null],
  ]);
});

Give background work its own context

A timer or promise created inside a request scope can still have that context after the response has gone out. Calling run() does not cancel asynchronous work. Jobs that continue after the response need their own delivery and error handling. An order confirmation sent through a queue can carry a narrow correlation field in the message. When the consumer receives it, start a fresh scope with the job ID and add the original correlation ID as a separate field when it is needed. If you find a line with missing context, log the store inside the scope and again inside the suspected callback adapter. A native Promise adapter may resolve the issue. Node.js also documents AsyncResource for integrations that need to describe an asynchronous resource and its lifecycle. Test the specific boundary where the context disappears. Keep a stable event type for records with no ID so normal maintenance events remain distinguishable from context loss.

Propagate trace information at the service boundary

A local store does not travel automatically across an HTTP call, a queue message, or a worker thread. When multiple services participate in one trace, use the instrumentation layer to generate and parse the W3C Trace Context traceparent header. Give the distributed trace ID a separate field from the request ID generated at your service. That lets an operator find one incoming request or follow the broader trace through upstream and downstream calls. Generate the local request ID at the service boundary. A public client can supply any string in a header, so do not log its header verbatim as your own ID. If an outside correlation field is operationally useful, validate its shape and size and keep it separate. Avoid bulk logging request bodies, credentials, and headers. Budget for retention and volume independently of the decision to propagate a trace. The fields that make a request searchable should be deliberate.

Verify the schema and error records before rollout

Agree on the meaning of requestId, event, route, and durationMs with the people who query these logs. Use a route template instead of a URL containing customer or order identifiers. Define what each duration measures. For instance, HTTP duration can run until response completion and the inventory timer can represent just the call to that dependency. Keep high-cardinality request IDs in logs and traces. Adding them as metric labels can produce a separate time series for each ID. For a rollout check, run two overlapping requests, exercise a known failure and collect a record issued outside the HTTP path. Match start and finish events by request ID on the running server. Filter out known background events when monitoring missing IDs in the HTTP log. Re-run the context test after changing an adapter that schedules callbacks. The evidence that matters during an incident is which operation failed and which request it affected.

Be the first reader ✎ Write a comment

Reader discussion

Discussion prompt

What would you change first for maintainability and testing in your own project?

No comments yet. Be the first to contribute.

Write a comment

Comments are real visitor contributions. Repeated, link-heavy or abusive submissions may be limited.