In a NestJS app, should a message-broker connection be closed in onModuleDestroy, beforeApplicationShutdown or onApplicationShutdown, and why?
answer
- where the HTTP server closes
- requests may still be in flight
- stop new work, then close
- last hook after dispose
basics
~20 sClose it in onApplicationShutdown when requests may still use it: NestJS calls that hook only after closing the HTTP server. Use onModuleDestroy or beforeApplicationShutdown to stop taking new work while the server is still open.
solid answer
~40 sDuring `app.close()` NestJS runs `onModuleDestroy()`, then `beforeApplicationShutdown(signal)`, then closes what it owns, the HTTP server, WebSocket gateways and connected microservice listeners, and only then calls `onApplicationShutdown(signal)`. In the first two hooks the server is still handling requests, and a handler may still publish to the broker. So stop consuming new messages and stop background loops there, and close the connection itself in `onApplicationShutdown()`, when no request can reach it any more. Every hook is awaited, so `await client.close()` holds the sequence until it settles; a rejected hook is logged and the rest still run. On the Express adapter, `return503OnClosing: true` in the app options makes new requests get 503 as soon as shutdown starts.
go deeper
Remember that NestJS closes the HTTP server between beforeApplicationShutdown and onApplicationShutdown, so only the last hook runs with it closed.
Explain the split: stop new work in the first two shutdown hooks, close shared connections in onApplicationShutdown, and that each hook is awaited.
Show you can trace a closed-connection error during deploys back to a teardown placed in onModuleDestroy while requests were still being served.
Make the teardown order a reviewed convention per resource type, and budget its total time against the platform's grace period.
## The terminating phase step by step When `app.close()` runs, or a signal arrives after `app.enableShutdownHooks()`, NestJS runs one fixed sequence. Reading it from the source of `NestApplicationContext` and `NestApplication`: 1. Wait for any initialization still in progress to finish. 2. Let the HTTP adapter prepare: the Express adapter marks itself as shutting down (this only changes responses when `return503OnClosing` is on). 3. Call **`onModuleDestroy()`** on every component, module by module. 4. Call **`beforeApplicationShutdown(signal)`** the same way. 5. **Dispose**: close the WebSocket gateways, the microservices module, the HTTP adapter (which closes the HTTP server and waits for it) and every connected microservice. 6. Call **`onApplicationShutdown(signal)`**. 7. Remove the process signal listeners that `enableShutdownHooks()` installed. The important line is step 5: it sits **between** the second and the third hook. ## What each shutdown hook is for | Hook | HTTP server at that moment | Typical work | |---|---|---| | `onModuleDestroy()` | still open, still serving | stop consumers, timers and schedulers; refuse new jobs | | `beforeApplicationShutdown(signal)` | still open | wait for your own in-flight jobs to finish, flush buffers | | `onApplicationShutdown(signal)` | closed | close connections and pools that requests used | `onModuleDestroy()` takes no arguments; the other two receive the signal name, such as `'SIGTERM'`, or `undefined` after a plain `app.close()`. You can pass one yourself with `app.close('SIGTERM')`. ## Closing a broker connection Picture a service that consumes order messages from a broker and whose HTTP handlers also publish to it. A safe split is: - In `onModuleDestroy()`, **stop consuming**: cancel the subscription so no new message starts work. - In `beforeApplicationShutdown()`, wait for the message handlers already running to finish, if your client tracks them. - In `onApplicationShutdown()`, **close the connection**. By now Nest has closed the HTTP server, so no request handler can still be publishing. Closing the connection in `onModuleDestroy()` instead is a classic bug: the server is still handling requests, and any handler that publishes after that point fails with a closed-connection error. ```typescript import { Injectable, OnApplicationShutdown, OnModuleDestroy } from '@nestjs/common'; import { BrokerClient } from './broker.client.js'; @Injectable() export class OrderEvents implements OnModuleDestroy, OnApplicationShutdown { constructor(private readonly broker: BrokerClient) {} async onModuleDestroy(): Promise<void> { await this.broker.stopConsuming(); // no new messages start work } async onApplicationShutdown(signal?: string): Promise<void> { await this.broker.close(); // the HTTP server is already closed here } } ``` ## Order and failures - **Awaited**: each hook's promise settles before the sequence moves on, so a slow close delays the whole shutdown. - **Failures do not stop the sequence**: if a shutdown hook throws or rejects, Nest logs the error and keeps calling the remaining hooks, so one broken teardown does not skip the others. - **Modules in reverse**: the shutdown hooks visit modules in the reverse of the boot order, the root module first and the most deeply imported modules last. - **Time budget**: the platform that sent the signal usually allows a fixed grace period before it kills the process outright; teardown that outlives it never finishes. - **Not the process exit**: `app.close()` does not end the process; on the signal path, Nest ends it after the hooks. ## Refusing new requests early By default the HTTP server keeps accepting requests until step 5. Passing `return503OnClosing: true` to `NestFactory.create()` makes the Express adapter answer new requests with `503 Service Unavailable` and `Connection: close` from step 2 on, while requests already in progress complete. How the underlying server drains connections is the runtime's subject, not Nest's. ## Mistakes interviewers listen for - **Closing shared connections in `onModuleDestroy()`**: requests are still being served, so a handler that touches the connection afterwards fails mid-request. - **Doing all teardown in `onApplicationShutdown()`**: consumers keep pulling new messages until the very end, so work starts that can never finish before the process exits. - **Fire-and-forget teardown**: calling `client.close()` without returning or awaiting its promise lets Nest move on, and the process may end before the close completes. - **Assuming one hook per class**: a single provider may implement all three shutdown hooks, and splitting stop-consuming from close-connection inside one class is often the cleanest design.
- In NestJS, what does `return503OnClosing` change during shutdown?With `return503OnClosing: true` in the options passed to `NestFactory.create()`, the Express adapter marks itself as shutting down at the start of the sequence and answers every new request with 503 and `Connection: close`, while requests already in progress finish. Without it, new requests keep being served until Nest closes the HTTP server between `beforeApplicationShutdown()` and `onApplicationShutdown()`.
- Why should a NestJS shutdown hook catch its own errors if NestJS already logs them?Nest logs a failed shutdown hook and moves on, which protects the other hooks but leaves your resource half closed and the cause only in the log. Catching inside the hook lets you retry, force-close, or record a precise message about which resource did not close, which matters when a pod is about to disappear.
Closing a restaurant: first stop seating new guests and taking orders, then let the diners already at the tables finish and leave, and only then turn off the kitchen gas. Turning off the gas first leaves seated guests with nothing.
- onModuleDestroy runs after the HTTP server has stopped serving requests.
- Closing every connection in onModuleDestroy is safe because requests are finished.
- One failed shutdown hook makes Nest skip all the remaining hooks.
- onModuleDestroy receives the shutdown signal name as its argument.
- app.close() terminates the Node process once the hooks finish.