Skip to content

fix(core): clean up repeated shutdown signal listeners - #17625

Merged
kamilmysliwiec merged 3 commits into
nestjs:masterfrom
Raj4478:fix/17623-shutdown-signal-cleanup
Sep 14, 2026
Merged

kamilmysliwiec merged 3 commits into
nestjs:masterfrom
Raj4478:fix/17623-shutdown-signal-cleanup

Conversation

@Raj4478

@Raj4478 Raj4478 commented Aug 30, 2026

Copy link
Copy Markdown
Contributor

Summary

  • track the cleanup handler registered for each shutdown signal
  • remove every registered process listener when the application closes
  • share the received-signal guard across registrations so concurrent signals run shutdown hooks once
  • add regression coverage for repeated and separate calls to enableShutdownHooks()

Testing

  • focused shutdown regression tests (3 passed)
  • existing process exit/kill shutdown tests (2 passed)
  • tsc -b packages/core --pretty false
  • oxlint packages/core/nest-application-context.ts packages/core/test/nest-application-context.spec.ts
  • Prettier check and git diff --check
  • public-API verification on Windows:
    • registering SIGTERM twice: listener count 0 -> 1 -> 0
    • registering SIGTERM and SIGINT separately: both 0 -> 1 -> 0

Closes #17623

@kamilmysliwiec

Copy link
Copy Markdown
Member

a single call like enableShutdownHooks(['sigterm', 'SIGTERM']) (the Set-dedup runs before uppercase/trim normalization) registers two listeners but remembers only one, leaking a listener that the old activeShutdownSignals-based removal loop used to clean up

@kamilmysliwiec

Copy link
Copy Markdown
Member

and also Opus feedback: the promoted receivedSignal flag is never reset anywhere so it latches permanently once a cleanup fires, and activeShutdownSignals is now a redundant, never-cleared duplicate of the Map's keys (dropping it in favor of shutdownCleanupRefs.has() would fix the silent no-op when re-enabling hooks after close()). Also worth noting: the new "repeated registration" test passes on pre-PR code, so it doesn't actually guard the fix. The remaining findings are test-code cleanups.

Track each registered cleanup handler and share shutdown state across
registrations so close removes every process listener and concurrent signals run
hooks once.

Closes nestjs#17623
@Raj4478
Raj4478 force-pushed the fix/17623-shutdown-signal-cleanup branch from 706fd6f to 2b44718 Compare August 31, 2026 14:11
@Raj4478

Raj4478 commented Aug 31, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the feedback. I updated the PR to address each point:

  • normalize and trim signals before deduplicating them
  • use shutdownCleanupRefs as the single source of truth instead of activeShutdownSignals
  • reset the shared received-signal guard when starting a fresh registration cycle, allowing hooks to be re-enabled after close() or a completed signal cleanup
  • replace the ineffective repeated-registration test with regressions for normalized aliases, re-enabling after close, and re-enabling after signal cleanup
  • retain coverage ensuring separately registered concurrent signals execute shutdown only once

I also rebased onto the latest master. The seven relevant shutdown tests, core TypeScript build, Prettier, oxlint, and diff checks pass locally. The updated commit is 2b447180a5b14ed3af00e5c0dcb27b157ab60197.

@micalevisk micalevisk left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the follow-up, the source changes look correct to me and all three points from the earlier comments are addressed. I ran the unit spec (31 passing), the integration/hooks e2e after a full build (5 passing), lint/prettier, and a handful of targeted source mutations against the new tests.

One thing is still missing before this can go in: there is no regression test for the headline case of #17623, i.e. the same signal registered by two separate enableShutdownHooks() calls. The "normalize" test covers aliases within one call and "separate calls" covers different signals, but if I delete the .filter(signal => !this.shutdownCleanupRefs.has(signal)) line the whole spec still passes, even though that mutant leaks the first listener on close() (the second call overwrites the Map entry and registers a second listener). See the inline suggestion; I confirmed that test fails on master, fails on the mutant, and passes on this branch.

A couple of smaller test-quality points inline (two tests that can pass vacuously, and the repeated finally cleanup). No behaviour regressions found: re-enabling after close(), all-listener removal on the signal path, and running hooks once across registrations all match what the issue asks for and are not breaking.

Out of scope for this PR, but worth a follow-up issue: close() does not check receivedSignal, so calling it while a signal-triggered shutdown is in flight still runs the hook sequence twice (the adjacent behaviour from #14998), and options passed on a later call for an already-registered signal are silently ignored.

Add a regression for the same signal registered by separate calls and
assert listener counts before and after cleanup. Share baseline cleanup,
use the handler map consistently, and document registration behavior.
Reset the shutdown guard alongside listener cleanup.
@Raj4478

Raj4478 commented Sep 13, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the detailed review, @micalevisk. Addressed the feedback in commit "a454e680562cfe43f4b96bfcb9171cf48d0eeb30":

  • Added the missing regression for registering the same signal through two separate calls. Confirmed it fails against the pre-PR source and when the duplicate-signal filter is removed, and passes with the fix.
  • Added listener-count assertions before "close()" in the separate-signals and re-enable-after-close tests, plus baseline checks after signal-triggered cleanup.
  • Extracted "removeListenersNotIn()" and consistently retrieved cleanup handlers from "shutdownCleanupRefs".
  • Documented per-signal idempotency and re-enabling after "close()". Also moved the signal-guard reset into "unsubscribeFromProcessSignals()", as suggested.

Validation on Linux with Node 24.19.0:

  • 2,796 unit tests passed, including all 32 application-context tests.
  • 29 integration tests passed across "integration/hooks" and "integration/graceful-shutdown", including real process signals and in-flight HTTP requests.
  • Full package build, changed-file lint, Prettier, and "git diff --check" passed. Full lint reported one existing warning in the unchanged "packages/websockets/socket-module.ts".

The existing manifest/lockfile mismatch prevented "npm ci", so validation used "npm install --legacy-peer-deps --no-package-lock --no-audit --no-fund". No dependency files changed. "NO_COLOR" was unset because the logger spec expects ANSI colors

Promoting the received-signal guard to instance scope stopped concurrent
signals from tearing the context down twice, but `close()` never took part
in it. A signal delivered while a programmatic `close()` was still awaiting
its hooks re-entered the cleanup handler with the guard clear and ran
`callDestroyHook`, `callBeforeShutdownHook`, `dispose` and
`callShutdownHook` a second time, concurrently.

Replace the boolean with the in-flight shutdown promise itself and share it
between both entry points, so whichever arrives second awaits the first
instead of starting its own teardown. The sequence moves into
`runShutdownSequence`, which `close()` and the signal handler now reach
through `shutdown()` rather than each keeping their own copy of the six
lifecycle calls.

Clearing the promise once the cycle settles also unwedges the failure path:
previously a throw skipped `unsubscribeFromProcessSignals`, leaving the flag
latched and the registry populated, so the reset in `enableShutdownHooks`
could never fire and the context ignored every later signal.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@kamilmysliwiec
kamilmysliwiec merged commit ddbb455 into nestjs:master Sep 14, 2026
1 check passed
ttt43ttt pushed a commit to NoDevelopers/ts-monorepo that referenced this pull request Nov 22, 2026
| datasource | package                  | from   | to     |
| ---------- | ------------------------ | ------ | ------ |
| npm        | @nestjs/common           | 12.0.1 | 12.1.0 |
| npm        | @nestjs/core             | 12.0.1 | 12.1.0 |
| npm        | @nestjs/platform-express | 12.0.1 | 12.1.0 |


## [v12.1.0](https://github.com/nestjs/nest/releases/tag/v12.1.0)

##### v12.1.0 (2026-09-23)

##### Bug fixes

- `core`
  - [#17838](nestjs/nest#17838) fix(core): inherit optional ctor params when the ctor is not redeclared ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
  - [#17819](nestjs/nest#17819) fix(core): name the module when metadata entries are invalid ([@thekhegay](https://github.com/thekhegay))
- `microservices`
  - [#17828](nestjs/nest#17828) fix(microservices): let the redis client retry after a failed connect ([@hktitof](https://github.com/hktitof))
  - [#17810](nestjs/nest#17810) fix(microservices): fail every pending request when a callback throws ([@hktitof](https://github.com/hktitof))

##### Enhancements

- `core`
  - [#17846](nestjs/nest#17846) fix(core): do not skip subsequent middleware after a transient one ([@lehafari](https://github.com/lehafari))
  - [#17840](nestjs/nest#17840) fix(core): preserve route handler names ([@Grmiade](https://github.com/Grmiade))
- `common`, `core`
  - [#17713](nestjs/nest#17713) feat(core): add support for array of global prefixes ([@micalevisk](https://github.com/micalevisk))
  - [#17834](nestjs/nest#17834) feat(common,core): add built-in, adapter-agnostic cookies ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
- `platform-fastify`
  - [#17824](nestjs/nest#17824) fix(fastify): honor Nest forceCloseConnections in initHttpServer ([@xia-chao](https://github.com/xia-chao))
- `common`
  - [#17827](nestjs/nest#17827) fix(common): apply the ParseDatePipe default to every missing value ([@xia-chao](https://github.com/xia-chao))
- `platform-fastify`, `testing`
  - [#17835](nestjs/nest#17835) feat(fastify): add file upload interceptors backed by [@fastify/multipart](https://github.com/fastify/multipart) ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
- `common`, `core`, `platform-fastify`
  - [#17836](nestjs/nest#17836) feat(common,core,fastify): built-in CSRF protection and security headers ([@kamilmysliwiec](https://github.com/kamilmysliwiec))

##### Committers: 9

- Abdellatif Anaflous ([@hktitof](https://github.com/hktitof))
- Alejandro ([@lehafari](https://github.com/lehafari))
- Chris Z ([@haimingZZ](https://github.com/haimingZZ))
- Johnny J. Huirilef Millán ([@johnnyhuirilef](https://github.com/johnnyhuirilef))
- Jérémy Fauvel ([@Grmiade](https://github.com/Grmiade))
- Kamil Mysliwiec ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
- Micael Levi L. Cavalcante ([@micalevisk](https://github.com/micalevisk))
- Roman Khegay ([@thekhegay](https://github.com/thekhegay))
- Xia Chao ([@xia-chao](https://github.com/xia-chao))


## [v12.0.4](https://github.com/nestjs/nest/releases/tag/v12.0.4)

##### v12.0.4 (2026-09-21)

##### Bug fixes

- `microservices`
  - [#17816](nestjs/nest#17816) fix(microservices): let the kafka client retry after a failed connect ([@Xch4rt](https://github.com/Xch4rt))
  - [#17786](nestjs/nest#17786) fix(microservices): fail pending rmq requests on client close ([@johnnyhuirilef](https://github.com/johnnyhuirilef))
  - [#17802](nestjs/nest#17802) fix(microservices): fail pending nats requests on client close ([@hktitof](https://github.com/hktitof))
  - [#17803](nestjs/nest#17803) fix(microservices): handle missing grpc package namespace gracefully ([@Se3do](https://github.com/Se3do))
  - [#17799](nestjs/nest#17799) fix(microservices): share the processing hook envelope across transports ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
  - [#17797](nestjs/nest#17797) fix(microservices): close the kafka request-response span exactly once ([@MingLin1995](https://github.com/MingLin1995))
  - [#17794](nestjs/nest#17794) fix(microservices): close the request-response span exactly once ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
  - [#17785](nestjs/nest#17785) fix(microservices): route message handler rejections to handleError ([@hktitof](https://github.com/hktitof))
- `core`
  - [#17821](nestjs/nest#17821) fix(core): hang on sparse factory inject array ([@xia-chao](https://github.com/xia-chao))

##### Enhancements

- `platform-express`
  - [#17818](nestjs/nest#17818) Fix: merge multer `limits` key-by-key instead of overriding it wholesale ([@mdrezuanislamridoy](https://github.com/mdrezuanislamridoy))
- `common`
  - [#17780](nestjs/nest#17780) fix(common): mark parse date pipe options as optional ([@Chy-Zaber-Bin-Zahid](https://github.com/Chy-Zaber-Bin-Zahid))

##### Dependencies

- `common`
  - [#17793](nestjs/nest#17793) fix(deps): update dependency file-type to v22.1.1 ([@renovate\[bot\]](https://github.com/apps/renovate))
- `platform-fastify`
  - [#17791](nestjs/nest#17791) fix(deps): update dependency fastify to v5.12.5 ([@renovate\[bot\]](https://github.com/apps/renovate))

##### Committers: 10

- Abdellatif Anaflous ([@hktitof](https://github.com/hktitof))
- Chowdhury Zaber Bin Zahid ([@Chy-Zaber-Bin-Zahid](https://github.com/Chy-Zaber-Bin-Zahid))
- Imad - Prakticode ([@prakticode](https://github.com/prakticode))
- Johnny J. Huirilef Millán ([@johnnyhuirilef](https://github.com/johnnyhuirilef))
- Kamil Mysliwiec ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
- MD. Ridoy Babu ([@mdrezuanislamridoy](https://github.com/mdrezuanislamridoy))
- Ming ([@MingLin1995](https://github.com/MingLin1995))
- Mohammed Said ([@Se3do](https://github.com/Se3do))
- Pablo Gutiérrez ([@Xch4rt](https://github.com/Xch4rt))
- Xia Chao ([@xia-chao](https://github.com/xia-chao))


## [v12.0.3](https://github.com/nestjs/nest/releases/tag/v12.0.3)

##### v12.0.3 (2026-09-15)

##### Bug fixes

- `microservices`
  - [#17766](nestjs/nest#17766) fix(microservices): always run the kafka processing end hook ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
  - [#17757](nestjs/nest#17757) fix(microservices): fail pending requests on client close ([@hktitof](https://github.com/hktitof))
  - [#17746](nestjs/nest#17746) fix(microservices): bound memory held for a TCP peer ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
  - [#17745](nestjs/nest#17745) fix(microservices): destroy open TCP sockets on shutdown ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
- `common`
  - [#17738](nestjs/nest#17738) fix(common): validate uuid version and variant when no version is set ([@otnc](https://github.com/otnc))
  - [#17761](nestjs/nest#17761) fix(common): invoke proto-key stripping hook via this in transform ([@koreahghg](https://github.com/koreahghg))

##### Dependencies

- `platform-express`
  - [#17762](nestjs/nest#17762) fix(deps): update dependency multer to v2.4.0 ([@renovate\[bot\]](https://github.com/apps/renovate))
- `common`
  - [#17753](nestjs/nest#17753) fix(deps): update dependency file-type to v22.1.0 ([@renovate\[bot\]](https://github.com/apps/renovate))

##### Committers: 4

- Abdellatif Anaflous ([@hktitof](https://github.com/hktitof))
- Kamil Mysliwiec ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
- otoneko. ([@otnc](https://github.com/otnc))
- 한국 ([@koreahghg](https://github.com/koreahghg))


## [v12.0.2](https://github.com/nestjs/nest/releases/tag/v12.0.2)

##### v12.0.2 (2026-09-14)

##### Bug fixes

- `platform-socket.io`, `platform-ws`
  - [#17666](nestjs/nest#17666) fix(socket.io): keep the message stream alive when a handler throws ([@hktitof](https://github.com/hktitof))
- `microservices`
  - [#17728](nestjs/nest#17728) fix(microservices): detach signal listeners of connected microservices ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
  - [#17671](nestjs/nest#17671) fix(microservices): fail requests whose reply subscription is rejected ([@samuelmbabhazi](https://github.com/samuelmbabhazi))
  - [#17670](nestjs/nest#17670) fix(microservices): do not treat foreign JSON as an RPC envelope ([@xia-chao](https://github.com/xia-chao))
  - [#17644](nestjs/nest#17644) fix(microservices): don't flatten plain handler results with pre-request hooks ([@iamolegga](https://github.com/iamolegga))
  - [#17641](nestjs/nest#17641) fix(microservices): run the mqtt listen callback once ([@johnnyhuirilef](https://github.com/johnnyhuirilef))
- `common`
  - [#17710](nestjs/nest#17710) fix(common): collapse duplicate internal slashes in `normalizePath` ([@Asadshah7950](https://github.com/Asadshah7950))
  - [#17655](nestjs/nest#17655) fix(common): validate UUID v3 variant ([@gwagjiug](https://github.com/gwagjiug))
  - [#17702](nestjs/nest#17702) fix(common): treat empty string as array input in ParseArrayPipe ([@xia-chao](https://github.com/xia-chao))
- `core`
  - [#17667](nestjs/nest#17667) fix(core): discover factory providers with discovery decorators ([@hktitof](https://github.com/hktitof))
  - [#17709](nestjs/nest#17709) fix(core): avoid treating error instances with `statusCode` as http errors ([@Asadshah7950](https://github.com/Asadshah7950))
  - [#17625](nestjs/nest#17625) fix(core): clean up repeated shutdown signal listeners ([@Raj4478](https://github.com/Raj4478))
- `platform-fastify`
  - [#17705](nestjs/nest#17705) fix(fastify): derive neutral version when accept header is absent ([@Gaurav1112](https://github.com/Gaurav1112))
  - [#17699](nestjs/nest#17699) fix(fastify): send responses for exceptions thrown from middleware ([@micalevisk](https://github.com/micalevisk))

##### Enhancements

- `microservices`
  - [#17734](nestjs/nest#17734) feat(microservices): add maxConnectionAttempts to ServerMqtt ([@kamilmysliwiec](https://github.com/kamilmysliwiec))

##### Dependencies

- `platform-fastify`
  - [#17729](nestjs/nest#17729) fix(deps): update dependency fastify to v5.12.4 ([@renovate\[bot\]](https://github.com/apps/renovate))

##### Committers: 16

- Abdellatif Anaflous ([@hktitof](https://github.com/hktitof))
- Alexey Solovyov ([@lyohaplotinka](https://github.com/lyohaplotinka))
- Asad Ali Shah ([@Asadshah7950](https://github.com/Asadshah7950))
- Gyeonghun Park ([@Gyeonghun-Park](https://github.com/Gyeonghun-Park))
- Johnny J. Huirilef Millán ([@johnnyhuirilef](https://github.com/johnnyhuirilef))
- Kamil Mysliwiec ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
- Kumar Gaurav ([@Gaurav1112](https://github.com/Gaurav1112))
- Micael Levi L. Cavalcante ([@micalevisk](https://github.com/micalevisk))
- Ming ([@MingLin1995](https://github.com/MingLin1995))
- Mohammed Said ([@Se3do](https://github.com/Se3do))
- Rajeshwar Singh  ([@Raj4478](https://github.com/Raj4478))
- Xia Chao ([@xia-chao](https://github.com/xia-chao))
- [@iamolegga](https://github.com/iamolegga)
- cui fliter ([@cuishuang](https://github.com/cuishuang))
- samuel mbabhazi ([@samuelmbabhazi](https://github.com/samuelmbabhazi))
- 곽지욱 ([@gwagjiug](https://github.com/gwagjiug))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

enableShutdownHooks() leaves a process signal listener behind when called more than once

3 participants