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.

Overview - 图1

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 request-response and event-based messaging. This makes it easy to switch from one transport layer to another — for example to leverage the specific reliability or performance features of a particular transport layer — without impacting your application code.

Installation

To start building microservices, first install the required package:

  1. $ npm i --save @nestjs/microservices

Getting started

To instantiate a microservice, use the createMicroservice() method of the NestFactory class:

  1. @@filename(main)
  2. import { NestFactory } from '@nestjs/core';
  3. import { Transport } from '@nestjs/microservices';
  4. import { ApplicationModule } from './app.module';
  5. async function bootstrap() {
  6. const app = await NestFactory.createMicroservice(ApplicationModule, {
  7. transport: Transport.TCP,
  8. });
  9. app.listen(() => console.log('Microservice is listening'));
  10. }
  11. bootstrap();

info Hint Microservices use the TCP transport layer by default.

The second argument of the createMicroservice() method is an options object. This object may consist of two members:

transport Specifies the transporter (for example, 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, MQTT, etc.), see the relevant chapter for a description of the available options.

host Connection hostname
port Connection port
retryAttempts Number of times to retry message
retryDelay Delay between message retry attempts (ms)

Patterns

Microservices recognize both messages and events by patterns. A pattern is a plain value, for example, a literal object or a string. Patterns are automatically serialized and sent over the network along with the data portion of a message. In this way, message senders and consumers can coordinate which requests are consumed by which handlers.

Request-response

The request-response message style is useful when you need to exchange messages between various external services. With this paradigm, you can be certain that the service has actually received the message (without the need to manually implement a message ACK protocol). However, the request-response paradigm is not always the best choice. For example, streaming transporters that use log-based persistence, such as Kafka or NATS streaming, are optimized for solving a different range of issues, more aligned with an event messaging paradigm (see event-based messaging below for more details).

To enable the request-response message type, Nest creates two logical channels - one is responsible for transferring the data while the other waits for incoming responses. For some underlying transports, such as NATS, this dual-channel support is provided out-of-the-box. For others, Nest compensates by manually creating separate channels. There can be overhead for this, so if you do not require a request-response message style, you should consider using the event-based method.

To create a message handler based on the request-response paradigm use the @MessagePattern() decorator, which is imported from the @nestjs/microservices package.

  1. @@filename(math.controller)
  2. import { Controller } from '@nestjs/common';
  3. import { MessagePattern } from '@nestjs/microservices';
  4. @Controller()
  5. export class MathController {
  6. @MessagePattern({ cmd: 'sum' })
  7. accumulate(data: number[]): number {
  8. return (data || []).reduce((a, b) => a + b);
  9. }
  10. }
  11. @@switch
  12. import { Controller } from '@nestjs/common';
  13. import { MessagePattern } from '@nestjs/microservices';
  14. @Controller()
  15. export class MathController {
  16. @MessagePattern({ cmd: 'sum' })
  17. accumulate(data) {
  18. return (data || []).reduce((a, b) => a + b);
  19. }
  20. }

In the above code, the accumulate() message handler listens for messages that fulfill the cmd: 'sum' pattern. The message handler takes a single argument, the data passed from the client. In this case, the data is an array of numbers which are to be accumulated.

Asynchronous responses

Message handlers are able to respond either synchronously or asynchronously. Hence, async methods are supported.

  1. @@filename()
  2. @MessagePattern({ cmd: 'sum' })
  3. async accumulate(data: number[]): Promise<number> {
  4. return (data || []).reduce((a, b) => a + b);
  5. }
  6. @@switch
  7. @MessagePattern({ cmd: 'sum' })
  8. async accumulate(data) {
  9. return (data || []).reduce((a, b) => a + b);
  10. }

A message handler is also able to return an Observable, in which case the result values will be emitted until the stream is completed.

  1. @@filename()
  2. @MessagePattern({ cmd: 'sum' })
  3. accumulate(data: number[]): Observable<number> {
  4. return from([1, 2, 3]);
  5. }
  6. @@switch
  7. @MessagePattern({ cmd: 'sum' })
  8. accumulate(data: number[]): Observable<number> {
  9. return from([1, 2, 3]);
  10. }

In the example above, the message handler will respond 3 times (with each item from the array).

Event-based

While the request-response method is ideal for exchanging messages between services, it is less suitable when your message style is event-based - when you just want to publish events without waiting for a response. In that case, you do not want the overhead required by request-response for maintaining two channels.

Suppose you would like to simply notify another service that a certain condition has occurred in this part of the system. This is the ideal use case for the event-based message style.

To create an event handler, we use the @EventPattern() decorator, which is imported from the @nestjs/microservices package.

  1. @@filename()
  2. @EventPattern('user_created')
  3. async handleUserCreated(data: Record<string, unknown>) {
  4. // business logic
  5. }
  6. @@switch
  7. @EventPattern('user_created')
  8. async handleUserCreated(data) {
  9. // business logic
  10. }

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 which has been sent over the network).

Decorators

In more sophisticated scenarios, you may want to access more information about the incoming request. For example, in the case of NATS with wildcard subscriptions, you may want to get the original subject that the producer has sent the message to. Likewise, in Kafka you may want to access the message headers. In order to accomplish that, you can use built-in decorators as follows:

  1. @@filename()
  2. @MessagePattern('time.us.*')
  3. getDate(@Payload() data: number[], @Ctx() context: NatsContext) {
  4. console.log(`Subject: ${context.getSubject()}`); // e.g. "time.us.east"
  5. return new Date().toLocaleTimeString(...);
  6. }
  7. @@switch
  8. @Bind(Payload(), Ctx())
  9. @MessagePattern('time.us.*')
  10. getDate(data, context) {
  11. console.log(`Subject: ${context.getSubject()}`); // e.g. "time.us.east"
  12. return new Date().toLocaleTimeString(...);
  13. }

info Hint @Payload(), @Ctx() and NatsContext are imported from @nestjs/microservices.

Client

A client Nest application can exchange messages or publish events to a Nest microservice using the ClientProxy class. This class defines several methods, such as send() (for request-response messaging) and emit() (for event-driven messaging) that let you communicate with a remote microservice. Obtain an instance of this class in one of the following ways.

One technique is to import the ClientsModule, which exposes the static register() method. This method takes an argument which is an array of objects representing microservices. Each such object has a name property as well as a microservice-specific options object.

The name property serves as an injection token that can be used to inject an instance of a ClientProxy where needed. The value of the name property, as an injection token, can be an arbitrary string or JavaScript symbol, as described here.

The options object has the same properties we saw in the createMicroservice() method earlier.

  1. ClientsModule.register([
  2. { name: 'MATH_SERVICE', transport: Transport.TCP },
  3. ]),

Once the module has been imported, we can inject 'MATH_SERVICE' using the @Inject() decorator.

  1. constructor(
  2. @Inject('MATH_SERVICE') private readonly client: ClientProxy,
  3. ) {}

info Hint The ClientsModule and ClientProxy classes are imported from the @nestjs/microservices package.

As is sometimes the case, we may need to fetch the microservice configuration from another service (say a ConfigService), rather than hard-coding it in our client application. To do this, we can use the ClientProxyFactory class to register a custom provider (which provides a ClientProxy instance):

  1. {
  2. provide: 'MATH_SERVICE',
  3. useFactory: (configService: ConfigService) => {
  4. const mathSvcOptions = configService.getMathSvcOptions();
  5. return ClientProxyFactory.create(mathSvcOptions);
  6. },
  7. inject: [ConfigService],
  8. }

info Hint The ClientProxyFactory is imported from the @nestjs/microservices package.

Another option is to use the @Client() property decorator.

  1. @Client({ transport: Transport.TCP })
  2. client: ClientProxy;

info Hint The @Client() decorator is imported from the @nestjs/microservices package.

Using the @Client() decorator is not the preferred technique, as it is harder to test and harder to share a client instance.

The ClientProxy is lazy. It doesn’t initiate a connection immediately. Instead, it will be established before the first microservice call, and then reused across each subsequent call. However, if you want to delay the application bootstrapping process until a connection is established, you can manually initiate a connection using the ClientProxy object’s connect() method inside the OnApplicationBootstrap lifecycle hook.

  1. @@filename()
  2. async onApplicationBootstrap() {
  3. await this.client.connect();
  4. }

If the connection cannot be created, the connect() method will reject with the corresponding error object.

Sending messages

The ClientProxy exposes a send() method. This method is intended to call the microservice and returns an Observable with its response. Thus, we can subscribe to the emitted values easily.

  1. @@filename()
  2. accumulate(): Observable<number> {
  3. const pattern = { cmd: 'sum' };
  4. const payload = [1, 2, 3];
  5. return this.client.send<number>(pattern, payload);
  6. }
  7. @@switch
  8. accumulate() {
  9. const pattern = { cmd: 'sum' };
  10. const payload = [1, 2, 3];
  11. return this.client.send(pattern, payload);
  12. }

The send() method takes two arguments, pattern and payload. The pattern should match the one defined in a @MessagePattern() decorator. The payload is a message that we want to transmit to the remote microservice. This method returns a cold Observable, which means that you have to explicitly subscribe to it before the message will be sent.

Publishing events

To send an event, use the ClientProxy object’s emit() method. This method publishes an event to the message broker.

  1. @@filename()
  2. async publish() {
  3. this.client.emit<number>('user_created', new UserCreatedEvent());
  4. }
  5. @@switch
  6. async publish() {
  7. this.client.emit('user_created', new UserCreatedEvent());
  8. }

The emit() method takes two arguments, pattern and payload. The patternshould match the one defined in an @EventPattern() decorator. The payload is an event payload that we want to transmit to the remote microservice. This method returns a hot Observable (unlike the cold Observable returned by send()), which means that whether or not you explicitly subscribe to the observable, the proxy will immediately try to deliver the event.

Scopes

For people coming from different programming language backgrounds, it might be unexpected to learn that in Nest, almost everything is shared across incoming requests. We have a connection pool to the database, singleton services with global state, etc. Remember that Node.js doesn’t follow the request/response Multi-Threaded Stateless Model in which every request is processed by a separate thread. Hence, using singleton instances is fully safe for our applications.

However, there are edge-cases when request-based lifetime of the handler may be the desired behavior, for instance per-request caching in GraphQL applications, request tracking or multi-tenancy. Learn how to control scopes here.

Request-scoped handlers and providers can inject RequestContext using the @Inject() decorator in combination with CONTEXT token:

  1. import { Injectable, Scope, Inject } from '@nestjs/common';
  2. import { CONTEXT, RequestContext } from '@nestjs/microservices';
  3. @Injectable({ scope: Scope.REQUEST })
  4. export class CatsService {
  5. constructor(@Inject(CONTEXT) private readonly ctx: RequestContext) {}
  6. }

This provides access to the RequestContext object, which has two properties:

  1. export interface RequestContext<T = any> {
  2. pattern: string | Record<string, any>;
  3. data: T;
  4. }

The data property is the message payload sent by the message producer. The pattern property is the pattern used to identify an appropriate handler to handle the incoming message.