How does NestJS handle graceful shutdown?
Answer
Graceful shutdown in NestJS ensures in-flight requests complete and resources are cleaned up before the process exits. Enable signal handling in main.ts: app.enableShutdownHooks();. NestJS then listens for SIGTERM, SIGINT, and other signals. Lifecycle hooks fire in order: onModuleDestroy() on all providers → beforeApplicationShutdown(signal) → onApplicationShutdown(signal). Implement these in services to close database connections, flush buffers, deregister from service discovery, and stop background jobs. For HTTP connections, the underlying server (server.close()) stops accepting new connections but waits for existing ones. In Kubernetes, set a terminationGracePeriodSeconds longer than your longest expected request to ensure complete draining before pod termination.
Previous
What is the NestJS Interceptor execution order and how do multiple interceptors interact?
Next
What is custom provider syntax in NestJS (useClass, useValue, useFactory)?
More NestJS Questions
View all →- Advanced What is the CQRS pattern and how does NestJS support it?
- Advanced How do you implement gRPC in NestJS?
- Advanced What is the NestJS Interceptor execution order and how do multiple interceptors interact?
- Advanced What is custom provider syntax in NestJS (useClass, useValue, useFactory)?
- Advanced What is the difference between forRoot() and forFeature() in NestJS modules?