skip to content

In a NestJS 12 order service, why does ClientProxy.send() deliver nothing until subscribed, while emit() publishes immediately?

level: middleimportance: should knowfreq 35%

answer

  1. cold versus hot
  2. who subscribes to the Observable
  3. controllers resolve Observables for you
  4. firstValueFrom plus timeout

basics

~10 s

ClientProxy.send() returns a cold Observable: the request is published only when something subscribes, and again for each subscription. emit() returns a hot Observable that dispatches the event immediately, whether or not anyone subscribes.

solid answer

~40 s

`send()` is request-response, so its Observable wraps the whole exchange: connect, publish the packet, wait for the reply. It is **cold**: nothing happens until a subscriber arrives, and each new subscription sends the message again. Returning it from an HTTP controller works because Nest resolves an Observable result itself with `lastValueFrom()`; calling it inside a service and dropping the result sends nothing. In a service, write `await firstValueFrom(this.client.send(...).pipe(timeout(5000)))`. `emit()` is fire-and-forget: the proxy connects and dispatches at once through a hot, already-connected Observable, so the event leaves even if you ignore the return value, although only a subscriber sees a dispatch error. Both connect lazily on first use; awaiting `client.connect()` in `onApplicationBootstrap()` surfaces a bad address at boot.

code

typescript · 23 lines
typescript
import { Inject, Injectable } from '@nestjs/common';
import { ClientProxy } from '@nestjs/microservices';
import { firstValueFrom, timeout } from 'rxjs';

@Injectable()
export class OrdersService {
  constructor(@Inject('INVENTORY_SERVICE') private readonly inventory: ClientProxy) {}

  async place(order: { id: string; sku: string; qty: number }) {
    // cold: published when firstValueFrom subscribes
    const stock = await firstValueFrom(
      this.inventory
        .send<{ available: number }>({ cmd: 'check_stock' }, { sku: order.sku })
        .pipe(timeout(5000)),
    );
    if (stock.available < order.qty) {
      throw new Error(`not enough stock for ${order.sku}`);
    }
    // hot: dispatched now, although the result is ignored
    this.inventory.emit('order_placed', order);
    return order;
  }
}

go deeper

for a junior

Recall that send() is for request-response and emit() for events, and that both return Observables rather than plain values.

for a middle

Explain cold versus hot: send() publishes per subscription, emit() publishes at once. Show firstValueFrom with timeout in a service, and why returning send() from a controller already works.

for a senior

Diagnose the classic 'stock check never arrives' report from a discarded send(), spot double subscriptions that run a handler twice, and fail fast at boot with connect() in onApplicationBootstrap().

for a principal

Set the house rule for calling other services: every send() bounded by a timeout, request-response only where the caller truly needs the answer, and events wherever a reply is not needed.

## Two methods, two contracts `ClientProxy`, from `@nestjs/microservices`, is the producer side of Nest's transport layer. The usual way to get one is to import `ClientsModule.register([{ name: 'INVENTORY_SERVICE', transport: Transport.TCP }])` and inject it with `@Inject('INVENTORY_SERVICE')`: the `name` is the **injection token**, and `transport` defaults to `Transport.TCP` when omitted. The proxy offers two calls: - `send(pattern, data)` for request-response, matched by a `@MessagePattern()` handler. - `emit(pattern, data)` for events, matched by an `@EventPattern()` handler. Both return an RxJS `Observable`, which is where the confusion starts: the two return values look alike and behave in opposite ways. ## Why send() is cold A **cold** Observable does no work until something subscribes, and does the work again for each subscriber. `send()` is built that way on purpose. Its Observable stands for the whole exchange: make sure the connection exists, publish the packet, then wait for the reply, or for several replies if the remote handler returns an Observable. Until a subscriber exists there is nobody to hand a reply to, so nothing is published. Three rules follow: 1. **Somebody must subscribe.** Calling `this.client.send(...)` inside a service and discarding the result sends nothing at all. 2. **Each subscription is a new request.** Subscribing twice runs the remote handler twice, which matters when that handler has side effects. 3. **Returning it from an HTTP controller is fine.** Nest's router resolves an Observable result with `lastValueFrom()` before it writes the response, so the framework subscribes for you. In a service, convert the Observable explicitly and bound the wait: ```ts const stock = await firstValueFrom( this.inventory .send<{ available: number }>({ cmd: 'check_stock' }, { sku }) .pipe(timeout(5000)), ); ``` `firstValueFrom()` takes the first reply, and `lastValueFrom()` waits for the stream to complete and keeps the last one. Without `timeout()` a call to a service that never answers can wait indefinitely; with it, the Observable errors with a `TimeoutError` that you can turn into a 503 or a retry. ## Why emit() is hot An event has no reply, so there is nothing to wait for. `emit()` therefore returns a **hot** Observable: it is built from a connectable source that is connected before `emit()` returns, so the proxy connects and dispatches the event straight away, whether or not anyone subscribes. Subscribing is still useful for one thing: a dispatch failure, such as an unreachable server, is only visible to a subscriber. ## The connection behind the proxy - The proxy is **lazy**: it connects just before the first `send()` or `emit()` and reuses that connection for later calls. - To fail at boot instead of on the first request, `await this.client.connect()` in `onApplicationBootstrap()`; `connect()` rejects when the connection cannot be made. - Clients created through `ClientsModule` are closed for you when the application is closed, through their `onApplicationShutdown()` hook. - `ClientsModule.registerAsync()` builds the options from injected providers, and `isGlobal: true` makes the registered clients injectable everywhere. - A `null` or `undefined` pattern or payload makes both methods error with `InvalidMessageException` before anything is sent, so an event with no data still needs a value such as `{}`. - The type parameter in `send<{ available: number }>()` only types the reply for the compiler. Nothing checks the shape at runtime, so a reply from an older version of the inventory service arrives exactly as that service serialized it. ## Side by side | | `send()` | `emit()` | |---|---|---| | Message style | request-response | event | | Observable | cold | hot | | Published when | a subscriber arrives, once per subscriber | immediately | | Emits | the handler's reply values | no reply from any handler; completes once dispatched | | Typical use | `firstValueFrom()` plus `timeout()`, or return it from a controller | call and move on; subscribe only to observe failure | ## The bug this explains The classic report reads: the inventory service never logs the stock check, but the order-placed events arrive fine. Both calls look identical in the order service, and both use the same proxy and the same connection. The difference is the subscription. The `send()` result was assigned to a variable, or ignored, inside a service method; the `emit()` result was ignored too, but `emit()` does not need a subscriber. Wrapping the `send()` in `firstValueFrom()` fixes it, and adding `timeout()` keeps the next outage from hanging the HTTP request that triggered the call.

  • In NestJS, what goes wrong if two parts of the code subscribe to the same send() Observable?
    Because the Observable is cold, each subscription repeats the whole exchange: two packets go out and the remote `@MessagePattern()` handler runs twice. For a read that only costs a round trip; for a handler with side effects it duplicates them. Subscribe once, by awaiting `firstValueFrom()` and passing the value around, or share the result with an operator such as `shareReplay()`.
  • Why would a NestJS service call client.connect() in onApplicationBootstrap()?
    `ClientProxy` connects lazily, just before the first `send()` or `emit()`, so a wrong host or a missing server only shows up when the first real request fails. Awaiting `this.client.connect()` in `onApplicationBootstrap()` moves that to startup: `connect()` rejects when the connection cannot be made, and the application fails to boot instead of failing a user's request.
  • How do you stop a NestJS send() call from waiting forever when the remote service is down?
    Pipe the Observable through RxJS `timeout()`, for example `this.client.send(pattern, data).pipe(timeout(5000))`. If no reply arrives within five seconds, the Observable errors with a `TimeoutError`, which you catch and map to a 503, a fallback value or a retry. Without it, the HTTP request that triggered the call waits as long as the transport does.

  • send() publishes the request as soon as the method is called.
  • If you ignore emit()'s return value, the event is never published.
  • Subscribing twice to one send() Observable reuses a single request.
  • ClientProxy opens its connection when the module is instantiated.
  • Returning send() from an HTTP controller leaves the request unsent.