DEV Community

Cover image for Effortless Redis Sentinel Setup in NestJS with RedisX
Suren Krmoian
Suren Krmoian

Posted on

Effortless Redis Sentinel Setup in NestJS with RedisX

Redis Sentinel is no joke when it comes to keeping your Redis instances highly available. Hook it up with NestJS via RedisX, and you've got a streamlined, powerful setup.

Setting Up Redis Sentinel in NestJS with RedisX

Getting Redis Sentinel up and running with NestJS doesn't have to be rocket science. First, make sure your Redis environment has a Sentinel setup. You’ll need at least three Sentinel instances for a proper quorum and failover.

Step 1: Install Necessary Packages

Let's start by installing some packages. Open up your terminal and run:

npm install @nestjs-redisx/core ioredis
Enter fullscreen mode Exit fullscreen mode

Boom. Now you have the core module and the ioredis driver, which plays nicely with Redis Sentinel.

Step 2: Sentinel Configuration

Time to configure. Head over to your AppModule in your NestJS app and set up RedisModule to use Sentinel:

import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { RedisModule } from '@nestjs-redisx/core';

@Module({
  imports: [
    ConfigModule.forRoot({ isGlobal: true }),
    RedisModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: (config: ConfigService) => ({
        clients: {
          type: 'sentinel',
          sentinels: [
            { host: config.get('SENTINEL_HOST1'), port: config.get('SENTINEL_PORT1') },
            { host: config.get('SENTINEL_HOST2'), port: config.get('SENTINEL_PORT2') },
            { host: config.get('SENTINEL_HOST3'), port: config.get('SENTINEL_PORT3') },
          ],
          name: config.get('SENTINEL_MASTER_NAME'),
        },
      }),
    }),
  ],
})
export class AppModule {}
Enter fullscreen mode Exit fullscreen mode

Don’t forget to replace SENTINEL_HOST and SENTINEL_PORT with the actual details of your Sentinel instances.

Step 3: Why Use Redis Sentinel with RedisX?

  • Automatic Failover: If your master server bites the dust, Sentinel steps in, electing a new one without missing a beat.
  • Monitoring: Keeps an eye on your Redis instance. If something goes south, you'll know.
  • Simplified Setup: RedisX brings simplicity to Sentinel configurations, centralizing everything. Less hassle, more uptime.

RedisX Simplification

RedisX’s plugin architecture means everything—Sentinel included—lives under one roof. This keeps things neat, especially if you’re juggling multiple Redis setups.

Wrapping Up

There you have it. By setting up Redis Sentinel with NestJS via RedisX, you secure a reliable, high-availability Redis setup. It’s easy to manage and scales with your needs. Dive deeper into the NestJS RedisX documentation to explore more.

For specific details on configuring Redis Sentinel in NestJS, check out the NestJS Redis sentinel configuration.

Top comments (0)