콘텐츠로 이동

NestJS Upstream/Downstream 프로세스 설계: History와 Queue 기반 Interface 패턴

Interactive Diagram

새 탭 ↗

협업 플랫폼에서 사용자가 문서를 생성하면, 그 데이터는 내부 시스템과 Legacy 시스템을 거쳐 최종 DB에 저장된다. 이 흐름을 Upstream(문서 생성 및 Interface 호출)과 Downstream(실시간 알림 및 상태 조회)으로 나누고, Upstream에서 History 기반 동기 방식과 Queue 기반 비동기 방식을 비교한다.

PlantUML Diagram

흐름:

  1. External User가 Portal에서 문서 생성/수정 API 호출
  2. Document 데이터를 MongoDB에 저장
  3. Interface 기능이 Document 데이터를 조회하고 RDB 형태로 변환
  4. 변환된 데이터를 PostgreSQL I/F DB에 저장
  5. Legacy 시스템이 I/F DB를 읽어 Legacy DB에 반영
PlantUML Diagram

특징:

  • Document 생성과 Interface API 호출이 하나의 요청에서 순차 실행
  • Interface API 호출 결과(성공/실패)를 History table에 기록
  • 사용자는 응답을 받을 때까지 대기: Interface 실패 시 즉시 알 수 있음

장점:

  • 간단한 구조: Transaction 관리가 명확
  • 실패 시 즉시 재시도 또는 롤백 가능

단점:

  • Interface API가 느리면 사용자 응답이 느려짐
  • Interface API 장애 시 전체 요청이 실패
컬럼타입설명
idSERIALPrimary Key
document_idVARCHARMongoDB Document ID
statusVARCHARSUCCESS, FAILED, PENDING
error_messageTEXT실패 시 에러 메시지
created_atTIMESTAMP생성 시각
updated_atTIMESTAMP업데이트 시각
PlantUML Diagram

특징:

  • Document 생성 후 Queue에 Job 등록하고 즉시 응답
  • Interface Consumer가 비동기로 Job 처리
  • 처리 완료 시 Websocket으로 사용자에게 알림

장점:

  • 사용자 응답이 빠름: Interface 처리를 기다리지 않음
  • Interface API 장애가 사용자 경험에 영향 주지 않음
  • 실패한 Job을 재시도하기 쉬움

단점:

  • 복잡도 증가: Queue, Consumer, Websocket 모두 관리 필요
  • 사용자가 결과를 즉시 알 수 없음 (알림 또는 polling 필요)
컬럼타입설명
idSERIALPrimary Key
job_idVARCHARBull Queue Job ID
document_idVARCHARMongoDB Document ID
statusVARCHARQUEUED, PROCESSING, COMPLETED, FAILED
retry_countINT재시도 횟수
error_messageTEXT실패 시 에러 메시지
created_atTIMESTAMP생성 시각
updated_atTIMESTAMP업데이트 시각
todos.service.ts
@Injectable()
export class TodosService {
constructor(
@Inject('TODO_REPOSITORY')
private todoRepository: Repository<Todo>,
private interfaceService: InterfaceService,
private historyService: HistoryService,
) {}
async create(createTodoDto: CreateTodoDto): Promise<Todo> {
// 1. Document DB에 저장
const todo = await this.todoRepository.save(createTodoDto);
try {
// 2. Interface API 호출
await this.interfaceService.sendToLegacy(todo);
// 3. History 성공 기록
await this.historyService.create({
documentId: todo.id,
status: 'SUCCESS',
});
} catch (error) {
// 3. History 실패 기록
await this.historyService.create({
documentId: todo.id,
status: 'FAILED',
errorMessage: error.message,
});
throw error; // 사용자에게 에러 반환
}
return todo;
}
}
todos.service.ts
@Injectable()
export class TodosService {
constructor(
@Inject('TODO_REPOSITORY')
private todoRepository: Repository<Todo>,
@InjectQueue('todo-interface')
private interfaceQueue: Queue,
) {}
async create(createTodoDto: CreateTodoDto): Promise<Todo> {
// 1. Document DB에 저장
const todo = await this.todoRepository.save(createTodoDto);
// 2. Queue에 Job 등록
await this.interfaceQueue.add('process-interface', {
todoId: todo.id,
});
// 3. 즉시 응답 (Interface 처리 대기 안 함)
return todo;
}
}
// todos.consumer.ts
@Processor('todo-interface')
export class TodosConsumer {
constructor(
private interfaceService: InterfaceService,
private queueStatusService: QueueStatusService,
private websocketGateway: EventsGateway,
) {}
@Process('process-interface')
async handleInterface(job: Job) {
const { todoId } = job.data;
try {
// 1. Queue status를 PROCESSING으로 업데이트
await this.queueStatusService.update(job.id, 'PROCESSING');
// 2. Interface API 호출
await this.interfaceService.sendToLegacy(todoId);
// 3. Queue status를 COMPLETED로 업데이트
await this.queueStatusService.update(job.id, 'COMPLETED');
// 4. Websocket으로 사용자에게 알림
this.websocketGateway.server.emit('interface:completed', { todoId });
} catch (error) {
// 3. Queue status를 FAILED로 업데이트
await this.queueStatusService.update(job.id, 'FAILED', error.message);
// 4. Websocket으로 실패 알림
this.websocketGateway.server.emit('interface:failed', {
todoId,
error: error.message,
});
throw error; // Bull Queue retry 트리거
}
}
}

Queue 기반 Upstream에서는 처리 완료 시 사용자에게 실시간 알림을 보낸다.

// Frontend (Angular/React)
import { io } from 'socket.io-client';
const socket = io('https://backend-api.example.com');
socket.on('interface:completed', (data) => {
console.log('Interface completed:', data.todoId);
// UI 업데이트
});
socket.on('interface:failed', (data) => {
console.error('Interface failed:', data.todoId, data.error);
// 에러 메시지 표시
});
기준History 기반Queue 기반
구현 복잡도낮음높음
사용자 응답 속도느림빠름
실패 처리즉시 알림Websocket 또는 polling
재시도 구현수동Bull Queue 자동
Interface 장애 영향전체 요청 실패사용자 경험에 영향 없음
권장 시나리오소규모, 동기 필수대규모, 비동기 가능
  • 소규모 프로젝트는 History 기반: 구조가 단순하고 트러블슈팅이 쉽다
  • 대규모 또는 Interface가 느린 경우 Queue 기반: 사용자 경험을 해치지 않는다
  • Queue 기반에서는 상태 table 필수: Job ID와 Document ID를 매핑해야 사용자가 진행 상태를 조회할 수 있다
  • Websocket 알림은 필수: Queue 기반에서 사용자가 완료를 알 수 있는 유일한 방법
  • Bull Dashboard로 모니터링: Failed Job을 수동 재시도하거나 Queue 적체를 감지한다

이 Upstream/Downstream 패턴의 전체 아키텍처는 앞서 다룬 글들과 연결된다: