Overview
In addition to traditional (sometimes called monolithic) application architectures, Nest natively supports the microservice architectural style of development. Most of the concepts discussed elsewhere in this documentation, such as dependency injection, decorators, exception filters, pipes, guards, and interceptors, apply equally to microservices. Wherever possible, Nest abstracts implementation details so that the same components can run across HTTP-based platforms, WebSockets, and microservices. This section covers the aspects of Nest that are specific to microservices.
In Nest, a microservice is fundamentally an application that uses a different transport layer than HTTP.

Nest supports several built-in transport layer implementations, called transporters, which are responsible for transmitting messages between different microservice instances. Most transporters natively support both request-response and event-based message styles. Nest abstracts the implementation details of each transporter behind a canonical interface for both styles. This lets you switch from one transport layer to another (e.g., to take advantage of the reliability or performance features of a particular transport layer) without changing your application code.
Installation#
To start building microservices, first install the required package:
$ npm i --save @nestjs/microservices
Getting started#
To instantiate a microservice, use the createMicroservice() method of the NestFactory class:
import { NestFactory } from '@nestjs/core';
import { Transport, MicroserviceOptions } from '@nestjs/microservices';
import { AppModule } from './app.module.js';
async function bootstrap() {
const app = await NestFactory.createMicroservice<MicroserviceOptions>(
AppModule,
{
transport: Transport.TCP,
},
);
await app.listen();
}
await bootstrap();
import { NestFactory } from '@nestjs/core';
import { Transport } from '@nestjs/microservices';
import { AppModule } from './app.module.js';
async function bootstrap() {
const app = await NestFactory.createMicroservice(AppModule, {
transport: Transport.TCP,
});
await app.listen();
}
await bootstrap();
Hint Microservices use the TCP transport layer by default.
The second argument of the createMicroservice() method is an options object with two members:
transport | Specifies the transporter (e.g., Transport.NATS) |
options | A transporter-specific options object that determines transporter behavior |
The options object is specific to the chosen transporter. The TCP transporter exposes the properties described below. For other transporters (e.g., Redis or MQTT), see the relevant chapter for a description of the available options.
host | Connection hostname (default: 'localhost'). Starting with NestJS v12.5, an empty value (undefined, null or '') means 'localhost' as well, so a server that other hosts connect to, e.g. one running in a container, has to set '0.0.0.0' or '::' |
port | Connection port (default: 3000) |
retryAttempts | Number of times the server tries to listen again after it closes unexpectedly (default: 0) |
retryDelay | Delay between those attempts (ms) (default: 0) |
serializer | Custom serializer for outgoing messages |
deserializer | Custom deserializer for incoming messages |
socketClass | A custom Socket that extends TcpSocket (default: JsonSocket) |
tlsOptions | Options to configure the TLS protocol (see TLS support) |
maxBufferSize | Maximum length of a single incoming packet, in characters (default: 16 * 1024 * 1024). A packet declaring a greater length is rejected before any of it is buffered, and the connection is dropped. Starting with NestJS v12.5, it applies to each packet, and its default was lowered from 128 * 1024 * 1024. A client applies its own maxBufferSize to the replies it receives |
incompleteMessageTimeout | How long (ms) a peer may stay silent in the middle of a packet before the connection is dropped. Set to 0 to disable (default: 30000) |
messageReceiveTimeout | How long (ms) a peer may take to send a single packet, from its first character to its last, before the connection is dropped. Unlike incompleteMessageTimeout, further reads don't extend it. Set to 0 to disable (default: 300000) |
maxSendBufferSize | Maximum number of response bytes that may be queued for a peer that isn't reading them before the connection is dropped. Set to 0 to disable (default: 128MB) |
drainTimeout | How long (ms) the responses queued for a peer may go without any of them being written out before the connection is dropped. Set to 0 to disable (default: 30000) |
maxConcurrentMessages | How many messages of a single peer may be handled at the same time. A message counts until its handler, and the stream it returned, have settled. Later messages wait, and once more than maxBufferSize characters are waiting, reading from the peer is suspended. If none of the pending messages settles for drainTimeout after that, the connection is dropped. Set to 0 to disable (default: 1000) |
gracefulShutdown | Enables graceful shutdown. When enabled, closing the server keeps the connections that have requests or events being handled open until those are done, and takes no further message from them. The other connections are closed right away (default: false) |
gracePeriod | Longest time before every connection is closed when gracefulShutdown is enabled (ms) (default: 10000) |
A maxBufferSize, incompleteMessageTimeout, messageReceiveTimeout, maxSendBufferSize, drainTimeout or maxConcurrentMessages that isn't a number, such as the NaN that Number() makes of an unset environment variable, gets its default.
Message and Event Patterns#
Microservices recognize both messages and events by patterns. A pattern is a plain value, e.g., a literal object or a string. Patterns are automatically serialized and sent over the network along with the data portion of a message. This way, message senders and consumers can coordinate which requests are consumed by which handlers.
Nest matches an object pattern to its handler by its keys and values, within fixed limits: at most 5 levels of nesting, 20 keys per object (or items per array), keys of up to 256 characters, string values of up to 4096 characters, and 100 keys in the whole pattern. A part of a pattern beyond these limits, or the whole pattern past 100 keys, is replaced with a marker such as [TOO_MANY_KEYS] before it's matched, so keep the patterns of your handlers within them. A pattern that arrives as JSON text longer than 1 MiB is matched as a plain string, without being parsed.
Request-response#
The request-response message style is useful when you need to exchange messages between services. It ensures that the service has actually received the message, without requiring you to implement an acknowledgment protocol manually. However, request-response isn't always the best fit. For example, streaming platforms that use log-based persistence, such as Kafka or NATS JetStream, are optimized for a different set of challenges, more aligned with the event messaging paradigm (see event-based messaging for more details).
To enable the request-response message type, Nest creates two logical channels: one for transferring data and another for waiting for incoming responses. For some underlying transports, like NATS, this dual-channel support is provided out of the box. For others, Nest compensates by creating separate channels manually, which can introduce some overhead. If you don't need the request-response message style, consider using the event-based method instead.
To create a message handler based on the request-response paradigm, use the @MessagePattern() decorator, which is imported from the @nestjs/microservices package. Use this decorator only within controller classes, as they serve as the entry points for your application. The Nest runtime ignores it in providers.
import { Controller } from '@nestjs/common';
import { MessagePattern } from '@nestjs/microservices';
@Controller()
export class MathController {
@MessagePattern({ cmd: 'sum' })
accumulate(data: number[]): number {
return (data || []).reduce((a, b) => a + b);
}
}
import { Controller } from '@nestjs/common';
import { MessagePattern } from '@nestjs/microservices';
@Controller()
export class MathController {
@MessagePattern({ cmd: 'sum' })
accumulate(data) {
return (data || []).reduce((a, b) => a + b);
}
}
In the above code, the accumulate() message handler listens for messages that match the { cmd: 'sum' } message pattern. The message handler takes a single argument, the data passed from the client. In this case, the data is an array of numbers to be accumulated.
Asynchronous responses#
Message handlers can respond either synchronously or asynchronously, so async methods are supported.
@MessagePattern({ cmd: 'sum' })
async accumulate(data: number[]): Promise<number> {
return (data || []).reduce((a, b) => a + b);
}
@MessagePattern({ cmd: 'sum' })
async accumulate(data) {
return (data || []).reduce((a, b) => a + b);
}
A message handler can also return an Observable, in which case the result values are emitted until the stream completes.
@MessagePattern({ cmd: 'sum' })
accumulate(data: number[]): Observable<number> {
return from([1, 2, 3]);
}
@MessagePattern({ cmd: 'sum' })
accumulate(data) {
return from([1, 2, 3]);
}
In the example above, the message handler responds three times, once for each item in the array.
Event-based#
While the request-response method works well for exchanging messages between services, it is less suited to event-based messaging, where you want to publish events without waiting for a response. In such cases, the overhead of maintaining two channels for request-response is unnecessary.
For example, if you want to notify another service that a specific condition has occurred in this part of the system, use the event-based message style.
To create an event handler, use the @EventPattern() decorator, which is imported from the @nestjs/microservices package.
@EventPattern('user_created')
async handleUserCreated(data: Record<string, unknown>) {
// business logic
}
@EventPattern('user_created')
async handleUserCreated(data) {
// business logic
}
Hint You can register multiple event handlers for a single event pattern, and Nest triggers all of them in parallel.
The handleUserCreated() event handler listens for the 'user_created' event. The event handler takes a single argument, the data passed from the client (in this case, an event payload sent over the network).
Additional request details#
In more advanced scenarios, you might need additional details about the incoming request. For instance, when using NATS with wildcard subscriptions, you may want to retrieve the original subject that the producer sent the message to. Similarly, with Kafka, you may need to access the message headers. To do so, use the built-in decorators shown below:
@MessagePattern('time.us.*')
getDate(@Payload() data: number[], @Ctx() context: NatsContext) {
console.log(`Subject: ${context.getSubject()}`); // e.g. "time.us.east"
return new Date().toLocaleTimeString(...);
}
@Bind(Payload(), Ctx())
@MessagePattern('time.us.*')
getDate(data, context) {
console.log(`Subject: ${context.getSubject()}`); // e.g. "time.us.east"
return new Date().toLocaleTimeString(...);
}
Hint@Payload(),@Ctx(), andNatsContextare imported from@nestjs/microservices.
Hint You can also pass a property key to the@Payload()decorator to extract a specific property from the incoming payload object, e.g.,@Payload('id'). To validate the payload against a schema, see microservice pipes.
Client (producer class)#
A client Nest application can exchange messages with, or publish events to, a Nest microservice using the ClientProxy class. This class provides several methods for communicating with a remote microservice, such as send() (for request-response messaging) and emit() (for event-driven messaging). You can obtain an instance of this class in the following ways.
One approach is to import the ClientsModule, which exposes the static register() method. This method takes an array of objects representing microservice transporters. Each object must include a name property, and can include a transport property (if omitted, Nest uses Transport.TCP) and an options property.
The name property acts as an injection token, which you can use to inject an instance of ClientProxy wherever needed. Its value can be any string or JavaScript symbol, as described in non-class-based provider tokens.
The options property is an object with the same properties we saw in the createMicroservice() method earlier.
@Module({
imports: [
ClientsModule.register([
{ name: 'MATH_SERVICE', transport: Transport.TCP },
]),
],
})
Alternatively, use the registerAsync() method if you need to provide configuration or perform other asynchronous processes during setup.
@Module({
imports: [
ClientsModule.registerAsync([
{
imports: [ConfigModule],
name: 'MATH_SERVICE',
useFactory: async (configService: ConfigService) => ({
transport: Transport.TCP,
options: {
host: configService.get('HOST'),
port: configService.get('PORT'),
},
}),
inject: [ConfigService],
},
]),
],
})
Once the module has been imported, use the @Inject() decorator to inject the ClientProxy instance configured for the 'MATH_SERVICE' transporter.
constructor(
@Inject('MATH_SERVICE') private client: ClientProxy,
) {}
Hint TheClientsModuleandClientProxyclasses are imported from the@nestjs/microservicespackage.
At times, you may need to fetch the transporter configuration from another service (such as a ConfigService) rather than hard-coding it in your client application. To do so, register a custom provider using the ClientProxyFactory class. This class provides a static create() method that accepts a transporter options object and returns a customized ClientProxy instance.
@Module({
providers: [
{
provide: 'MATH_SERVICE',
useFactory: (configService: ConfigService) => {
const mathSvcOptions = configService.getMathSvcOptions();
return ClientProxyFactory.create(mathSvcOptions);
},
inject: [ConfigService],
}
]
...
})
Hint TheClientProxyFactoryclass is imported from the@nestjs/microservicespackage.
Another option is to use the @Client() property decorator.
@Client({ transport: Transport.TCP })
client: ClientProxy;
Hint The@Client()decorator is imported from the@nestjs/microservicespackage.
The @Client() decorator isn't the preferred technique, because a client created this way is harder to test and harder to share.
The ClientProxy is lazy. It doesn't initiate a connection immediately. Instead, the connection is established before the first microservice call and reused for each subsequent call. If you want to delay the application bootstrapping process until a connection is established, initiate the connection manually with the ClientProxy object's connect() method inside the onApplicationBootstrap() lifecycle hook.
async onApplicationBootstrap() {
await this.client.connect();
}
If the connection can't be created, the connect() method rejects with the corresponding error object.
Sending messages#
The ClientProxy exposes a send() method, which calls the microservice and returns an Observable with its response.
accumulate(): Observable<number> {
const pattern = { cmd: 'sum' };
const payload = [1, 2, 3];
return this.client.send<number>(pattern, payload);
}
accumulate() {
const pattern = { cmd: 'sum' };
const payload = [1, 2, 3];
return this.client.send(pattern, payload);
}
The send() method takes two arguments, pattern and payload. The pattern should match one defined in a @MessagePattern() decorator. The payload is the message to transmit to the remote microservice. This method returns a cold Observable, which means that you have to subscribe to it explicitly before the message is sent.
Publishing events#
To send an event, use the ClientProxy object's emit() method. This method publishes an event to the message broker.
async publish() {
this.client.emit<number>('user_created', new UserCreatedEvent());
}
async publish() {
this.client.emit('user_created', new UserCreatedEvent());
}
The emit() method takes two arguments, pattern and payload. The pattern should match one defined in an @EventPattern() decorator, while the payload is the event data to transmit to the remote microservice. This method returns a hot Observable (in contrast to the cold Observable returned by send()), which means that the proxy immediately attempts to deliver the event, whether or not you subscribe to the observable.
Request-scoping#
If you come from a different programming language background, it may be surprising that in Nest, most things are shared across incoming requests. This includes the database connection pool, singleton services with global state, and more. Node.js doesn't follow the request/response multi-threaded stateless model, in which each request is processed by a separate thread. As a result, using singleton instances is safe for your applications.
However, there are edge cases where a request-based lifetime for the handler might be desirable, such as per-request caching in GraphQL applications, request tracking, or multi-tenancy. Learn how to control scopes in the injection scopes chapter.
Request-scoped handlers and providers can inject RequestContext using the @Inject() decorator in combination with the CONTEXT token:
import { Injectable, Scope, Inject } from '@nestjs/common';
import { CONTEXT, type RequestContext } from '@nestjs/microservices';
@Injectable({ scope: Scope.REQUEST })
export class CatsService {
constructor(@Inject(CONTEXT) private ctx: RequestContext) {}
}
This provides access to the RequestContext object, which has the following shape:
export interface RequestContext<TData = any, TContext extends BaseRpcContext = any> {
pattern: string | Record<string, any>;
data: TData;
context?: TContext;
getData(): TData;
getPattern(): string | Record<string, any>;
getContext(): TContext;
}
The data property is the message payload sent by the message producer. The pattern property is the pattern used to identify the handler for the incoming message. The context property holds the transporter-specific context object (e.g., NatsContext), the same object that the @Ctx() decorator injects.
Instance status updates#
To get real-time updates on the connection and the state of the underlying driver instance, subscribe to the status stream. This stream provides status updates specific to the chosen driver. For instance, with the TCP transporter (the default), the status stream emits connected and disconnected events.
this.client.status.subscribe((status: TcpStatus) => {
console.log(status);
});
Hint TheTcpStatustype is imported from the@nestjs/microservicespackage.
Similarly, you can subscribe to the server's status stream to receive notifications about the server's status.
const server = app.connectMicroservice<MicroserviceOptions>(...);
server.status.subscribe((status: TcpStatus) => {
console.log(status);
});
Listening to internal events#
In some cases, you might want to listen to internal events emitted by the microservice. For example, you could listen for the error event to trigger additional operations when an error occurs. To do this, use the on() method:
this.client.on('error', (err) => {
console.error(err);
});
Similarly, you can listen to the server's internal events:
server.on<TcpEvents>('error', (err) => {
console.error(err);
});
Hint TheTcpEventstype is imported from the@nestjs/microservicespackage.
With the TCP transporter, starting with NestJS v12.1.1, listeners registered with the client's on() method stay registered until you call close(), so they are also attached to the new socket the client opens on the next send() or emit() call after the connection was closed. Registrations are not deduplicated, so register each listener once rather than again from its callback or after each reconnect.
Underlying driver access#
For more advanced use cases, you may need to access the underlying driver instance, for example, to close the connection manually or to use driver-specific methods. In most cases, however, you shouldn't need to access the driver directly.
To do so, use the unwrap() method, which returns the underlying driver instance. The generic type parameter specifies the type of driver instance you expect.
const netSocket = this.client.unwrap<Socket>();
Here, Socket is a type imported from the net module.
Similarly, you can access the server's underlying driver instance:
const netServer = server.unwrap<Server>();
Handling timeouts#
In distributed systems, microservices are sometimes down or unavailable. To avoid waiting indefinitely, apply a timeout to your microservice calls with the RxJS timeout operator. If the microservice doesn't respond within the specified time, an error is thrown, which you can catch and handle appropriately.
Apply the timeout operator within the pipe:
this.client
.send<TResult, TInput>(pattern, data)
.pipe(timeout(5000));
this.client
.send(pattern, data)
.pipe(timeout(5000));
Hint Thetimeoutoperator is imported from therxjs/operatorspackage.
If the microservice doesn't respond within 5 seconds, the Observable errors with a TimeoutError.
Sending metadata with every message#
To attach a value that is not part of the payload (a correlation id, a tenant, a locale) to every outgoing request and event, register a hook on the client with setOnDispatchHook(). The hook receives each packet right before it goes to the transport and may assign packet.metadata, a record of string values:
client.setOnDispatchHook((packet) => {
packet.metadata = { 'x-correlation-id': getCorrelationId() };
});
Do not replace pattern or data in the hook. On the receiving side, read the values with getMetadata() of the transport context (TcpContext, RedisContext, NatsContext, RmqContext, MqttContext or KafkaContext):
@MessagePattern('orders.create')
create(@Payload() data: CreateOrderDto, @Ctx() context: NatsContext) {
const correlationId = context.getMetadata()?.['x-correlation-id'];
}
TCP and Redis carry the metadata inside the packet. NATS, Kafka, RabbitMQ, MQTT 5 and gRPC carry it as message headers (gRPC: call metadata) under the names given in the hook, and never in the payload. A header set on the record itself, such as with NatsRecordBuilder, RmqRecordBuilder or MqttRecordBuilder, wins over a metadata entry of the same name. MQTT 3 has no header channel, so the metadata does not travel over it.
Hint On NATS, Kafka and RabbitMQ,getMetadata()returns only the headers with a single string value, and on MQTT only the user properties with a single value. Read the others withgetHeaders()(NATS),getMessage()(Kafka, RabbitMQ) orgetPacket()(MQTT).
Tracing a request across services#
Timeouts tell you that a call failed to come back in time. They don't tell you where the time went, and in a system of five services talking over TCP, NATS, and Kafka, that is the question that matters. A gateway request that takes 3 seconds might spend 2.9 of them in a downstream service that nobody suspected, while each service's own logs show that everything looked fine.
The usual fix is to propagate a correlation ID by hand through every transport, then stitch the timelines back together after the fact. NestJS Observe does that stitching for you. Instrument each service with the @nestjs/observe SDK and forward the trace ID on whatever channel the transport already has (a Kafka header, a NATS header, or a field on the TCP payload), and the dashboard reassembles one waterfall spanning every service that participated:

From there, the timeout stops being a mystery. You can see the gateway's send() waiting, the consumer picking up the message (and how long the message waited before that), the query inside the handler that ran long, and the error it eventually threw, with its source lines, all on one clock. Message and event handlers are instrumented automatically, so @MessagePattern() and @EventPattern() handlers show up as operations without any manual span wiring.
Forwarding the trace ID is the one piece that requires application code, because only you know which channel your transport leaves free. See Distributed tracing for the pattern per transport, and the Observability chapter to get set up.
TLS support#
When communicating outside of a private network, encrypt the traffic. The TCP transporter has built-in support for TLS, based on Node's TLS module, which lets you encrypt communication between microservices and their clients.
To enable TLS for a TCP server, you need both a private key and a certificate in PEM format. Add them to the server's options with the tlsOptions property:
import * as fs from 'node:fs';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module.js';
import { MicroserviceOptions, Transport } from '@nestjs/microservices';
async function bootstrap() {
const key = fs.readFileSync('<pathToKeyFile>', 'utf8').toString();
const cert = fs.readFileSync('<pathToCertFile>', 'utf8').toString();
const app = await NestFactory.createMicroservice<MicroserviceOptions>(
AppModule,
{
transport: Transport.TCP,
options: {
tlsOptions: {
key,
cert,
},
},
},
);
await app.listen();
}
await bootstrap();
For a client to communicate securely over TLS, define the tlsOptions object as well, this time with the CA certificate, i.e., the certificate of the authority that signed the server's certificate. This ensures that the client trusts the server's certificate and can establish a secure connection.
import * as fs from 'node:fs';
import { Module } from '@nestjs/common';
import { ClientsModule, Transport } from '@nestjs/microservices';
@Module({
imports: [
ClientsModule.register([
{
name: 'MATH_SERVICE',
transport: Transport.TCP,
options: {
tlsOptions: {
ca: [fs.readFileSync('<pathToCaFile>', 'utf-8').toString()],
},
},
},
]),
],
})
export class AppModule {}
The ca property accepts an array, so you can list several CAs if your setup involves multiple trusted authorities.
Once everything is set up, inject the ClientProxy as usual with the @Inject() decorator. Communication between your microservices is then encrypted, with Node's TLS module handling the encryption details.
For more information, refer to Node's TLS documentation.
Dynamic configuration#
A microservice's transport options are passed to createMicroservice(), before any provider (such as the ConfigService from the @nestjs/config package) can be injected. To configure the microservice with injected providers, pass AsyncMicroserviceOptions instead: Nest resolves the providers listed in inject and passes them to the useFactory function, which returns the transport options.
import { NestFactory } from '@nestjs/core';
import { ConfigService } from '@nestjs/config';
import { AsyncMicroserviceOptions, Transport } from '@nestjs/microservices';
import { AppModule } from './app.module.js';
async function bootstrap() {
const app = await NestFactory.createMicroservice<AsyncMicroserviceOptions>(
AppModule,
{
useFactory: (configService: ConfigService) => ({
transport: Transport.TCP,
options: {
host: configService.get<string>('HOST'),
port: configService.get<number>('PORT'),
},
}),
inject: [ConfigService],
},
);
await app.listen();
}
await bootstrap();
Talking to a server that is not Nest#
Most microservice setups talk to at least one system that knows nothing about Nest: a gateway already in production, a worker written in another language, a queue that other services also consume. The packets that travel over the TCP and Redis transports have a fixed shape, so that system can call a handler and answer a client without the @nestjs/microservices package.
A request has three fields. pattern selects the handler (over Redis, the channel does, as described below), data is what the handler receives, and id ties the reply to its request. The id is a number or a string of at most 256 characters: a request with any other id gets no reply, and the server logs an error.
{ "pattern": "sum", "data": [1, 2], "id": "b7e1c0" }
The reply repeats the id and carries either a response or an err. A successful reply also sets isDisposed, which is what tells a Nest client that the request is over:
{ "id": "b7e1c0", "response": 3, "isDisposed": true }
Without isDisposed the value still reaches the caller, but send() never completes: lastValueFrom() and anything else waiting for the observable to close hangs. When a handler returns a stream, the Nest server sends one reply for each value it emits, and sets isDisposed on the last of them or, when the stream completes after its last value has been sent, in a reply of its own without a response.
A failed request gets an err instead, which ends the request whether isDisposed is set or not:
{ "id": "b7e1c0", "err": { "message": "Division by zero", "status": "error" } }
Leave any other field out of a reply. A Nest client takes a packet with a field it doesn't expect for a payload that isn't a Nest reply, and the whole packet becomes the response.
A packet without an id is dispatched as an event: the handler runs and nothing travels back. That is the shape emit() sends:
{ "pattern": "user_created", "data": { "id": 42 } }
A reply that arrives with a different id, or with none, matches no request, and the caller keeps waiting. send() has no default timeout: unless the caller pipes it through the timeout() operator (see Handling timeouts), it waits until the connection closes, and then fails with a Connection closed error. A pattern can also be an object instead of a string, which Nest matches by its keys and values, with the limits that message and event patterns lists. Over TCP, a Nest client sends such a pattern as an object in a request, but as a string, its route, in an event, where { cmd: 'sum' } arrives as {"cmd":"sum"}. A server that is not Nest should accept both forms.
The TCP transport writes neither packet as bare JSON. JsonSocket, the socket the server and the client share, puts the length of the JSON text first, then a #, then the text itself:
import { connect } from 'node:net';
const packet = JSON.stringify({ pattern: 'sum', data: [1, 2], id: 'b7e1c0' });
const socket = connect({ host: 'localhost', port: 3000 }, () => {
socket.write(`${packet.length}#${packet}`);
});
That length counts the UTF-16 code units of the JSON text, which is what String#length returns in JavaScript, not its bytes. A peer that writes a byte count desynchronizes on any payload with a non-ASCII character, such as an accented letter, and one that counts Unicode code points, as len() does in Python, desynchronizes on characters outside the basic plane, such as emoji.
The Redis transport publishes the packets as plain JSON text, and there the channel a packet is published on selects the handler, not its pattern field. A request or event for the sum pattern is published on the sum channel, and the replies to a request on the sum.reply channel. An object pattern uses its route as the channel name, such as {"cmd":"sum"}.
Over TCP and Redis, the metadata a client attaches with setOnDispatchHook() travels in the packet's metadata field, a record of string values. The other transports carry it as headers, as sending metadata with every message describes.

