skip to content

A NestJS 12 service runs onModuleDestroy on app.close() in tests, but never when the orchestrator stops its pod with SIGTERM; why?

level: seniorimportance: must knowfreq 50%

answer

  1. close() versus a process signal
  2. signal listeners are opt-in
  3. Node's default action on SIGTERM
  4. default list, custom list

basics

~20 s

NestJS only listens for process signals after app.enableShutdownHooks() is called at bootstrap. Without it, SIGTERM takes Node's default action and the process dies before any shutdown hook runs; tests pass because they call app.close() directly.

solid answer

~40 s

Shutdown hooks run on an explicit `app.close()`, which the tests call, but for a signal Nest must first install process listeners, and it does that only when you call `app.enableShutdownHooks()`. It is off by default because the listeners cost memory, and several apps in one process, as in parallel tests, can trigger too-many-listeners warnings. Without it, `SIGTERM` gets Node's default action and the process ends at once, with no hooks. With it, Nest runs `onModuleDestroy()`, `beforeApplicationShutdown()` and `onApplicationShutdown()`, removes its listeners and re-sends the signal to its own process, which then normally ends with the signal's status. Called with no arguments it listens for every `ShutdownSignal` value, `SIGTERM` included; a list such as `['SIGINT']` would miss `SIGTERM` again.

go deeper

for a junior

Remember that NestJS only runs its shutdown hooks on a process signal after app.enableShutdownHooks() is called at bootstrap.

for a middle

Explain the two entry points, close() and signals, the default signal list, and why the feature is off by default.

for a senior

Walk the diagnosis: missing call, narrowed list, signal not forwarded, grace period exceeded, then how Nest ends the process and with which status.

for a principal

Decide the bootstrap template every service shares, including the signal list, the exit behaviour and a teardown time budget under the grace period.

## Two ways into the shutdown sequence NestJS has one shutdown sequence, `onModuleDestroy()`, `beforeApplicationShutdown()`, closing the server, then `onApplicationShutdown()`, and two ways to start it: - **An explicit `app.close()`**. Test suites call it after the last test, which is why the hooks visibly run there. - **A process signal**, such as the `SIGTERM` an orchestrator sends before stopping a container. Nest only reacts to signals if `app.enableShutdownHooks()` was called at bootstrap. When the second path is not enabled, nothing in Nest listens for `SIGTERM`. The runtime applies the default action for the signal, which terminates the process immediately; how Node treats unhandled signals is the runtime's own subject. No hook runs, no connection is closed politely, and the exit status is the one a signal death produces (143 for `SIGTERM` on Linux). ## What `enableShutdownHooks()` installs ```typescript import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module.js'; const app = await NestFactory.create(AppModule); app.enableShutdownHooks(); await app.listen(process.env.PORT ?? 3000); ``` - **Signal list**: `enableShutdownHooks(signals?, options?)`. With no list, or an empty one, Nest listens for every value of the `ShutdownSignal` enum: `SIGHUP`, `SIGINT`, `SIGQUIT`, `SIGILL`, `SIGTRAP`, `SIGABRT`, `SIGBUS`, `SIGFPE`, `SIGSEGV`, `SIGUSR2` and `SIGTERM`. Names you pass are upper-cased and de-duplicated. - **Idempotent**: calling it again for a signal it already handles adds no second listener. - **One shutdown at a time**: if a signal arrives while a shutdown is already under way, from `app.close()` or another signal, Nest ignores it rather than starting a second teardown. - **After the hooks**: Nest removes its listeners and calls `process.kill(process.pid, signal)`, so, unless some other listener handles that signal, the process now dies of it with the status the platform expects. - **On failure**: if the shutdown sequence itself rejects, Nest logs `Error happened during shutdown` and calls `process.exit(1)`. ## Choosing how the process ends | Setting | After the hooks | Exit status for `SIGTERM` | |---|---|---| | `enableShutdownHooks()` | re-sends the signal to itself | 143 | | `enableShutdownHooks([], { useProcessExit: true })` | calls `process.exit(0)` | 0 | `useProcessExit` exists so that the process `exit` event fires, which some asynchronous log transports need to flush their buffers. The option's own documentation warns that it changes the exit code, may keep other libraries' signal handlers from running, and can change how an orchestrator reads the termination. ## Why it is opt-in The documentation is explicit: the listeners consume memory, and when several Nest applications run in one Node process, as in parallel test runs, Node can warn about too many listeners. So the framework leaves the choice to the application's bootstrap file rather than to every test that creates an app. ## Diagnosing a skipped cleanup When cleanup does not happen on a real stop, check in this order: 1. **Is `enableShutdownHooks()` called** in the production bootstrap file, and not only in a test helper? 2. **Does the signal list include `SIGTERM`?** A list written for local development, such as `['SIGINT']`, silently drops it. 3. **Does the signal reach the Node process at all?** A wrapper process in front of Node may not forward it; that is a process-management concern, not Nest's. 4. **Do the hooks finish inside the grace period?** If teardown outlives it, the platform kills the process and the later hooks never run. 5. **Is it Windows?** The documentation states `SIGTERM` never works there, while `SIGINT` can be expected to work. 6. **Is the class request-scoped?** Request-scoped classes receive no lifecycle hooks at all. ## The interview point The clean answer names the mechanism: `app.close()` runs the hooks directly, a signal runs them only through listeners that `enableShutdownHooks()` installs, and those listeners are disabled by default for a stated cost. A strong answer adds how the process then ends, and why a narrowed signal list brings the bug back. It also explains why the tests were misleading. A test suite that ends with `app.close()` exercises the hooks themselves, but never the path from a signal to those hooks, so the one line that wires a signal to the sequence goes untested. A cheap guard is a smoke test that starts the built app in a child process, sends it `SIGTERM`, and asserts on a log line written from `onApplicationShutdown()`; it catches a missing call or a narrowed signal list before a deploy does.

  • In NestJS, why might a team pass `{ useProcessExit: true }` to `enableShutdownHooks()`, and what does it cost?
    It makes Nest call `process.exit(0)` after the hooks instead of re-sending the signal, so the process `exit` event fires and asynchronous log transports can flush. The cost is a changed exit status, 0 instead of 143 for `SIGTERM`, other libraries' signal handlers may not run, and the orchestrator may read the stop differently.
  • What does NestJS do if a second `SIGTERM` arrives while its shutdown hooks are still running?
    It ignores it. The signal listener checks whether a shutdown is already under way, from a signal or an explicit `app.close()`, and returns without starting a second teardown; callers share the one in-flight shutdown. The platform's grace period, not a second signal, decides how long the hooks get.
  • Where should `enableShutdownHooks()` be called in a NestJS app?
    In the production bootstrap, after `NestFactory.create()` and normally before `app.listen()`, so the listeners exist from the moment the app can receive traffic. Calling it in each test is usually unnecessary, because tests call `app.close()` themselves and many apps in one process would pile up listeners.

  • Nest listens for SIGTERM by default, so cleanup always runs.
  • Passing a signal list adds to the defaults instead of replacing them.
  • After the hooks Nest leaves the process running until the platform kills it.
  • enableShutdownHooks is free, so every test app should call it.
  • useProcessExit keeps the 143 exit status for SIGTERM.