The state sharing model in NestJS is based on Node.js’s single-threaded event loop, where nearly everything is shared across incoming requests—including database connection pools, singleton services with global state, and other resources.
How it works
Unlike multi-threaded frameworks where each request gets its own thread, Node.js (and thus NestJS) uses a single thread with an event loop. This means:
- All requests share the same process memory
- Singleton providers are instantiated once at application bootstrap
- The same service instances handle all incoming requests
Safety
Using singleton instances in NestJS is completely safe because:
- Node.js doesn’t use a multi-threaded request/response model
- JavaScript’s single-threaded nature prevents race conditions from concurrent access
- Each request is processed sequentially in the event loop
Implications
- Services maintain state across requests (useful for caching, connection pools)
- Per-request state should be stored in request-scoped providers or request context
- Database connection pools are safely shared across all requests
This model explains why singleton patterns like Redis Repository Pattern work well in NestJS applications.