콘텐츠로 이동

NestJS Redis 패턴: Cache-Manager와 Bull Queue 실전 활용

Interactive Diagram

새 탭 ↗

Redis는 Backend에서 Cache storage와 Message Queue 두 가지 역할로 동시에 사용된다. NestJS는 cache-manager와 bull package를 framework 수준에서 통합 지원하므로, Redis를 아주 쉽게 붙일 수 있다. 이 글은 실제 프로젝트에서 Cache와 Queue를 설계한 패턴과 bull-board로 Queue를 모니터링하는 구조를 다룬다.

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

NestJS는 @nestjs/common에 CacheModule을 내장하고 있어 별도 wrapping 없이 바로 사용할 수 있다.

  • 디렉터리src/
    • 디렉터리database/
      • 디렉터리redis/
        • 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, // 전체 모듈에서 사용 가능
useFactory: () => ({
store: redisStore,
host: process.env.REDIS_HOST,
port: process.env.REDIS_PORT,
ttl: 60, // 기본 TTL (초)
password: process.env.REDIS_PASSWORD,
}),
}),
],
})
export class RedisCacheModule {}

핵심 포인트:

  • isGlobal: true: 모든 module에서 재import 없이 사용 가능
  • store: redisStore: 지정하지 않으면 in-memory cache 사용
  • ttl: 60: 기본 만료 시간 (초 단위)
  • 디렉터리src/
    • 디렉터리api/
      • 디렉터리v1/
        • 디렉터리cache/
          • 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;
}
}

CACHE_MANAGER token을 inject해서 Cache class를 사용한다. get, set, del 메서드로 Redis를 조작한다.

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
# 첫 요청 — cache 생성
$ curl 'https://backend-api.example.com/api/v1/cache'
save new time : 1659489894415
# 두 번째 요청 — 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은 Redis 기반 Queue library이며, Producer/Consumer 패턴을 지원한다.

Bull은 Queue name별로 Redis key를 생성하고, Job에 순차 번호를 부여한다.

Queue name: todo-created, Process name: temporary

Redis Key설명
bull:todo-created:wait대기 중인 Job 목록
bull:todo-created:completed완료된 Job 목록
bull:todo-created:failed실패한 Job 목록
bull:todo-created:{jobId}개별 Job 데이터 (상태별로 내용 다름)

Completed Job 데이터 예시:

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

Failed Job 데이터 예시:

{
"id": "88",
"data": { ... },
"failedReason": "MongoServerError: E11000 duplicate key...",
"stacktrace": [ ... ]
}
  • 디렉터리src/
    • 디렉터리database/
      • 디렉터리redis/
        • 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 {}

각 module에서 BullModule.registerQueue()로 사용할 Queue를 등록한다.

  • 디렉터리src/
    • 디렉터리api/
      • 디렉터리v1/
        • 디렉터리todos/
          • 디렉터리consumers/
            • todos.consumer.ts Queue Consumer
          • todos.controller.ts API endpoint
          • todos.module.ts Queue 등록
          • 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 이름
}),
],
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;
}
}

@InjectQueue('todo-created')로 Queue를 주입받고, add(processName, data)로 Job을 생성한다.

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) {
// MongoDB에 저장하는 로직 (예시)
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);
}
}

핵심 Decorator:

  • @Processor('todo-created'): 이 Consumer가 처리할 Queue 이름
  • @Process('temporary'): 이 메서드가 처리할 Process 이름
  • @OnQueueFailed(): Job 실패 시 실행
  • @OnQueueCompleted(): Job 성공 시 실행
Terminal window
### Job 성공
[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":"냐아옹"},"completed":false}}
[Winston] Info 2022-08-03T01:28:51+00:00 (Queue) on Completed: job 87 -> result: undefined
### Job 실패 (중복 키 오류)
[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은 @bull-board로 Admin UI를 제공한다. Redis memory usage, Queue 상태, Job 목록을 모니터링하고 Failed Job을 재시도할 수 있다.

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();

/admin/queues 엔드포인트로 접속하면 Bull Dashboard가 표시된다.

  • Redis memory usage, fragmentation ratio 모니터링
  • Queue name별 Job 목록 조회
  • Queue status별(wait/completed/failed) Job 조회
  • Job 데이터 삭제
  • Failed Job 재시도
  • Dashboard 인증 관리 (기본 인증 설정 가능)
  • Cache는 isGlobal로: 모든 module에서 재import 없이 사용
  • Queue는 module별로 등록: 각 도메인이 자신의 Queue를 소유
  • Consumer는 별도 class로 분리: Service와 Consumer를 섞으면 책임이 불명확해진다
  • Bull Dashboard는 필수: Failed Job을 수동 재시도하거나 Queue 적체를 모니터링할 때 필수다
  • Event Decorator 활용: @OnQueueFailed, @OnQueueCompleted로 Job lifecycle을 추적한다

이 Redis 패턴 위에서 Web Push Notification을 구현하는 방법은 NestJS Web Push Notification에서 다룬다. Upstream/Downstream 프로세스 설계는 NestJS Upstream/Downstream 설계에서 이어진다.