In NestJS 12, what must change when an order service's microservice transport moves from TCP to NATS or Kafka?
answer
- handlers stay, wiring changes
- both ends of the wire
- a driver package per transporter
- a context class per transporter
- Kafka reply topics
basics
~20 sThe transport and options objects change on both sides: createMicroservice() or connectMicroservice() on the consumer, ClientsModule on the producer, plus the transporter's driver package. Handlers and patterns mostly stay; @Ctx() types and quirks such as Kafka reply topics change.
solid answer
~40 sNest hides each transporter behind one interface, so `@MessagePattern()`/`@EventPattern()` handlers and `send()`/`emit()` calls are written the same way. What changes is configuration: the `transport` (a `Transport` member such as `NATS` or `KAFKA`) and its `options` in `createMicroservice()` or `connectMicroservice()`, and the matching entry in `ClientsModule.register()`, because producer and consumer must agree. Each transporter needs its driver: in Nest 12 the NATS transporter loads `@nats-io/transport-node` instead of the old `nats` package, and Kafka needs `kafkajs`. Handlers that read `@Ctx()` change type (`NatsContext.getSubject()`, `KafkaContext.getTopic()`). Semantics leak through too: a Kafka `send()` needs `subscribeToResponseOf()` for its reply topic, and gRPC uses `@GrpcMethod()` with a proto file rather than generic patterns.
code
typescript · 17 linesimport { Inject, Injectable, OnModuleInit } from '@nestjs/common';
import { ClientKafkaProxy } from '@nestjs/microservices';
@Injectable()
export class StockClient implements OnModuleInit {
constructor(@Inject('INVENTORY_SERVICE') private readonly client: ClientKafkaProxy) {}
async onModuleInit() {
// request-response over Kafka needs the derived reply topic
this.client.subscribeToResponseOf('inventory.check');
await this.client.connect();
}
check(sku: string) {
return this.client.send<{ available: number }>('inventory.check', { sku });
}
}go deeper
Recall that the transport is picked with the Transport enum in createMicroservice() and in ClientsModule, and that the handlers themselves do not change.
Explain everything that does change: both ends' transport and options, the driver package, @Ctx() context types, and per-transport steps such as Kafka's subscribeToResponseOf().
Anticipate what the abstraction hides: Redis pub/sub drops unheard messages, RabbitMQ's noAck default, NATS queue groups, Kafka reply topics, and the Nest 12 NATS v3 driver swap during an upgrade.
Judge whether a transport switch is a configuration change or a contract change; gRPC and handlers that depend on @Ctx() turn it into the latter, which affects how a team plans the move.
## What the transport layer promises Nest calls each built-in transport implementation a **transporter**, and it hides all of them behind one canonical interface for both message styles. Handlers declared with `@MessagePattern()` and `@EventPattern()`, and calls made through `ClientProxy.send()` and `emit()`, are written the same way whichever transporter carries them. The stated aim is that a team can move to another transport layer, for its reliability or performance features, without changing application code. That promise covers handlers and calls. It does not cover configuration, installed dependencies, the context object a handler may read, or the delivery semantics each transporter brings with it. ## The configuration that must change A transporter is chosen in two places, and the two must agree: 1. **The consumer**: the options object passed to `NestFactory.createMicroservice()`, or to `app.connectMicroservice()` in a hybrid app, has a `transport` member (one of `Transport.TCP`, `REDIS`, `NATS`, `MQTT`, `GRPC`, `RMQ`, `KAFKA`) and a transporter-specific `options` object. 2. **Every producer**: each `ClientsModule.register()` or `registerAsync()` entry names the same `transport` with compatible `options`. ```ts // consumer: the inventory service const app = await NestFactory.createMicroservice<MicroserviceOptions>(InventoryModule, { transport: Transport.NATS, options: { servers: ['nats://localhost:4222'], queue: 'inventory' }, }); await app.listen(); // producer: in the order service's module ClientsModule.register([ { name: 'INVENTORY_SERVICE', transport: Transport.NATS, options: { servers: ['nats://localhost:4222'] } }, ]); ``` When `transport` is omitted, both `createMicroservice()` and `ClientsModule` fall back to TCP, so forgetting one side leaves that side on TCP rather than raising an error. ## Each transporter needs its driver `@nestjs/microservices` does not bundle the client libraries; it loads the driver when the transporter starts, and fails if the package is missing. | `Transport` member | Driver package(s) to install | Default address | |---|---|---| | `TCP` | none (built on Node's networking) | `localhost:3000` | | `REDIS` | `ioredis` | `localhost:6379` | | `NATS` | `@nats-io/transport-node` | `nats://localhost:4222` | | `MQTT` | `mqtt` | `mqtt://localhost:1883` | | `RMQ` | `amqplib` and `amqp-connection-manager` | `amqp://localhost` | | `KAFKA` | `kafkajs` | `localhost:9092` | | `GRPC` | `@grpc/grpc-js` and `@grpc/proto-loader` | `localhost:5000` | The NATS row is new in Nest 12. Its microservices package targets NATS v3, so the old `nats` package gives way to `@nats-io/transport-node`, Nest serializes NATS packets as JSON strings, and a custom NATS deserializer now receives the whole message object instead of raw bytes. ## Code that reads @Ctx() changes type The `@Ctx()` parameter is a transport-specific context, so any handler that reads it is tied to its transporter: - `TcpContext`, with `getPattern()`. - `RedisContext`, with `getChannel()`. - `NatsContext`, with `getSubject()`, the concrete subject behind a wildcard pattern. - `MqttContext`, with `getTopic()`. - `RmqContext`, with `getMessage()`, `getChannelRef()` and `getPattern()`. - `KafkaContext`, with `getTopic()` and `getMessage()`. ## Semantics that leak through - **Redis** uses pub/sub: a message published while nobody is subscribed is gone, so nothing guarantees that any service handles it. - **RabbitMQ**: `noAck` defaults to `true`; set it to `false` to acknowledge manually through the channel from `context.getChannelRef()`. - **NATS**: the `queue` option subscribes the server with a queue group, NATS's built-in way to load-balance messages across instances. - **Kafka**: request-response uses a request topic and a reply topic, by default the request topic plus `.reply`. The producer's `ClientKafkaProxy` must call `subscribeToResponseOf()` for each request topic before it connects, or `send()` fails because the client consumer did not subscribe to the reply topic. A pattern doubles as the Kafka topic name, so string patterns that are valid topic names, such as `'inventory.check'`, are the safe choice. Nest 12 also lets Kafka handlers take a `RegExp` pattern, which the other transporters do not accept. - **gRPC** is the outlier. The contract is a `.proto` file (`package` and `protoPath` options), handlers use `@GrpcMethod()`, and producers inject a `ClientGrpc` and call `getService()`. Moving to gRPC is a contract change, not a configuration change. ## What stays the same The handler methods, the `@Payload()` parameters, and the `send()` and `emit()` calls in the producers keep their shape, and so do most patterns; Kafka is the exception, because its patterns are topic names. The enhancers around the handlers stay too: guards, pipes, interceptors and RPC exception filters bind the same way on every transporter, and on the pattern-based transporters an `RpcException` still reaches a `send()` caller as an error object. ## A migration checklist 1. Install the driver and change `transport` and `options` on the consumer and on every producer. 2. Search for `@Ctx()` and retype or rewrite each use. 3. Add the transporter's extra steps, such as `subscribeToResponseOf()` for Kafka request-response. 4. Re-read the transporter's delivery guarantees before relying on them. 5. On an upgrade to Nest 12 that keeps NATS, swap the driver package and review any custom NATS serializer or deserializer.
- Why does a NestJS Kafka client need subscribeToResponseOf() for send() but not for emit()?Request-response over Kafka uses two topics: the request topic and a reply topic derived from it, by default with `.reply` appended. `subscribeToResponseOf('inventory.check')` adds that reply topic to the client's consumer, and it must run before `connect()`. Events have no reply, so `emit()` needs no reply topic at all.
- Can one NestJS hybrid app listen on TCP and NATS at once and bind a handler to only one of them?Yes. Call `connectMicroservice()` once per transporter, then pass the transport as the second argument of the decorator, as in `@MessagePattern('time.us.*', Transport.NATS)`. Without that argument the handler is registered for every connected listener.
- After the Nest 12 upgrade, why might a custom NATS deserializer break?Nest 12 moved the NATS transporter to NATS v3. Nest now serializes NATS packets as JSON strings, and a custom NATS deserializer receives the whole NATS message object instead of a raw `Uint8Array`, so it should read the payload with `msg.json()` rather than decoding bytes by hand.
- Switching transporter means rewriting every @MessagePattern() handler.
- Only the consumer's createMicroservice() options need to change.
- Nest 12's NATS transporter still loads the nats package.
- Kafka request-response in Nest works with no extra client setup.
- A NestJS gRPC service needs no proto file, only @MessagePattern() strings.
Assumes NestJS 12, whose microservices package targets NATS v3 and loads @nats-io/transport-node instead of the nats package; Kafka RegExp patterns are also new in 12.