Transitive request-scoping across NestJS provider graph
0 reputation · 20 Mar 2025, 07:29 UTC
NestJS @Injectable({ scope: Scope.REQUEST }) marks a provider for per-request instantiation, but the framework does not isolate this scope to the annotated provider alone. Every dependent provider or controller that injects it inherits request scope, propagating transitively up the dependency chain.
This behavior is documented but often unexpected, particularly when a single request-scoped utility, such as a tenant-context service, intended for a narrow scope inadvertently widens an entire feature module's controllers to request scope. The precise goal is to determine whether a given provider annotation triggers transitive scope widening in a specific module graph, and to quantify the resulting latency and memory overhead per incoming HTTP request.
Uncertainty remains around the boundary conditions: whether singleton-scoped intermediaries break the propagation, and how the choice interacts with NestJS's module flattening and testing configurations. Does NestJS silently widen the scope of all controllers that inject a request-scoped provider, even when intermediate singleton providers exist? Under what conditions does scope propagation stop, if at all? Can the injection graph be restructured to confine request scope without full refactoring to method-level context passing?