CodePark/ questions / Configuration & lifecycle hooks
START PRACTICINGPRACTICE
Backend question · NestJS › Configuration & lifecycle hooks

How do you implement graceful shutdown in Nest, for example closing a queue worker and DB pool when Kubernetes sends SIGTERM?

// main.ts
const app = await NestFactory.create(AppModule);
app.enableShutdownHooks();
await app.listen(3000);

@Injectable()
export class WorkerService implements OnApplicationShutdown {
  async onApplicationShutdown(signal?: string) {
    await this.worker.close();
  }
}

Call app.enableShutdownHooks() in main.ts. Then put your cleanup code in Nest's shutdown hooks.

Why you need it: without this call, Nest doesn't listen for system signals like SIGTERM. SIGTERM is the signal Kubernetes sends when it wants a pod to stop. Without the call, the shutdown hooks only run when you call app.close() yourself.

When the app stops, Nest runs these steps in order:

  • It calls onModuleDestroy() on providers.
  • When those have finished, it calls beforeApplicationShutdown(signal).
  • It closes the HTTP server and other connections.
  • It calls onApplicationShutdown(signal).

Nest waits for async hooks to finish. Put your cleanup in these hooks:

  • Stop accepting new jobs.
  • Close queue workers.
  • Flush logs.
  • Disconnect from the database.

The feature is opt-in, because shutdown listeners use some resources. Nest does not call lifecycle hooks on request-scoped providers. Make sure the container's grace period is longer than your cleanup takes. The grace period is how long Kubernetes waits after SIGTERM before it kills the process.

  • Call app.enableShutdownHooks() so Nest reacts to signals like SIGTERM.
  • The order is onModuleDestroy, then beforeApplicationShutdown, then onApplicationShutdown.
  • Nest closes connections between the last two hooks.
  • Nest waits for async hooks to finish.
  • Lifecycle hooks are not called on request-scoped providers.