Two engineers compare terminal logs with a wall display showing request A starting and the second listener reading MUTATED.

One Node.js Event, Two Listeners: Why Did the Request ID Change?

Sat, Nov 21, 2026

When a callback calls getStore(), does the store belong to the request whose work the callback is doing? A shared event emitter makes that question concrete. If one listener enters a different store, the next listener can read a plausible request ID even though the original request is still being handled.

The Node.js documentation for AsyncLocalStorage distinguishes two ways of setting a store. run() makes the store available to its callback and to asynchronous operations created within that callback. It restores the previous context when the callback returns. enterWith() changes the context for the rest of the current synchronous execution and propagates it to subsequent asynchronous work. Because EventEmitter calls listeners synchronously in registration order, a call to enterWith() inside one listener can affect the next. Node recommends preferring run() unless there is a strong reason to use enterWith().

The fixture pins Node.js v24.22.2 LTS, released October 28, 2026. Node 26 was also listed as an LTS release when the fixture was specified. The version pin identifies the runtime whose behavior the expectations describe.

Executive Summary

All nine cases are EXPECTED / NOT EXECUTED. No store value, timing observation, hash, exit status, or test result has been recorded. The distinction matters at each stage of the investigation.

Evidence class

Meaning

Documented semantics

Statements directly supported by version-pinned Node.js documentation

Independent oracle

Expected store identities written before execution

Observation

Values actually captured by a future fixture execution

Operational inference

ACCEPT / REPAIR / RERUN / HOLD after reconciling observation against the oracle

A test can pass while the application’s request-isolation contract fails. Suppose the first listener calls enterWith({requestId: "MUTATED"}). If the second listener reads "MUTATED", an assertion that checks Node’s documented behavior should pass. The application, however, requires the second listener to see request A. The Node.js test runner reports whether a test completed successfully, including whether its promise fulfilled. Only the comparison with the independently known request ID can establish who owns the work.

A zero exit status is necessary when all assertions are expected to pass. ACCEPT also requires a matching runtime and fixture, complete case coverage, one record per case, and the expected order and request identities. Choose RERUN for an attempted run with missing or corrupt evidence. A reproducible isolation violation with a known repair calls for REPAIR. HOLD applies when there is no execution evidence or a valid run contradicts the pinned behavior without explanation.

Source Baseline and Version Boundary

In v24.22.2, getStore() returns the current store. Outside a context established by run() or enterWith(), it returns undefined. Calling run(store, callback) enters the context synchronously. Asynchronous work created inside the callback retains access to its store even after the caller has resumed in the surrounding context.

Node v24.22.2 marks enterWith() as Stability 1 (Experimental). In Node’s example, one handler calls enterWith(store) and another handler sees the same store later in the same emit(). A single synchronous dispatch is enough to expose an ownership error. No asynchronous race is required.

Compare the point where a listener is registered with the point where it is invoked. A listener registered under request A can later be invoked outside any request scope. Conversely, a listener registered outside a request can be invoked while request A emits. The expected values for these two cases follow from the scope of run() and the synchronous behavior of emit(). In Python, request ID capture with asyncio.create_task illustrates why it is worth identifying exactly which operation associates work with its context.

For a callback that unexpectedly loses context, Node’s “Troubleshooting: Context loss” guidance suggests logging getStore() after suspected calls to locate the first change. For callback-based APIs, Node recommends promisification where appropriate. A custom callback API or thenable may require AsyncResource to associate the callback with its intended execution context. The fixture tests a narrower case: a plain function created outside a request and invoked within run(). A similar timing question arises with context capture in Python’s asyncio.to_thread, where constructing the coroutine, scheduling it, copying the context, and invoking the work are distinct events.

The Node.js async_hooks documentation describes an asynchronous resource as an object associated with a callback that can execute once or many times. Node strongly discourages direct use of createHook, AsyncHook, and executionAsyncResource for ordinary context tracking and directs that work toward AsyncLocalStorage. For these cases, the evidence is the value returned by getStore() alongside a request identity established independently of that store.

A synchronous test fails when it throws. A promise-returning test fails when the promise rejects. The built-in runner is stable. Its test-file process isolation model, also documented in v24.15.0, can run matching files in child processes and use the child’s exit status to determine file success. The v24.22.2 fixture uses one test file, --test-concurrency=1, and a fresh AsyncLocalStorage instance per case. Those choices make ordering and cross-test state easier to inspect.

The commands assume Linux x86-64, Bash, curl, tar, grep, and sha256sum. Only the official Node distribution and its checksum file require network access. The fixture uses synthetic request IDs in a single test-file process and has no external npm dependencies. It uses no production traffic, credentials, services, queues, databases, or HTTP servers. Worker threads and third-party middleware are outside its scope. Node describes the supplied value as a store and makes no deep-copy promise. The shared-reference case tests the application’s assumptions about ownership.

In case C05, request A emits an event. The first listener changes the active store before the second listener calls getStore().

img-eventmitter

Every event value in the diagram is EXPECTED / NOT EXECUTED. Node documents the scope rules and listener order. The request IDs and the requirement that the second listener still see A belong to the fixture.

Disposable Fixture, Independent Manifest, and Controlled Cases

Each case uses a fresh AsyncLocalStorage instance. Cases that need listeners share an EventEmitter within that case. Each test writes its own JSON evidence file. A fresh working directory keeps records from different runs separate.

Create a new temporary directory in Bash. Keep this shell open so that WORKDIR continues to name the same directory.

set -euo pipefail

WORKDIR="$(mktemp -d "${TMPDIR:-/tmp}/als-request-isolation.XXXXXX")"
cd "$WORKDIR"

Expected-case manifest

Write the manifest before execution. Its expectedObservation field predicts what Node v24.22.2 will expose. Its contractSatisfied field records whether that prediction satisfies the application’s request-isolation policy. C05 and C07 deliberately predict behavior that violates that policy.

Save this file as manifest.json in the temporary directory.

{
  "fixture": "als-request-isolation-v1",
  "node": "v24.22.2",
  "status": "EXPECTED / NOT EXECUTED",
  "cases": {
    "C01": {
      "name": "run establishes isolated request stores across concurrent work",
      "expectedObservation": {
        "A": ["A", "A"],
        "B": ["B", "B"]
      },
      "contractSatisfied": true
    },
    "C02": {
      "name": "enterWith persists through synchronous execution and created async work",
      "expectedObservation": {
        "sync": "E",
        "async": "E"
      },
      "contractSatisfied": true
    },
    "C03": {
      "name": "shared emitter listener observes invocation request context",
      "expectedObservation": [
        {"payload": "A", "store": "A"},
        {"payload": "B", "store": "B"}
      ],
      "contractSatisfied": true
    },
    "C04": {
      "name": "negative control: listener registration under A does not by itself bind later invocation",
      "expectedObservation": {
        "outsideEmitStore": null
      },
      "contractSatisfied": true
    },
    "C05": {
      "name": "enterWith in first listener contaminates later synchronous listener",
      "expectedObservation": {
        "secondListener": "MUTATED"
      },
      "contractSatisfied": false
    },
    "C06": {
      "name": "callback created outside context observes invocation scope",
      "expectedObservation": {
        "direct": "A",
        "setImmediate": "A"
      },
      "contractSatisfied": true
    },
    "C07": {
      "name": "two run scopes given the same mutable store share the same object reference",
      "expectedObservation": {
        "before": "base",
        "afterOtherScopeMutation": "changed-by-B"
      },
      "contractSatisfied": false
    },
    "C08": {
      "name": "rejected async operation does not leave request store active in caller",
      "expectedObservation": {
        "insideBeforeReject": "R",
        "outsideAfterReject": null
      },
      "contractSatisfied": true
    },
    "C09": {
      "name": "repair comparison: listener-local run scope restores original request for later listener",
      "expectedObservation": {
        "scopedListener": "LOCAL",
        "laterListener": "A"
      },
      "contractSatisfied": true
    }
  }
}

All nine entries are EXPECTED / NOT EXECUTED. C01 is the positive control for ordinary run() isolation. C04 is the negative control. If the listener reports A when it fires outside any request, the fixture cannot distinguish registration from invocation as intended. C05 preserves the original failure case. C09 provides the controlled comparison by using a listener-local run() scope.

Request-isolation tests

Save the following test file as fixture.test.mjs alongside manifest.json.

import test from 'node:test';
import assert from 'node:assert/strict';
import { AsyncLocalStorage } from 'node:async_hooks';
import { EventEmitter } from 'node:events';
import {
  mkdirSync,
  readFileSync,
  writeFileSync
} from 'node:fs';
import { setImmediate as immediate } from 'node:timers/promises';

const manifest = JSON.parse(readFileSync('./manifest.json', 'utf8'));
const evidenceDir = './evidence';
mkdirSync(evidenceDir, { recursive: true });

function rid(als) {
  return als.getStore()?.requestId ?? null;
}

function persist(caseId, actual) {
  const record = {
    fixture: manifest.fixture,
    caseId,
    node: process.version,
    observedAt: new Date().toISOString(),
    actual
  };

  writeFileSync(
    ${evidenceDir}/${caseId}.json,
    JSON.stringify(record, null, 2) + '\n',
    'utf8'
  );
}

function expected(caseId) {
  return manifest.cases[caseId].expectedObservation;
}

test('C01 run isolates concurrent request stores', async () => {
  const als = new AsyncLocalStorage();
  const actual = { A: [], B: [] };

  async function request(id) {
    return als.run({ requestId: id }, async () => {
      actual[id].push(rid(als));
      await immediate();
      actual[id].push(rid(als));
    });
  }

  await Promise.all([request('A'), request('B')]);

  persist('C01', actual);
  assert.deepEqual(actual, expected('C01'));
  assert.equal(als.getStore(), undefined);
});

test('C02 enterWith persists synchronously and into created async work', async () => {
  const als = new AsyncLocalStorage();

  als.enterWith({ requestId: 'E' });
  const actual = { sync: rid(als), async: null };

  await new Promise((resolve) => {
    setImmediate(() => {
      actual.async = rid(als);
      resolve();
    });
  });

  persist('C02', actual);
  assert.deepEqual(actual, expected('C02'));
});

test('C03 shared emitter follows invocation request context', async () => {
  const als = new AsyncLocalStorage();
  const emitter = new EventEmitter();
  const actual = [];

  emitter.on('work', (payload) => {
    actual.push({ payload, store: rid(als) });
  });

  async function request(id) {
    await als.run({ requestId: id }, async () => {
      await immediate();
      emitter.emit('work', id);
    });
  }

  await request('A');
  await request('B');

  persist('C03', actual);
  assert.deepEqual(actual, expected('C03'));
});

test('C04 negative control: registration is not treated as context binding', () => {
  const als = new AsyncLocalStorage();
  const emitter = new EventEmitter();
  let outsideEmitStore = 'UNSET';

  als.run({ requestId: 'A' }, () => {
    emitter.on('work', () => {
      outsideEmitStore = rid(als);
    });
  });

  emitter.emit('work');

  const actual = { outsideEmitStore };
  persist('C04', actual);
  assert.deepEqual(actual, expected('C04'));
});

test('C05 enterWith contaminates later synchronous listener', () => {
  const als = new AsyncLocalStorage();
  const emitter = new EventEmitter();
  let secondListener = null;

  emitter.on('work', () => {
    als.enterWith({ requestId: 'MUTATED' });
  });

  emitter.on('work', () => {
    secondListener = rid(als);
  });

  als.run({ requestId: 'A' }, () => {
    emitter.emit('work');
  });

  const actual = { secondListener };
  persist('C05', actual);
  assert.deepEqual(actual, expected('C05'));
});

test('C06 callback created outside context reads invocation context', async () => {
  const als = new AsyncLocalStorage();
  const callback = () => rid(als);

  const direct = als.run(
    { requestId: 'A' },
    () => callback()
  );

  let setImmediateValue = null;

  await als.run({ requestId: 'A' }, async () => {
    await new Promise((resolve) => {
      setImmediate(() => {
        setImmediateValue = callback();
        resolve();
      });
    });
  });

  const actual = {
    direct,
    setImmediate: setImmediateValue
  };

  persist('C06', actual);
  assert.deepEqual(actual, expected('C06'));
});

test('C07 shared mutable store reference is visible across scopes', async () => {
  const als = new AsyncLocalStorage();
  const shared = {
    requestId: 'SHARED',
    marker: 'base'
  };

  let release;
  const changed = new Promise((resolve) => {
    release = resolve;
  });

  const actual = {
    before: null,
    afterOtherScopeMutation: null
  };

  const a = als.run(shared, async () => {
    actual.before = als.getStore().marker;
    await changed;
    actual.afterOtherScopeMutation = als.getStore().marker;
  });

  const b = als.run(shared, async () => {
    als.getStore().marker = 'changed-by-B';
    release();
  });

  await Promise.all([a, b]);

  persist('C07', actual);
  assert.deepEqual(actual, expected('C07'));
});

test('C08 rejected async operation leaves caller outside request store', async () => {
  const als = new AsyncLocalStorage();
  let insideBeforeReject = null;

  await assert.rejects(
    als.run({ requestId: 'R' }, async () => {
      await immediate();
      insideBeforeReject = rid(als);
      throw new Error('synthetic rejection');
    }),
    /synthetic rejection/
  );

  const actual = {
    insideBeforeReject,
    outsideAfterReject: rid(als)
  };

  persist('C08', actual);
  assert.deepEqual(actual, expected('C08'));
});

test('C09 run scopes listener-local context and restores request A', () => {
  const als = new AsyncLocalStorage();
  const emitter = new EventEmitter();

  let scopedListener = null;
  let laterListener = null;

  emitter.on('work', () => {
    als.run({ requestId: 'LOCAL' }, () => {
      scopedListener = rid(als);
    });
  });

  emitter.on('work', () => {
    laterListener = rid(als);
  });

  als.run({ requestId: 'A' }, () => {
    emitter.emit('work');
  });

  const actual = {
    scopedListener,
    laterListener
  };

  persist('C09', actual);
  assert.deepEqual(actual, expected('C09'));
});

All test results remain EXPECTED / NOT EXECUTED.

Capture the runtime, test output, and exit status

Run the following commands in the same Bash session, from the temporary directory containing both files. The commands fetch the official Linux x64 binary and published checksums for v24.22.2, record the runtime and fixture hashes, and capture the test output and exit status.

release_host=nodejs.org
release_url="https://${release_host}/dist/v24.22.2"
curl -fsSLO "$release_url/node-v24.22.2-linux-x64.tar.xz"
curl -fsSLO "$release_url/SHASUMS256.txt"

grep ' node-v24.22.2-linux-x64.tar.xz$' SHASUMS256.txt \
  | sha256sum -c -

tar -xf node-v24.22.2-linux-x64.tar.xz

NODE="$WORKDIR/node-v24.22.2-linux-x64/bin/node"

"$NODE" --version
"$NODE" -p 'JSON.stringify({
  version: process.version,
  platform: process.platform,
  arch: process.arch,
  versions: process.versions
}, null, 2)' > runtime.json

sha256sum manifest.json fixture.test.mjs > fixture.sha256

mkdir -p evidence

set +e
"$NODE" --test --test-concurrency=1 --test-reporter=tap fixture.test.mjs \
  2>&1 | tee evidence/test.tap
TEST_STATUS=${PIPESTATUS[0]}
set -e

printf '%s\n' "$TEST_STATUS" > evidence/exit-status.txt

printf 'Evidence files:\n'
find evidence -maxdepth 1 -type f -print | sort

printf 'Fixture hashes:\n'
cat fixture.sha256

printf 'Recorded exit status: %s\n' "$TEST_STATUS"

Evidence Ledger, Reconciliation, Recovery, and Decision Gate

Create the case ledger before execution. Record observations alongside the original expectations so that differences remain visible. All nine cases below are EXPECTED / NOT EXECUTED.

Case

Purpose

Independent expected state

Observed state

Evidence status

Contract implication

C01

run() request isolation

A → A/A, B → B/B

NOT EXECUTED

EXPECTED / NOT EXECUTED

Candidate ACCEPT

C02

enterWith() persistence

sync E, async E

NOT EXECUTED

EXPECTED / NOT EXECUTED

Boundary evidence

C03

Shared emitter invocation

payload A → store A, B → B

NOT EXECUTED

EXPECTED / NOT EXECUTED

Candidate ACCEPT

C04

Registration negative control

emit outside → null

NOT EXECUTED

EXPECTED / NOT EXECUTED

Fixture validity

C05

enterWith() listener contamination

later listener → MUTATED

NOT EXECUTED

EXPECTED / NOT EXECUTED

REPAIR if observed

C06

Outside-created callback

direct A, scheduled A

NOT EXECUTED

EXPECTED / NOT EXECUTED

Callback-boundary evidence

C07

Shared mutable store

base → changed-by-B

NOT EXECUTED

EXPECTED / NOT EXECUTED

REPAIR if isolation required

C08

Rejected async cleanup

inside R, outside null

NOT EXECUTED

EXPECTED / NOT EXECUTED

Recovery evidence

C09

Scoped listener repair

LOCAL then A

NOT EXECUTED

EXPECTED / NOT EXECUTED

Repair comparison

C05 and C07 can pass their assertions even when the application’s request-isolation contract fails. Each assertion asks whether the runtime behaved as predicted. In C05, the expected value for the second listener is "MUTATED". Observing that value would let the assertion pass while showing that the listener lost request A. The Node test runner reports thrown assertions and rejected promises. The application has to decide which request should own the work. A similar distinction arises when checking which items a Python asyncio.Queue worker processed after join() returns.

To reconcile a store with a request, establish the request identity independently of getStore(). In C03, the payload passed to emit("work", "A") identifies request A. In C05 and C09, the enclosing run({ requestId: "A" }) identifies it. The manifest specifies which store each listener is expected to see. In a production system, the authoritative identity could come from another layer. This fixture covers only the synthetic inputs. The same identity check matters when recovering the row ID after PostgreSQL ON CONFLICT DO NOTHING completes.

A complete run should produce C01.json through C09.json exactly once, along with runtime.json, fixture.sha256, test.tap, and exit-status.txt. If the test file aborts after C04, the four existing JSON records cover only C01 through C04. A later run that reuses the directory could mix those records with files from a different execution. Use a fresh temporary directory for each run and preserve one immutable evidence bundle after completion. Checking every case ID against the manifest follows the same principle as reconciling source-row identities in a pandas GroupBy when a plausible aggregate can hide missing rows.

Save the following as verify-evidence.mjs. It checks which case files are present, the case ID in each file, and the recorded Node version.

// verify-evidence.mjs
import assert from 'node:assert/strict';
import { readdirSync, readFileSync } from 'node:fs';

const manifest = JSON.parse(readFileSync('./manifest.json', 'utf8'));
const expectedCases = Object.keys(manifest.cases).sort();

const observedCases = readdirSync('./evidence')
  .filter((name) => /^C\d\d\.json$/.test(name))
  .map((name) => name.slice(0, -5))
  .sort();

assert.deepEqual(
  observedCases,
  expectedCases,
  'missing or duplicate case evidence'
);

for (const caseId of expectedCases) {
  const record = JSON.parse(
    readFileSync./evidence/${caseId}.json, 'utf8')
  );

  assert.equal(record.caseId, caseId);
  assert.equal(record.node, manifest.node);
}

console.log('evidence-shape-valid');

Run the verifier from the same directory with the pinned Node binary.

"$NODE" verify-evidence.mjs

The verifier is also EXPECTED / NOT EXECUTED. A successful check would establish that the expected case files exist and report the pinned Node version. A file overwritten under the same name would be indistinguishable from one written once. C05 and C07 still require a separate decision about the application contract.

After verifying the evidence, copy the manifest, fixture, runtime record, hashes, and evidence directory to the location where you will review them. Then remove only the temporary directory created for this run.

cd /
rm -rf "$WORKDIR"

Recovery procedure

Use the following recovery procedure when a run is incomplete or a request identity differs from the application’s requirement.

  1. Preserve the original manifest, fixture hashes, runtime record, TAP stream, case JSON, and exit status before changing code.

  2. If the runtime or fixture hash differs from the pinned value, classify the attempt as RERUN. Repeat it with the intended runtime and fixture before interpreting any difference in behavior.

  3. If C04 differs from the negative control’s prediction, place the decision on HOLD. The fixture may be binding context at a point its design did not intend.

  4. If C05 shows that the first listener changed the second listener’s store while C03 still follows the invocation context, apply the C09 repair. Scope the listener’s local work with run() so the next listener can see the original request.

  5. If C07 shows shared-reference mutation, repair store ownership. Give each request its own state so that two scopes cannot change the same mutable request object.

  6. Rerun the entire fixture. C01, C03, C04, C06, and C08 check request identity, callback invocation, the validity of the negative control, and cleanup after rejection.

  7. Roll back the repair if C09 changes unrelated cases or the new evidence cannot be reconciled with the frozen manifest. If an expectation changes, create a new manifest revision and retain the original.

Repair listener scope and store ownership

For C05, the only code that needs a new store is the work inside the first listener.

// Risky for a shared synchronous emitter:
emitter.on('work', () => {
  als.enterWith({ requestId: 'LOCAL' });
  doLocalWork();
});

// Bounded alternative:
emitter.on('work', () => {
  als.run({ requestId: 'LOCAL' }, () => {
    doLocalWork();
  });
});

In the second example, run() scopes the supplied store to its callback and to asynchronous operations created there. When the callback returns, the next synchronous listener can see the enclosing request’s store. With enterWith(), the entered store persists through the rest of the synchronous execution. This repair applies to the shared-emitter request-isolation contract exercised by C05.

Both scopes in C07 already use run(). They see the same mutation because they receive the same object. Allocate a store for each request.

function requestStore(requestId) {
  return Object.freeze({ requestId });
}

als.run(requestStore('A'), handleA);
als.run(requestStore('B'), handleB);

Freezing the store is an application choice. If an application needs mutable state, give each request its own mutable object. A change made for request B must leave request A’s identity intact.

Node documents how run() scopes a store, how enterWith() persists, the order in which EventEmitter invokes listeners, and how AsyncResource can associate callbacks with an asynchronous execution context. The manifest supplies the A, B, R, LOCAL, and MUTATED values. The application defines the requirement that payload A match store A, the policy on frozen objects, and the criteria for a release.

Decide ACCEPT, REPAIR, RERUN, or HOLD

Use the evidence from the run to choose a decision.

Evidence condition

Decision

Meaning

Pinned v24.22.2 confirmed; fixture hash confirmed; every case present exactly once; C01/C03/C04/C06/C08/C09 match oracle; no application-contract violation remains

ACCEPT

Admit only the tested request-isolation workflow

Valid fixture deterministically shows C05 contamination or C07 shared-state identity leakage and the defect is bounded to this code path

REPAIR

Apply narrow scoping/state-ownership fix, then execute full suite again

A run was attempted but runtime, hash, logs, case coverage, exit status, or evidence identity is incomplete or inconsistent

RERUN

Discard that run as admission evidence and repeat from a clean fixture

No execution evidence exists; negative control is invalid; valid reruns contradict the pinned documented model; or safe repair scope is unclear

HOLD

Do not admit the workflow until the uncertainty is resolved

The current decision is HOLD. Every fixture case is EXPECTED / NOT EXECUTED. To reach ACCEPT, a run must establish which request owned the callback and whether the store observed there satisfies the application’s contract.

Backend Development at Refonte Learning

For broader backend training, see Refonte Learning’s Backend Developer Program. It runs for three months at 10–12 hours per week. The listed prerequisites include a basic understanding of programming and current study toward a bachelor’s or higher degree.

The curriculum covers Node.js and Express, MongoDB and SQL, REST APIs and microservices, authentication and authorization, backend testing and debugging, deployment with Docker and cloud platforms, and a capstone project. Its REST API module includes routing, middleware, and database interaction. The program FAQ names AWS and Azure as examples of cloud platforms used in backend work.

The program describes educational mentoring and hands-on projects. It lists a virtual internship as a potential opportunity.

The program lists a Training Certificate and a Certificate of Internship for successful completion. Additional recommendation or appreciation materials depend on performance. The career paths listed include backend developer, API developer, and database administrator.