Skip to content

fix(microservices): count every failed rmq connection attempt - #18204

Merged
kamilmysliwiec merged 2 commits into
nestjs:masterfrom
maxymlyskov:fix/count-failed-rmq-connection-attempts
Oct 20, 2026
Merged

kamilmysliwiec merged 2 commits into
nestjs:masterfrom
maxymlyskov:fix/count-failed-rmq-connection-attempts

Conversation

@maxymlyskov

Copy link
Copy Markdown
Contributor

PR Checklist

Please check if your PR fulfills the following requirements:

PR Type

What kind of change does this PR introduce?

  • Bugfix
  • Feature
  • Code style update (formatting, local variables)
  • Refactoring (no functional changes, no api changes)
  • Build related changes
  • CI related changes
  • Other... Please describe:

What is the current behavior?

ServerRMQ.start() binds its connectFailed handler with once (server-rmq.ts L183-L207). amqp-connection-manager 5.0.0 emits connectFailed after every failed attempt, waits reconnectTimeInSeconds and connects again, until close(). So the handler counts the first failure, connectionAttempts goes to 1, and the handler is gone.

With maxConnectionAttempts above 1, ++this.connectionAttempts === maxConnectionAttempts never becomes true. close() and settleListenCallback(err) never run and the listen callback is never called. NestMicroservice.listen() wraps that callback in a promise, so app.listen() stays pending while the manager keeps reconnecting in the background, and every failure after the first one goes unlogged.

The option came in #10042 bound with on. The v11 refactor (3dfc7fc) changed it to once, and the unit tests only used maxConnectionAttempts: 1 with a stubbed client.once that never detaches, so they couldn't catch it.

Real amqp-connection-manager 5.0.0 on master, nothing listening on the port, reconnectTimeInSeconds: 0.2:

PROBE [base] maxConnectionAttempts=3 reconnect=200ms | after 4 s: failed attempts=20 | listen: NOT SETTLED | manager still retrying=true
PROBE [base] maxConnectionAttempts=1 reconnect=200ms | after 4 s: failed attempts=1 | listen: callback(err: connect ECONNREFUSED 127.0.0.1:57419) after 2 ms | manager still retrying=false
PROBE [base] app.listen() with maxConnectionAttempts=3, broker down: STILL PENDING after 10 s

Issue Number: N/A

Steps to reproduce

  1. npx vitest run packages/microservices/test/server/server-rmq.spec.ts -t "when the connection attempts run out" on this branch with server-rmq.ts reverted to master
  2. Expected: with maxConnectionAttempts: 3, the listen callback is called once, with the third error
  3. Actual (master):
 FAIL  packages/microservices/test/server/server-rmq.spec.ts > ServerRMQ > listen > when the connection attempts run out > should call the callback once the last of several attempts fails
AssertionError: expected "vi.fn()" to be called once with arguments: [ Error: ECONNREFUSED ]
 Test Files  1 failed (1)
      Tests  1 failed | 2 passed | 63 skipped (66)

What is the new behavior?

The handler is bound with on again, with a one-line comment saying why. On the Nth failure it closes the manager and calls the listen callback with that error. A later event would make the counter N+1, which never matches, and settleListenCallback has already cleared the callback. close() cancels the manager's retry anyway, so no more events come in.

INFINITE (the default) and the reconnect case (this.channel set) still return before counting, as before. maxConnectionAttempts: 1 behaves the same.

Same probe on the fix:

PROBE [branch] maxConnectionAttempts=3 reconnect=200ms | after 4 s: failed attempts=3 | listen: callback(err: connect ECONNREFUSED 127.0.0.1:57419) after 428 ms | manager still retrying=false
PROBE [branch] maxConnectionAttempts=1 reconnect=200ms | after 4 s: failed attempts=1 | listen: callback(err: connect ECONNREFUSED 127.0.0.1:57419) after 5 ms | manager still retrying=false
PROBE [branch] app.listen() with maxConnectionAttempts=3, broker down: rejected (connect ECONNREFUSED 127.0.0.1:57419) after 753 ms

Left as is: connectionAttempts isn't reset in listen(), so a second listen() on the same ServerRMQ instance after a failed one keeps the old count. Master does the same. ServerMqtt resets it there, but I kept this PR to the hang.

Does this PR introduce a breaking change?

  • Yes
  • No

One change you'll see in logs: with infinite attempts (the default) or while reconnecting, every failed attempt is logged again (CONNECTION_FAILED_MESSAGE plus the error), where master logs only the first. That's the behaviour from #10042 and what ServerMqtt does. The status stream goes through distinctUntilChanged, so subscribers don't get a repeated disconnected.

Other information

ServerMqtt's maxConnectionAttempts (#17734) counts every error with client.on(ERROR, …) (server-mqtt.ts L317-L343), rmq now counts the same way.

In server-rmq.spec.ts the "when the connection attempts run out" block makes client a real EventEmitter (plus createChannel) in one beforeEach, so once really detaches. The 2 existing limit-1 tests now emit connectFailed on it, assertions unchanged, and pass on master and on the fix. The new limit-3 test expects no callback after 2 failures and exactly one callback with the third error.

On Node v22.23.3: server-rmq.spec.ts 66/66. The nest-microservice, server-factory, server-grpc, server-kafka and server-rmq specs: 256 passed, 0 failed on the fix, 255 passed, 1 failed (the new test) on master. Whole unit suite: 4800 passed, 1 failed on the fix, 4799 passed, 2 failed on master; the one failing on both is the NO_COLOR serialise case in logger.service.spec.ts. prettier and oxlint clean.

amqp-connection-manager emits "connectFailed" after every failed
attempt and keeps reconnecting. Since the v11 refactor, ServerRMQ binds
its handler with once(), so only the first failure is counted and a
maxConnectionAttempts above 1 is never reached. listen() then never
settles while the broker is down.

Bind the handler with on() again, as nestjs#10042 did when it added the
option. The handler already ignores events after the limit through
settleListenCallback.
The counter was never reset, so a listen() after a failed one started above maxConnectionAttempts and never reached it.
@kamilmysliwiec
kamilmysliwiec merged commit a6cc71a into nestjs:master Oct 20, 2026
4 checks 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.2.0 | 12.3.1 |
| npm        | @nestjs/core             | 12.2.0 | 12.3.1 |
| npm        | @nestjs/platform-express | 12.2.0 | 12.3.1 |


## [v12.3.1](nestjs/nest@v12.3.0...v12.3.1)



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

#### v12.3.0 (2026-10-27)

##### Features

- `platform-node`
  - [#18063](nestjs/nest#18063) feat(node): add a native node http platform adapter ([@kamilmysliwiec](https://github.com/kamilmysliwiec))

##### Bug fixes

- `common`
  - [#18289](nestjs/nest#18289) fix(common): report the detected file type in file type errors ([@DenisCDev](https://github.com/DenisCDev))
  - [#18246](nestjs/nest#18246) fix(common): avoid throwing for arrow prototype constructors ([@fengxueweilai](https://github.com/fengxueweilai))
  - [#18220](nestjs/nest#18220) fix(common): abort the response when a streamable file fails midway ([@thekhegay](https://github.com/thekhegay))
- `core`
  - [#18276](nestjs/nest#18276) fix(core): run middleware once for routes that differ only in version ([@OmBhandwaldar](https://github.com/OmBhandwaldar))
  - [#18262](nestjs/nest#18262) fix(core): tolerate sse request sockets without tuning methods ([@SnowingFox](https://github.com/SnowingFox))
  - [#18252](nestjs/nest#18252) fix(core): read the url protocol from the server ([@thekhegay](https://github.com/thekhegay))
  - [#18254](nestjs/nest#18254) fix(core): name the array and index of undefined module entries ([@thekhegay](https://github.com/thekhegay))
  - [#18235](nestjs/nest#18235) fix(core): discover classes by each of their discovery decorators ([@OmBhandwaldar](https://github.com/OmBhandwaldar))
  - [#18216](nestjs/nest#18216) fix(core): read the abort on error option of the app being called ([@thekhegay](https://github.com/thekhegay))
  - [#18209](nestjs/nest#18209) fix(core): let middleware exclusions cover prefix-excluded routes ([@thekhegay](https://github.com/thekhegay))
  - [#18210](nestjs/nest#18210) fix(core): honor abortOnError passed to select() ([@Cayan](https://github.com/Cayan))
  - [#18215](nestjs/nest#18215) fix(core): subscribe to handler observables from other rxjs copies ([@koreahghg](https://github.com/koreahghg))
  - [#18201](nestjs/nest#18201) fix(core): read a quoted media type version in the middleware exclusions ([@hktitof](https://github.com/hktitof))
  - [#18200](nestjs/nest#18200) fix(core): resolve request-scoped forward refs for concurrent requests ([@maxymlyskov](https://github.com/maxymlyskov))
- `common`, `microservices`, `platform-ws`
  - [#18285](nestjs/nest#18285) fix(ws,microservices): load packages where bundlers can see them ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
- `common`, `microservices`, `websockets`
  - [#18272](nestjs/nest#18272) fix(common): keep one route param per argument in an overriding method ([@maxymlyskov](https://github.com/maxymlyskov))
- `platform-express`
  - [#18264](nestjs/nest#18264) fix(express): map unsupported multipart content types to 415 ([@seren-wib](https://github.com/seren-wib))
  - [#18234](nestjs/nest#18234) fix(express): end a head response for an empty streamable file ([@spokodev](https://github.com/spokodev))
  - [#18232](nestjs/nest#18232) fix(express): leave 5xx http-errors errors unmapped so they are logged ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
  - [#18214](nestjs/nest#18214) fix(platform-express): map http-errors exceptions to HttpException in Express adapter ([@okxint](https://github.com/okxint))
  - [#18199](nestjs/nest#18199) fix(express): send the standard body for an exception wrapping an error ([@KAPUIST](https://github.com/KAPUIST))
- `platform-fastify`
  - [#18253](nestjs/nest#18253) fix(fastify): send object error bodies with a json content type ([@maxymlyskov](https://github.com/maxymlyskov))
  - [#18240](nestjs/nest#18240) fix(fastify): leave 5xx fastify errors unmapped so they are logged ([@thekhegay](https://github.com/thekhegay))
  - [#18239](nestjs/nest#18239) fix(fastify): map 4xx http-errors errors to http exceptions ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
  - [#18226](nestjs/nest#18226) fix(fastify): listen on a file descriptor ([@thekhegay](https://github.com/thekhegay))
  - [#18217](nestjs/nest#18217) fix(fastify): run cors before nest middleware ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
- `core`, `platform-express`, `platform-fastify`, `platform-socket.io`, `platform-ws`, `websockets`
  - [#18251](nestjs/nest#18251) fix(core,express,fastify,ws,socket.io): load adapters with an older core ([@thekhegay](https://github.com/thekhegay))
- `microservices`
  - [#18250](nestjs/nest#18250) fix(microservices): re-arm the redis retries on a new listen ([@hktitof](https://github.com/hktitof))
  - [#18255](nestjs/nest#18255) fix(microservices): report a nats connection that gave up reconnecting ([@thekhegay](https://github.com/thekhegay))
  - [#18249](nestjs/nest#18249) fix(microservices): do not emit a trailing null to kafka requesters ([@thekhegay](https://github.com/thekhegay))
  - [#18256](nestjs/nest#18256) fix(microservices): let a retriable exception keep travelling ([@hktitof](https://github.com/hktitof))
  - [#18238](nestjs/nest#18238) fix(microservices): retry the tcp server again after close and listen ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
  - [#18223](nestjs/nest#18223) fix(microservices): clear the tcp retry timer when a new listen starts ([@hktitof](https://github.com/hktitof))
  - [#18221](nestjs/nest#18221) fix(microservices): honor mqtt topic filter boundaries ([@fabric0de](https://github.com/fabric0de))
  - [#18229](nestjs/nest#18229) fix(microservices): let only the exact message handler answer a request ([@maxymlyskov](https://github.com/maxymlyskov))
  - [#18211](nestjs/nest#18211) fix(microservices): fail the request when its last reply cannot be sent ([@maxymlyskov](https://github.com/maxymlyskov))
  - [#18206](nestjs/nest#18206) fix(microservices): reset the tcp retry attempts on each listen ([@hktitof](https://github.com/hktitof))
  - [#18204](nestjs/nest#18204) fix(microservices): count every failed rmq connection attempt ([@maxymlyskov](https://github.com/maxymlyskov))
  - [#18197](nestjs/nest#18197) fix(microservices): send the record headers of nats as message headers ([@hktitof](https://github.com/hktitof))

##### Dependencies

- `platform-express`
  - [#18268](nestjs/nest#18268) fix(deps): update dependency multer to v2.5.0 \[security] ([@renovate\[bot\]](https://github.com/apps/renovate))
- `common`
  - [#18257](nestjs/nest#18257) fix(deps): update dependency file-type to v22.2.0 ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
- `platform-fastify`
  - [#18219](nestjs/nest#18219) fix(deps): update dependency [@fastify/middie](https://github.com/fastify/middie) to v9.3.6 ([@renovate\[bot\]](https://github.com/apps/renovate))

##### Committers: 16

- Abdellatif Anaflous ([@hktitof](https://github.com/hktitof))
- Daniel Pinto ([@Cayan](https://github.com/Cayan))
- Denis Scarabelli ([@DenisCDev](https://github.com/DenisCDev))
- Junpei Zhang ([@pei711](https://github.com/pei711))
- Kamil Mysliwiec ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
- Luke Son ([@KAPUIST](https://github.com/KAPUIST))
- Maksym Lyskov ([@maxymlyskov](https://github.com/maxymlyskov))
- Om Bhandwaldar ([@OmBhandwaldar](https://github.com/OmBhandwaldar))
- Roman Khegay ([@thekhegay](https://github.com/thekhegay))
- Spoko Dev ([@spokodev](https://github.com/spokodev))
- [@fengxueweilai](https://github.com/fengxueweilai)
- [@okxint](https://github.com/okxint)
- snowingfox ([@SnowingFox](https://github.com/SnowingFox))
- yooseong ([@seren-wib](https://github.com/seren-wib))
- 김정현 (Kim JungHyeon) ([@fabric0de](https://github.com/fabric0de))
- 한국 ([@koreahghg](https://github.com/koreahghg))
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.

2 participants