We use cookies for analytics and advertising. Ads are disabled until you accept advertising cookies. Read our Cookie Policy and Privacy Policy.
Request-Scoped Dependency Container in Node.js (Guide) | TVerge Tech
Request-Scoped Dependency Container in Node.js (Guide)
Build a request-scoped dependency container in Node.js with AsyncLocalStorage: lifetimes, async factories, safe disposal, Express middleware and tests.
November 22, 2026Nwankwo Ernest Onyebuchi25 min read
Was this useful?
Building a Reliable Request-Scoped Dependency Container in Node.js
Every Node.js API eventually runs into the same problem. Some objects are safe to share across the whole process, like configuration, a connection pool or a base logger. Others must exist exactly once per incoming request, like the request ID, the authenticated user, a database connection or a transaction. If you mix the two up, you get bugs that only appear under concurrency: one user sees another user's data, a log line carries the wrong request ID, or a connection is never returned to the pool.
A request-scoped dependency container in Node.js solves this by giving each request its own short-lived scope. Services created inside that scope are shared by everything handling that request, isolated from every other request, and cleaned up when the request ends. In this guide you will build one from scratch in TypeScript, wire it into Express with AsyncLocalStorage, add safe disposal, and test the parts that usually break in production.
Key Takeaways
A reliable container needs three lifetimes: singleton (one per process), scoped (one per request) and transient (one per resolution).
Cache the promise of an instance, not the instance, so concurrent async resolutions never create duplicates.
Block singletons from depending on scoped services. This "captive dependency" mistake is the most common source of cross-request data leaks.
Create the scope in middleware, dispose it on the response close event, and dispose in reverse order of creation.
Use AsyncLocalStorage for ambient access (logging, deep call sites), but prefer explicit scope passing at your application edges.
Test isolation, disposal order, circular dependencies and context propagation directly. They are cheap to test and expensive to debug in production.
Why Request Scope Matters in Node.js
Node.js runs your JavaScript on a single main thread, and many requests are in flight at the same time. While one handler waits on a database query, another handler runs. Any state stored in a module-level variable is visible to all of them.
That is fine for immutable, process-wide things. It is dangerous for anything tied to one request. Consider this common mistake:
// Don't do this
let currentUser: User | undefined;
app.use(async (req, _res, next) => {
currentUser = await authenticate(req);
next();
});
app.get("/profile", async (_req, res) => {
const profile = await loadProfile(currentUser!.id); // which user is this?
res.json(profile);
});
Between the await in the middleware and the use of currentUser in the handler, another request can overwrite the variable. The code works in local testing with one request at a time and fails under real traffic.
The usual fix is to pass the data explicitly through every function. That is correct, but it becomes noisy as call chains grow: the request ID has to travel through controllers, services, repositories and the logger. A request-scoped container gives you a better default: each request gets one scope, and anything that needs request data asks the scope for it.
If you are also moving state out of process memory for deployment reasons, the same discipline applies. Process-wide singletons live and die with a single instance, which is the root cause behind users getting logged out after a Docker redeploy. A good container makes the boundary between "per process" and "per request" visible in code.
Core Concepts: Lifetimes, Scopes and Tokens
Before writing code, fix the vocabulary.
Dependency injection (DI) means a component receives the things it needs instead of creating or locating them itself. A container is the object that knows how to build those things and hand them out.
A scope is a child of the root container. It can create scoped instances and caches them for its own lifetime. When the scope is disposed, everything it created is cleaned up.
A token is the key you use to ask for a dependency. In TypeScript, interfaces do not exist at runtime, so you cannot use them as keys. A symbol branded with a type parameter gives you both a unique runtime key and full type inference.
Designing the Container
The design goals are small and strict:
Resolution is asynchronous, because real factories open connections and read files.
Scoped and transient instances are never cached in the root.
A singleton can never receive a scoped dependency.
Circular dependencies fail with a readable message instead of hanging.
Disposal runs in reverse creation order and reports every failure.
Step 1: Typed Tokens
// container/token.ts
export type Token<T> = symbol & { readonly __type?: T };
export function token<T>(description: string): Token<T> {
return Symbol(description) as Token<T>;
}
The __type property exists only for the compiler. At runtime a token is just a symbol, so two tokens with the same description are still different keys.
Step 2: The Scope and the Builder
One class, Scope, plays both roles. The root container is a scope with no parent, and each request scope is a child that points back to the root.
// container/scope.ts
import type { Token } from "./token";
export type Lifetime = "singleton" | "scoped" | "transient";
export interface Resolver {
resolve<T>(token: Token<T>): Promise<T>;
}
export type Factory<T> = (resolver: Resolver) => T | Promise<T>;
export type Disposer<T> = (instance: T) => void | Promise<void>;
interface Registration<T> {
lifetime: Lifetime;
factory: Factory<T>;
dispose?: Disposer<T>;
}
type Registry = Map<symbol, Registration<any>>;
export class ContainerBuilder {
private readonly registry: Registry = new Map();
add<T>(
token: Token<T>,
lifetime: Lifetime,
factory: Factory<T>,
dispose?: Disposer<T>,
): this {
this.registry.set(token, { lifetime, factory, dispose });
return this;
}
build(): Scope {
return new Scope(new Map(this.registry));
}
}
export class Scope implements Resolver {
private readonly cache = new Map<symbol, Promise<unknown>>();
private readonly seeded = new Map<symbol, unknown>();
private readonly disposers: Array<() => Promise<void>> = [];
private disposed = false;
constructor(
private readonly registry: Registry,
private readonly root?: Scope,
) {}
createScope(): Scope {
return new Scope(this.registry, this.root ?? this);
}
/** Seed a per-request value (request ID, user) that has no factory. */
provide<T>(token: Token<T>, value: T): this {
this.seeded.set(token, value);
return this;
}
resolve<T>(token: Token<T>): Promise<T> {
return this.resolveChain(token, []);
}
private resolveChain<T>(
token: Token<T>,
chain: readonly symbol[],
): Promise<T> {
const name = token.description ?? "unnamed";
if (this.disposed) {
return Promise.reject(
new Error(`Cannot resolve "${name}": the scope is already disposed`),
);
}
// Check cycles before the cache, or a cycle would wait on itself forever.
if (chain.includes(token)) {
const path = [...chain, token].map((t) => t.description).join(" -> ");
return Promise.reject(new Error(`Circular dependency: ${path}`));
}
if (this.seeded.has(token)) {
return Promise.resolve(this.seeded.get(token) as T);
}
const registration = this.registry.get(token);
if (!registration) {
return Promise.reject(
new Error(
`No provider registered for "${name}". ` +
`Request-scoped values cannot be injected into singletons.`,
),
);
}
const root = this.root ?? this;
if (registration.lifetime === "scoped" && this === root) {
return Promise.reject(
new Error(
`Scoped provider "${name}" was resolved outside a request scope. ` +
`Is a singleton depending on it?`,
),
);
}
// Singletons are always built and cached by the root, so their
// dependencies are resolved against the root as well.
const owner = registration.lifetime === "singleton" ? root : this;
const nextChain = [...chain, token];
if (registration.lifetime === "transient") {
return owner.instantiate(token, registration, nextChain);
}
let pending = owner.cache.get(token) as Promise<T> | undefined;
if (!pending) {
pending = owner.instantiate(token, registration, nextChain);
owner.cache.set(token, pending);
// Don't cache failures: let a later call retry.
pending.catch(() => {
if (owner.cache.get(token) === pending) owner.cache.delete(token);
});
}
return pending;
}
private async instantiate<T>(
token: Token<T>,
registration: Registration<T>,
chain: readonly symbol[],
): Promise<T> {
const resolver: Resolver = {
resolve: (dependency) => this.resolveChain(dependency, chain),
};
const instance = await registration.factory(resolver);
// The scope may have been disposed while the factory was running
// (for example, the client disconnected mid-request).
if (this.disposed) {
await registration.dispose?.(instance);
throw new Error(
`Scope was disposed while creating "${token.description}"`,
);
}
if (registration.dispose) {
const dispose = registration.dispose;
this.disposers.push(async () => dispose(instance));
}
return instance;
}
async dispose(): Promise<void> {
if (this.disposed) return;
this.disposed = true;
const errors: unknown[] = [];
// Newest first: dependents are released before their dependencies.
for (const run of this.disposers.splice(0).reverse()) {
try {
await run();
} catch (error) {
errors.push(error);
}
}
this.cache.clear();
this.seeded.clear();
if (errors.length > 0) {
throw new AggregateError(errors, "One or more providers failed to dispose");
}
}
}
A few design decisions are worth explaining, because each one prevents a specific class of bug.
Caching promises, not values. Suppose two parts of a request resolve the same scoped service at the same moment. If you cache only finished instances, both calls see an empty cache, both run the factory, and you end up with two database connections where you expected one. Storing the pending promise means the second caller simply waits for the first.
Detecting cycles before the cache lookup. If service A needs B and B needs A, the promise for A would wait on B, which waits on the promise for A. That is a silent deadlock. Tracking the resolution chain turns it into an immediate error with a readable path.
Resolving singleton dependencies against the root. A singleton factory receives a resolver bound to the root scope. If it asks for a scoped service, the root refuses. This turns the captive dependency bug, where a long-lived object quietly holds a reference to one request's data, into an error at the first resolution instead of an intermittent data leak.
Pushing disposers after creation. Dependencies finish creating before their dependents, so the disposer list is already in dependency order. Reversing it releases the dependents first.
Defining Services and Registering Providers
Now describe the application. The interfaces below stand in for whatever driver and logger you use, such as pg or mysql2 for the pool and pino for logging.
// app/tokens.ts
import { token } from "../container/token";
import type {
AppConfig, Connection, Logger, Pool, RequestContext,
} from "./types";
import type { UserRepository } from "./user-repository";
import type { UserService } from "./user-service";
export const TOKENS = {
Config: token<AppConfig>("Config"),
Pool: token<Pool>("Pool"),
Logger: token<Logger>("Logger"),
RequestContext: token<RequestContext>("RequestContext"),
RequestLogger: token<Logger>("RequestLogger"),
Db: token<Connection>("Db"),
UserRepository: token<UserRepository>("UserRepository"),
UserService: token<UserService>("UserService"),
} as const;
The services themselves know nothing about the container. They take plain constructor arguments, which keeps them easy to test and easy to reuse.
// app/user-repository.ts
import type { Connection, Logger, User } from "./types";
export class UserRepository {
constructor(
private readonly db: Connection,
private readonly log: Logger,
) {}
async findById(id: string): Promise<User | undefined> {
const rows = await this.db.query<User>(
"SELECT id, name, email FROM users WHERE id = $1",
[id],
);
this.log.info("user lookup", { found: rows.length > 0 });
return rows[0];
}
}
// app/user-service.ts
import type { User } from "./types";
import type { UserRepository } from "./user-repository";
export class UserService {
constructor(private readonly users: UserRepository) {}
getUser(id: string): Promise<User | undefined> {
return this.users.findById(id);
}
}
The composition root is the one place that knows how everything is wired. It also takes an optional customize callback, which is how tests swap in fakes.
// app/container.ts
import { ContainerBuilder, type Scope } from "../container/scope";
import { TOKENS } from "./tokens";
import type { AppConfig, Logger, Pool } from "./types";
import { UserRepository } from "./user-repository";
import { UserService } from "./user-service";
export function buildContainer(
config: AppConfig,
pool: Pool,
baseLogger: Logger,
customize?: (builder: ContainerBuilder) => void,
): Scope {
const builder = new ContainerBuilder()
// Process-wide
.add(TOKENS.Config, "singleton", () => config)
.add(TOKENS.Pool, "singleton", () => pool, (p) => p.end())
.add(TOKENS.Logger, "singleton", () => baseLogger)
// Per request
.add(TOKENS.RequestLogger, "scoped", async (r) => {
const [logger, ctx] = await Promise.all([
r.resolve(TOKENS.Logger),
r.resolve(TOKENS.RequestContext),
]);
return logger.child({ requestId: ctx.requestId });
})
.add(
TOKENS.Db,
"scoped",
async (r) => (await r.resolve(TOKENS.Pool)).acquire(),
(connection) => connection.release(),
)
.add(TOKENS.UserRepository, "scoped", async (r) =>
new UserRepository(
await r.resolve(TOKENS.Db),
await r.resolve(TOKENS.RequestLogger),
),
)
.add(TOKENS.UserService, "scoped", async (r) =>
new UserService(await r.resolve(TOKENS.UserRepository)),
);
customize?.(builder);
return builder.build();
}
Notice that the database connection is a scoped, lazily created resource. A request that never touches the database never acquires a connection, and one that does gets exactly one, released automatically when the scope is disposed. This is one of the practical benefits of the pattern: connection lifecycle becomes a declaration instead of a try/finally in every handler.
Wiring the Container Into Express
Express gives you the natural place to create a scope: a middleware that runs at the start of each request. The middleware has three jobs:
Create a child scope and seed it with the request context.
Schedule disposal for when the response ends.
Run the rest of the request inside that scope.
The request ID deserves a short security note. It is convenient to honor an incoming x-request-id header so traces can span services, but the value comes from the client. Validate its shape before it ends up in your logs, or a malicious client can inject arbitrary content into them.
// http/request-scope.ts
import { randomUUID } from "node:crypto";
import type { RequestHandler } from "express";
import { TOKENS } from "../app/tokens";
import type { Scope } from "../container/scope";
import { runInScope } from "./scope-storage";
const SAFE_REQUEST_ID = /^[A-Za-z0-9_-]{8,64}$/;
function pickRequestId(header: string | undefined): string {
return header && SAFE_REQUEST_ID.test(header) ? header : randomUUID();
}
export function requestScope(
root: Scope,
onDisposeError: (error: unknown) => void,
): RequestHandler {
return (req, res, next) => {
const scope = root.createScope().provide(TOKENS.RequestContext, {
requestId: pickRequestId(req.header("x-request-id")),
method: req.method,
path: req.path,
startedAt: Date.now(),
});
// "close" fires when the response completes AND when the client
// disconnects early, so cleanup runs in both cases.
res.once("close", () => {
scope.dispose().catch(onDisposeError);
});
runInScope(scope, () => next());
};
}
The close event on the response is the right hook because it covers both a normal finish and a premature disconnect. Listening only for finish would leak connections whenever a client hangs up mid-request. The Node.js HTTP documentation describes the exact semantics of both events.
Express treats everything after next() as part of the same call chain, so route handlers run inside the scope. If any middleware that runs before your scope middleware reads the request body, move the scope middleware after it. Some stream-based libraries emit events from contexts that were created before your scope existed, and the scope will not follow them.
Ambient Access With AsyncLocalStorage
Handlers can receive the scope explicitly, but deep call sites, such as a logging helper or an audit function, should not need it threaded through every signature. That is what AsyncLocalStorage from node:async_hooks is for. It keeps a value alive across await calls, timers and promise chains started inside run(), and each concurrent request sees only its own value.
// http/scope-storage.ts
import { AsyncLocalStorage } from "node:async_hooks";
import type { Token } from "../container/token";
import type { Scope } from "../container/scope";
const storage = new AsyncLocalStorage<Scope>();
export function runInScope<R>(scope: Scope, fn: () => R): R {
return storage.run(scope, fn);
}
export function currentScope(): Scope {
const scope = storage.getStore();
if (!scope) {
throw new Error(
"No active request scope. Was this called outside a request, " +
"or did the async context get lost?",
);
}
return scope;
}
export function inject<T>(token: Token<T>): Promise<T> {
return currentScope().resolve(token);
}
Now the route reads naturally, and the services behind it receive their dependencies without any request plumbing:
// server.ts
import express from "express";
import { buildContainer } from "./app/container";
import { TOKENS } from "./app/tokens";
import { inject } from "./http/scope-storage";
import { requestScope } from "./http/request-scope";
const root = buildContainer(config, pool, logger);
const app = express();
app.use(express.json());
app.use(
requestScope(root, (error) =>
logger.info("scope dispose failed", { error: String(error) }),
),
);
app.get("/users/:id", async (req, res) => {
const users = await inject(TOKENS.UserService);
const user = await users.getUser(req.params.id);
if (!user) {
res.status(404).json({ error: "User not found" });
return;
}
res.json(user);
});
Express 5 forwards rejected promises from async handlers to your error handler automatically. On Express 4, wrap async handlers in a helper or use try/catch. See the Express guide on error handling for the details of your version.
Prefer Explicit Scope Passing at the Edges
Ambient access is convenient, and convenience is how hidden dependencies creep in. A sensible split is:
Controllers and route handlers read the scope explicitly, for example from a typed req.scope.
Cross-cutting helpers, such as loggers and tracing, use AsyncLocalStorage.
Set req.scope = scope in the middleware and call req.scope.resolve(...) in handlers. If the async context is ever lost, your main code path still works, and only the ambient helpers fail, loudly, with the error message from currentScope().
Using the Same Idea in Other Frameworks
The pattern is framework-neutral. In Fastify, create the scope in an onRequest hook and dispose it in the response-side hooks; the Fastify hooks reference lists the full request lifecycle. NestJS has built-in request-scoped providers, with documented trade-offs, in its injection scopes guide. If you would rather not maintain your own container, libraries such as Awilix offer createScope() with similar semantics. Building one yourself is still worth doing once, because it teaches you exactly which failure modes any container has to handle.
Choosing Between Approaches
Approach
Strength
Main risk
Pass everything as parameters
Fully explicit, trivially testable
Noisy signatures in deep call chains
Attach services to req
Simple, no ambient state
Couples services to the HTTP layer
Container with explicit scope
Clear lifetimes, easy cleanup
You must pass the scope around
Container plus AsyncLocalStorage
Ambient access, minimal plumbing
Hidden dependencies; context can be lost
Framework DI (for example NestJS)
Integrated, well documented
Framework lock-in; scope can propagate up the dependency chain
There is no universally correct row. Small services often do fine with explicit parameters. Once you have per-request resources that need guaranteed cleanup, a container starts paying for itself.
Common Pitfalls and How to Avoid Them
1. The Captive Dependency
A singleton that holds a scoped service keeps the first request's instance forever. Every later request then shares it. This is the most damaging mistake because nothing crashes; the wrong data is simply served.
The container above prevents it structurally. If a singleton factory asks for a scoped token, the root rejects the call with a message that names the token. Treat that error as a design signal: either the singleton should not depend on request data, or the dependency should be passed as an argument at call time.
2. Losing the Async Context
AsyncLocalStorage follows promises and timers automatically. It can lose track in code that queues work outside your call chain, such as callback-based libraries that process a shared internal queue, or event emitters created before the request started. When that happens, getStore() returns undefined inside the callback.
The fix is to bind the callback to the context that was active when you registered it. Node.js provides AsyncResource.bind(), and recent releases also offer AsyncLocalStorage.bind() and AsyncLocalStorage.snapshot(); check the async context documentation for the version table.
import { AsyncResource } from "node:async_hooks";
legacyClient.on("data", AsyncResource.bind((chunk: Buffer) => {
// Runs with the context of the code that registered the listener.
void handleChunk(chunk);
}));
3. Background Work That Outlives the Request
The scope is disposed when the response closes. If a handler starts fire-and-forget work, such as sending an email or publishing an event, that work may try to resolve services from a scope that no longer exists and will fail with the "scope is already disposed" error.
Do not keep the request scope alive for background work. Create a fresh scope for the job instead:
Reusing the originating request ID keeps your logs traceable across the boundary.
4. Avoid enterWith
AsyncLocalStorage also exposes enterWith(), which changes the context for the rest of the current synchronous execution and anything it triggers. It is easy to leak that context into code that should not see it. Prefer run(), which has a clear beginning and end.
5. Disposal Failures Hiding Each Other
If one disposer throws and you stop there, the remaining resources never get released. The container above continues through the list and reports everything at the end through an AggregateError. Make sure your onDisposeError handler logs the individual errors.
6. Unbounded Scope Lifetimes
Long-lived connections such as server-sent events or WebSockets keep a scope alive for as long as they stay open. A scoped database connection acquired at the start would be held that whole time. For long-lived connections, resolve expensive resources on demand and release them early, or acquire them per message rather than per connection.
7. Process-Level State Is Not Shared Across Instances
Singletons are per process. If you run several containers or replicas, each has its own copy of every singleton. Anything that must be consistent across instances, such as sessions or rate-limit counters, belongs in an external store rather than a singleton's memory.
Testing the Container
The big advantage of this design is that the container has no HTTP dependency. You can test lifetimes, isolation and disposal with the built-in node:test runner and no server at all.
// container/scope.test.ts
import assert from "node:assert/strict";
import { test } from "node:test";
import { setTimeout as sleep } from "node:timers/promises";
import { ContainerBuilder } from "./scope";
import { token } from "./token";
import { inject } from "../http/scope-storage";
import { runInScope } from "../http/scope-storage";
const Counter = token<{ id: number }>("Counter");
const Singleton = token<object>("Singleton");
const Scoped = token<object>("Scoped");
test("scoped instances are shared within a scope and isolated across scopes", async () => {
let created = 0;
const root = new ContainerBuilder()
.add(Counter, "scoped", async () => {
await sleep(5);
return { id: ++created };
})
.build();
const a = root.createScope();
const b = root.createScope();
// Two concurrent resolutions in one scope must share one instance.
const [a1, a2] = await Promise.all([a.resolve(Counter), a.resolve(Counter)]);
const b1 = await b.resolve(Counter);
assert.equal(a1, a2);
assert.notEqual(a1, b1);
assert.equal(created, 2);
});
test("a singleton cannot depend on a scoped service", async () => {
const root = new ContainerBuilder()
.add(Scoped, "scoped", () => ({}))
.add(Singleton, "singleton", (r) => r.resolve(Scoped))
.build();
await assert.rejects(
root.createScope().resolve(Singleton),
/resolved outside a request scope/,
);
});
test("circular dependencies fail with a readable path", async () => {
const A = token<object>("A");
const B = token<object>("B");
const root = new ContainerBuilder()
.add(A, "singleton", (r) => r.resolve(B))
.add(B, "singleton", (r) => r.resolve(A))
.build();
await assert.rejects(root.resolve(A), /A -> B -> A/);
});
test("disposal runs in reverse creation order and reports every failure", async () => {
const order: string[] = [];
const First = token<string>("First");
const Second = token<string>("Second");
const root = new ContainerBuilder()
.add(First, "scoped", () => "first", () => { order.push("first"); })
.add(Second, "scoped", async (r) => {
await r.resolve(First);
return "second";
}, () => {
order.push("second");
throw new Error("release failed");
})
.build();
const scope = root.createScope();
await scope.resolve(Second);
await assert.rejects(scope.dispose(), AggregateError);
assert.deepEqual(order, ["second", "first"]);
});
test("AsyncLocalStorage keeps concurrent requests isolated", async () => {
const Id = token<string>("Id");
const root = new ContainerBuilder().build();
const seen = await Promise.all(
["a", "b", "c"].map((id) => {
const scope = root.createScope().provide(Id, id);
return runInScope(scope, async () => {
await sleep(Math.random() * 20);
return inject(Id);
});
}),
);
assert.deepEqual(seen, ["a", "b", "c"]);
});
For application-level tests, call buildContainer(...) with a customize callback that re-registers tokens with fakes. Because add() replaces an existing registration, a test can substitute the pool or the repository in one line without touching production wiring.
If you need sample identifiers for fixtures or load tests, the Bulk UUID Generator can produce them in bulk, and the JSON Formatter & Validator is handy for inspecting structured log lines while you verify that every entry carries the right requestId.
Production Checklist
Before you ship a request-scoped container, walk through these questions:
Lifetimes: Is every registration marked singleton, scoped or transient on purpose, rather than by habit?
Captive dependencies: Is there a test proving that a singleton cannot receive a scoped service?
Disposal: Is the scope disposed on the response close event, and do disposal errors get logged?
Cancellation: What happens when a client disconnects while a factory is still running? (The container above disposes the late instance and rejects.)
Request IDs: Are incoming IDs validated before being logged or echoed in headers?
Context propagation: Have you checked that logging and tracing helpers still see the scope inside callback-based libraries?
Background work: Does every job create its own scope instead of borrowing the request's?
Shutdown: On SIGTERM, do you stop accepting connections, let in-flight requests finish, and then dispose the root so singletons such as the pool close cleanly?
Observability: Do you log request duration at disposal time, using startedAt from the request context?
Measurement: Have you profiled your own workload? AsyncLocalStorage adds some overhead, and the right answer depends on your traffic, so measure it rather than assuming.
A minimal graceful shutdown for the root scope looks like this:
It is a dependency that is created at most once per incoming request and shared by everything handling that request, but never shared with other requests. Typical examples are the request context, a per-request logger, a database transaction and repositories that use them.
Do I need a dependency injection library, or can I build my own?
You can build a small one, as this guide shows, and for many services that is enough. A library becomes attractive when you need features such as automatic constructor injection, module systems or decorators. Either way, the lifetime rules in this article apply to all of them.
Is AsyncLocalStorage safe to use in production?
It is part of the Node.js core async_hooks module and is documented as stable in current Node.js releases. It is widely used for request-scoped logging and tracing. The main caveat is context loss in code that queues work outside your call chain, which you can address with the binding tools described above.
Does AsyncLocalStorage hurt performance?
There is some overhead, because Node.js has to track asynchronous resources to carry the store along. For most web workloads that cost is small compared with I/O, but the only reliable answer for your service is to benchmark it under realistic load.
Why not just attach services to the req object?
You can, and it works well at the HTTP layer. The drawback is that every function deeper in the call chain needs the req object, which couples your business logic to Express. A container with an explicit scope, optionally backed by AsyncLocalStorage, keeps that logic framework-independent.
How do I handle background jobs or queue consumers?
Create a new scope per job, seed it with the job's context, and dispose it in a finally block. Never reuse a request scope for work that can outlive the response.
Can a singleton use request data?
Not directly. If a singleton needs per-request data, pass that data as a method argument or have the caller resolve the scoped service and hand it in. Letting a singleton capture a scoped instance is exactly the bug this design is built to block.
Conclusion
A reliable request-scoped dependency container in Node.js comes down to a handful of rules, each of which prevents a real production failure: separate singleton, scoped and transient lifetimes; cache promises so concurrent resolution stays safe; forbid singletons from capturing scoped services; detect cycles early; and tie disposal to the response close event so resources are released whether the request succeeds, fails or is abandoned.
Add AsyncLocalStorage where ambient access genuinely helps, keep explicit scope passing at your application edges, and cover isolation, disposal and context propagation with tests. The result is code that is easier to reason about under concurrency, with resource cleanup you no longer have to remember in every handler.
3MutationObserver Guide: Detect DOM Changes in JS & React