0
0
NestJSframework~8 mins

Provider scope (default, request, transient) in NestJS - Performance & Optimization

Choose your learning style9 modes available
Performance: Provider scope (default, request, transient)
MEDIUM IMPACT
This affects server response time and memory usage by controlling how often instances of providers are created during request handling.
Managing service instances for HTTP requests
NestJS
import { Injectable, Scope } from '@nestjs/common';

@Injectable({ scope: Scope.REQUEST })
export class UserService {
  // stateful data per request
}

// New instance per HTTP request avoids shared state
Creates a fresh instance per request, avoiding shared state and reducing memory leaks.
📈 Performance GainImproves response consistency and controls memory usage by limiting instance lifetime.
Managing service instances for HTTP requests
NestJS
import { Injectable, Scope } from '@nestjs/common';

@Injectable({ scope: Scope.DEFAULT })
export class UserService {
  // stateful data stored here
}

// Used in many requests, but state is kept per instance
Using default scope with stateful providers can cause shared state bugs and unnecessary memory retention.
📉 Performance CostIncreases memory usage and can cause slower response times due to unintended state sharing.
Performance Comparison
PatternInstance Creation FrequencyMemory UsageResponse Time ImpactVerdict
Default Scope (Singleton)Once per app lifecycleLowFast[OK] Good
Request ScopeOnce per HTTP requestMediumModerate[!] OK
Transient ScopeEvery injectionHighSlower if overused[X] Bad if misused
Rendering Pipeline
Provider scope affects how NestJS creates and manages service instances during request processing, impacting memory allocation and CPU usage before sending response.
Dependency Injection
Request Handling
Memory Management
⚠️ BottleneckMemory Management due to instance creation and garbage collection
Optimization Tips
1Use default (singleton) scope for stateless services to minimize instance creation.
2Use request scope only when you need per-request state isolation.
3Use transient scope sparingly for unique short-lived instances to avoid memory bloat.
Performance Quiz - 3 Questions
Test your performance knowledge
Which provider scope creates a new instance for every HTTP request in NestJS?
ADefault scope
BRequest scope
CTransient scope
DSingleton scope
DevTools: Node.js Profiler or NestJS Debug Logs
How to check: Enable debug logs for provider lifecycle or use Node.js profiler to monitor object creation and memory usage during requests.
What to look for: Look for excessive instance creations or memory spikes indicating inefficient provider scope usage.