0% found this document useful (0 votes)
7 views8 pages

Redis - Microservices - NestJS - A Progressive Node - Js Framework

The document provides an overview of using Redis as a transporter for microservices in NestJS, detailing the publish/subscribe messaging paradigm and the necessary installation steps. It outlines options for configuring the Redis transporter, creating client instances, and accessing additional request information through RedisContext. Additionally, it covers advanced features such as wildcard subscriptions, instance status updates, and listening to internal events.

Uploaded by

ehenokh12
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views8 pages

Redis - Microservices - NestJS - A Progressive Node - Js Framework

The document provides an overview of using Redis as a transporter for microservices in NestJS, detailing the publish/subscribe messaging paradigm and the necessary installation steps. It outlines options for configuring the Redis transporter, creating client instances, and accessing additional request information through RedisContext. Additionally, it covers advanced features such as wildcard subscriptions, instance status updates, and listening to internal events.

Uploaded by

ehenokh12
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

2/24/25, 1:27 PM Redis - Microservices | NestJS - A progressive Node.

js framework

dark_mode

https://docs.nestjs.com/microservices/redis 1/8
2/24/25, 1:27 PM Redis - Microservices | NestJS - A progressive Node.js framework

Redis
The Redis transporter implements the publish/subscribe messaging paradigm and leverages the Pub/Sub feature
of Redis. Published messages are categorized in channels, without knowing what subscribers (if any) will eventually
receive the message. Each microservice can subscribe to any number of channels. In addition, more than one
channel can be subscribed to at a time. Messages exchanged through channels are fire-and-forget, which means
that if a message is published and there are no subscribers interested in it, the message is removed and cannot be
recovered. Thus, you don't have a guarantee that either messages or events will be handled by at least one service.
A single message can be subscribed to (and received) by multiple subscribers.

Installation
To start building Redis-based microservices, first install the required package:

$ npm i --save ioredis

Overview
To use the Redis transporter, pass the following options object to the createMicroservice() method:

main.ts JS

const app = await NestFactory.createMicroservice<MicroserviceOptions>(AppModule, { content_copy


https://docs.nestjs.com/microservices/redis 2/8
2/24/25, 1:27 PM Redis - Microservices | NestJS - A progressive Node.js framework
transport: Transport.REDIS,
options: {
host: 'localhost',
port: 6379,
},
});

HINT
The Transport enum is imported from the @nestjs/microservices package.

Options
The options property is specific to the chosen transporter. The Redis transporter exposes the properties
described below.

host Connection url

port Connection port

retryAttempts Number of times to retry message (default: 0 )

retryDelay Delay between message retry attempts (ms) (default: 0 )

wildcards Enables Redis wildcard subscriptions, instructing transporter to use


psubscribe / pmessage under the hood. (default: false )

All the properties supported by the official ioredis client are also supported by this transporter.

Client
Like other microservice transporters, you have several options for creating a Redis ClientProxy instance.

One method for creating an instance is to use the ClientsModule . To create a client instance with the
ClientsModule , import it and use the register() method to pass an options object with the same properties
https://docs.nestjs.com/microservices/redis 3/8
2/24/25, 1:27 PM Redis - Microservices | NestJS - A progressive Node.js framework
ClientsModule , import it and use the register() method to pass an options object with the same properties
shown above in the createMicroservice() method, as well as a name property to be used as the injection token.
Read more about ClientsModule here.

@Module({ content_copy
imports: [
ClientsModule.register([
{
name: 'MATH_SERVICE',
transport: Transport.REDIS,
options: {
host: 'localhost',
port: 6379,
}
},
]),
]
...
})

Other options to create a client (either ClientProxyFactory or @Client() ) can be used as well. You can read
about them here.

Context
In more complex scenarios, you may need to access additional information about the incoming request. When
using the Redis transporter, you can access the RedisContext object.

JS

@MessagePattern('notifications') content_copy
getNotifications(@Payload() data: number[], @Ctx() context: RedisContext) {
console.log(`Channel: ${context.getChannel()}`);
}

HINT
@P l d() @Ct () and
https://docs.nestjs.com/microservices/redis
R di C t t are imported from the @ tj / i i package 4/8
2/24/25, 1:27 PM Redis - Microservices | NestJS - A progressive Node.js framework
@Payload() , @Ctx() and RedisContext are imported from the @nestjs/microservices package.

Wildcards
To enable wildcards support, set the wildcards option to true . This instructs the transporter to use
psubscribe and pmessage under the hood.

const app = await NestFactory.createMicroservice(AppModule, { content_copy


transport: Transport.REDIS,
options: {
// Other options
wildcards: true,
},
});

Make sure to pass the wildcards option when creating a client instance as well.

With this option enabled, you can use wildcards in your message and event patterns. For example, to subscribe to
all channels starting with notifications , you can use the following pattern:

@EventPattern('notifications.*') content_copy

Instance status updates


To get real-time updates on the connection and the state of the underlying driver instance, you can subscribe to the
status stream. This stream provides status updates specific to the chosen driver. For the Redis driver, the
status stream emits connected , disconnected , and reconnecting events.

this.client.status.subscribe((status: RedisStatus) => { content_copy


console.log(status);
});

HINT
https://docs.nestjs.com/microservices/redis 5/8
2/24/25, 1:27 PM Redis - Microservices | NestJS - A progressive Node.js framework

The RedisStatus type is imported from the @nestjs/microservices package.

Similarly, you can subscribe to the server's status stream to receive notifications about the server's status.

const server = app.connectMicroservice<MicroserviceOptions>(...); content_copy


server.status.subscribe((status: RedisStatus) => {
console.log(status);
});

Listening to Redis 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,
as shown below:

this.client.on('error', (err) => { content_copy


console.error(err);
});

Similarly, you can listen to the server's internal events:

server.on<RedisEvents>('error', (err) => { content_copy


console.error(err);
});

HINT
The RedisEvents type is imported from the @nestjs/microservices package.

Underlying driver access


For more advanced use cases, you may need to access the underlying driver instance. This can be useful for
https://docs.nestjs.com/microservices/redis f f 6/8
2/24/25, 1:27 PM Redis - Microservices | NestJS - A progressive Node.js framework
scenarios like manually closing the connection or using driver-specific methods. However, keep in mind that for
most cases, you shouldn't need to access the driver directly.

To do so, you can use the unwrap() method, which returns the underlying driver instance. The generic type
parameter should specify the type of driver instance you expect.

const [pub, sub] = content_copy


this.client.unwrap<[import('ioredis').Redis, import('ioredis').Redis]>();

Similarly, you can access the server's underlying driver instance:

const [pub, sub] = content_copy


server.unwrap<[import('ioredis').Redis, import('ioredis').Redis]>();

Note that, in contrary to other transporters, the Redis transporter returns a tuple of two ioredis instances: the
first one is used for publishing messages, and the second one is used for subscribing to messages.

Support us
Nest is an MIT-licensed open source project. It can grow thanks to the support by these awesome people. If you'd
like to join them, please read more here.

Principal Sponsors Sponsors / Partners

Become a sponsor

https://docs.nestjs.com/microservices/redis
Join our Newsletter 7/8
2/24/25, 1:27 PM Redis - Microservices | NestJS - A progressive Node.js framework
Join our Newsletter
Subscribe to stay up to date with the latest Nest updates, features, and videos!

Email address..

Copyright © 2017-2025 MIT by Kamil Mysliwiec design by Jakub Staron


Official NestJS Consulting Trilon.io hosted by Netlify

https://docs.nestjs.com/microservices/redis 8/8

You might also like