Skip to content

NestJS Redis Patterns: Practical Use of Cache-Manager and Bull Queue

Interactive Diagram

새 탭 ↗

In the backend, Redis is used simultaneously in two roles: as cache storage and as a message queue. Because NestJS provides framework-level integration for the cache-manager and bull packages, Redis can be connected very easily. This article covers patterns for designing caches and queues in a real project, along with a structure for monitoring queues with bull-board.

Terminal window
npm install cache-manager
npm install -D @types/cache-manager

NestJS includes CacheModule in @nestjs/common, so it can be used directly without additional wrapping.

  • Directorysrc/
    • Directorydatabase/
      • Directoryredis/
        • redis.cache.module.ts
redis.cache.module.ts
import { CacheModule as NestCacheModule, Module } from '@nestjs/common';
import * as redisStore from 'cache-manager-ioredis';
@Module({
imports: [
NestCacheModule.registerAsync({
isGlobal: true, // available to all modules
useFactory: () => ({
store: redisStore,
host: process.env.REDIS_HOST,
port: process.env.REDIS_PORT,
ttl: 60, // default TTL (seconds)
password: process.env.REDIS_PASSWORD,
}),
}),
],
})
export class RedisCacheModule {}

Key points:

  • isGlobal: true: can be used in every module without re-importing it
  • store: redisStore: if it is not specified, the in-memory cache is used
  • ttl: 60: default expiration time (in seconds)
  • Directorysrc/
    • Directoryapi/
      • Directoryv1/
        • Directorycache/
          • cache.controller.ts
          • cache.module.ts
          • cache.service.ts
cache.module.ts
import { Module } from '@nestjs/common';
import { RedisCacheModule } from '../../../database/redis/redis.cache.module';
import { CacheController } from './cache.controller';
import { CacheService } from './cache.service';
@Module({
imports: [RedisCacheModule],
controllers: [CacheController],
providers: [CacheService],
})
export class CacheModule {}
cache.service.ts
import { Injectable, Inject, CACHE_MANAGER } from '@nestjs/common';
import { Cache } from 'cache-manager';
@Injectable()
export class CacheService {
constructor(@Inject(CACHE_MANAGER) private cacheManager: Cache) {}
async cache(): Promise<string> {
const savedTime = await this.cacheManager.get<number>('time');
if (savedTime) {
return 'saved time : ' + savedTime;
}
const now = new Date().getTime();
await this.cacheManager.set<number>('time', now);
return 'save new time : ' + now;
}
}

Inject the CACHE_MANAGER token to use the Cache class. Redis is manipulated with the get, set, and del methods.

cache.controller.ts
import { Controller, Get } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { CacheService } from './cache.service';
@ApiTags('Cache')
@Controller('cache')
export class CacheController {
constructor(private readonly cacheService: CacheService) {}
@Get()
async getCache() {
return this.cacheService.cache();
}
}
Terminal window
# first request - cache created
$ curl 'https://backend-api.example.com/api/v1/cache'
save new time : 1659489894415
# second request - cache hit
$ curl 'https://backend-api.example.com/api/v1/cache'
saved time : 1659489894415
Terminal window
npm install @nestjs/bull bull
npm install -D @types/bull

Bull is a Redis-based queue library that supports the Producer/Consumer pattern.

Bull creates Redis keys for each queue name and assigns sequential numbers to jobs.

Queue name: todo-created, Process name: temporary

Redis KeyDescription
bull:todo-created:waitList of jobs waiting to be processed
bull:todo-created:completedList of completed jobs
bull:todo-created:failedList of failed jobs
bull:todo-created:{jobId}Individual job data (contents differ by status)

Example completed job data:

{
"id": "87",
"data": {
"todo": {
"todoid": 61,
"content": {"test": "meow"},
"completed": false
}
},
"processedOn": 1659489531000,
"returnvalue": null
}

Example failed job data:

{
"id": "88",
"data": { ... },
"failedReason": "MongoServerError: E11000 duplicate key...",
"stacktrace": [ ... ]
}
  • Directorysrc/
    • Directorydatabase/
      • Directoryredis/
        • redis.queue.module.ts
redis.queue.module.ts
import { Module } from '@nestjs/common';
import { BullModule } from '@nestjs/bull';
@Module({
imports: [
BullModule.forRootAsync({
useFactory: () => ({
redis: {
host: process.env.REDIS_HOST,
port: Number(process.env.REDIS_PORT),
password: process.env.REDIS_PASSWORD,
},
}),
}),
],
})
export class RedisQueueModule {}

Register the queue to use in each module with BullModule.registerQueue().

Implementing a Queue Producer and Consumer

Section titled “Implementing a Queue Producer and Consumer”
  • Directorysrc/
    • Directoryapi/
      • Directoryv1/
        • Directorytodos/
          • Directoryconsumers/
            • todos.consumer.ts Queue Consumer
          • todos.controller.ts API endpoint
          • todos.module.ts Queue registration
          • todos.service.ts Queue Producer
todos.module.ts
import { Module } from '@nestjs/common';
import { BullModule } from '@nestjs/bull';
import { TodosController } from './todos.controller';
import { TodosService } from './todos.service';
import { TodosConsumer } from './consumers/todos.consumer';
@Module({
imports: [
BullModule.registerQueue({
name: 'todo-created', // Queue name
}),
],
controllers: [TodosController],
providers: [TodosService, TodosConsumer],
})
export class TodosModule {}
todos.service.ts
import { InjectQueue } from '@nestjs/bull';
import { Injectable } from '@nestjs/common';
import { Queue } from 'bull';
import { CreateTodoDto } from './dto/create-todo.dto';
@Injectable()
export class TodosService {
constructor(
@InjectQueue('todo-created')
private todoQueue: Queue,
) {}
async create_temporary(createTodoDto: CreateTodoDto): Promise<any> {
const job = await this.todoQueue.add('temporary', {
todo: createTodoDto,
});
return job.data;
}
}

Inject the queue with @InjectQueue('todo-created'), and create a job with add(processName, data).

todos.consumer.ts
import {
Processor,
Process,
InjectQueue,
OnQueueFailed,
OnQueueCompleted,
} from '@nestjs/bull';
import { Job, Queue } from 'bull';
import { Injectable } from '@nestjs/common';
@Processor('todo-created')
@Injectable()
export class TodosConsumer {
constructor(
@InjectQueue('todo-created')
private todoQueue: Queue,
) {}
@Process('temporary')
async handleTemporary(job: Job) {
// logic that stores into MongoDB (example)
console.log('Processing job', job.id, job.data);
// await this.todoModel.create(job.data.todo);
}
@OnQueueFailed()
async onQueueFailed(job: Job, error: Error) {
console.error(`Job ${job.id} failed:`, error.message);
}
@OnQueueCompleted()
async onQueueCompleted(job: Job, result: any) {
console.log(`Job ${job.id} completed:`, result);
}
}

Key decorators:

  • @Processor('todo-created'): the name of the queue this consumer processes
  • @Process('temporary'): the name of the process this method handles
  • @OnQueueFailed(): runs when a job fails
  • @OnQueueCompleted(): runs when a job succeeds
Terminal window
### Job success
[Winston] Info 2022-08-03T01:28:51+00:00 "POST /api/v1/todos/temporary" 201 Created
[Winston] Info 2022-08-03T01:28:51+00:00 {"todo":{"todoid":61,"content":{"test":"meow"},"completed":false}}
[Winston] Info 2022-08-03T01:28:51+00:00 (Queue) on Completed: job 87 -> result: undefined
### Job failure (duplicate key error)
[Winston] Info 2022-08-03T01:31:30+00:00 "POST /api/v1/todos/temporary" 201 Created
[Winston] Error 2022-08-03T01:31:30+00:00 (Queue) on Error: job 88 -> result: MongoServerError: E11000 duplicate key...

Bull provides an admin UI through @bull-board. It can monitor Redis memory usage, queue status, and job lists, and retry failed jobs.

Terminal window
npm install @bull-board/api @bull-board/express
main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { createBullBoard } from '@bull-board/api';
import { BullAdapter } from '@bull-board/api/bullAdapter';
import { ExpressAdapter } from '@bull-board/express';
import { Queue } from 'bull';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
// Bull dashboard setup
const serverAdapter = new ExpressAdapter();
serverAdapter.setBasePath('/admin/queues');
const todoQueue = app.get<Queue>(`BullQueue_todo-created`);
createBullBoard({
queues: [new BullAdapter(todoQueue)],
serverAdapter,
});
app.use('/admin/queues', serverAdapter.getRouter());
await app.listen(3000);
}
bootstrap();

The Bull Dashboard is displayed when you access the /admin/queues endpoint.

  • Monitor Redis memory usage and fragmentation ratio
  • View job lists by queue name
  • View jobs by queue status (wait/completed/failed)
  • Delete job data
  • Retry failed jobs
  • Manage dashboard authentication (basic authentication can be configured)
  • Make the cache global: use it in every module without re-importing it
  • Register queues per module: each domain owns its own queue
  • Separate consumers into their own classes: mixing services and consumers makes responsibilities unclear
  • The Bull Dashboard is essential: it is necessary for manually retrying failed jobs or monitoring queue backlogs
  • Use event decorators: track the job lifecycle with @OnQueueFailed and @OnQueueCompleted

How to implement Web Push Notifications on top of this Redis pattern is covered in NestJS Web Push Notification. The design of upstream/downstream processes continues in NestJS Upstream/Downstream Design.