🦅 NestJS Advanced

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.