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.