NestJS Upstream/Downstream 프로세스 설계: History와 Queue 기반 Interface 패턴
협업 플랫폼에서 사용자가 문서를 생성하면, 그 데이터는 내부 시스템과 Legacy 시스템을 거쳐 최종 DB에 저장된다. 이 흐름을 Upstream(문서 생성 및 Interface 호출)과 Downstream(실시간 알림 및 상태 조회)으로 나누고, Upstream에서 History 기반 동기 방식과 Queue 기반 비동기 방식을 비교한다.
Data Flow 개요
섹션 제목: “Data Flow 개요”흐름:
- External User가 Portal에서 문서 생성/수정 API 호출
- Document 데이터를 MongoDB에 저장
- Interface 기능이 Document 데이터를 조회하고 RDB 형태로 변환
- 변환된 데이터를 PostgreSQL I/F DB에 저장
- Legacy 시스템이 I/F DB를 읽어 Legacy DB에 반영
Upstream Process: History vs Queue
섹션 제목: “Upstream Process: History vs Queue”1. History Table 기반 (동기 방식)
섹션 제목: “1. History Table 기반 (동기 방식)”특징:
- Document 생성과 Interface API 호출이 하나의 요청에서 순차 실행
- Interface API 호출 결과(성공/실패)를 History table에 기록
- 사용자는 응답을 받을 때까지 대기: Interface 실패 시 즉시 알 수 있음
장점:
- 간단한 구조: Transaction 관리가 명확
- 실패 시 즉시 재시도 또는 롤백 가능
단점:
- Interface API가 느리면 사용자 응답이 느려짐
- Interface API 장애 시 전체 요청이 실패
History Table 구조
섹션 제목: “History Table 구조”| 컬럼 | 타입 | 설명 |
|---|---|---|
id | SERIAL | Primary Key |
document_id | VARCHAR | MongoDB Document ID |
status | VARCHAR | SUCCESS, FAILED, PENDING |
error_message | TEXT | 실패 시 에러 메시지 |
created_at | TIMESTAMP | 생성 시각 |
updated_at | TIMESTAMP | 업데이트 시각 |
2. Queue 기반 (비동기 방식)
섹션 제목: “2. Queue 기반 (비동기 방식)”특징:
- Document 생성 후 Queue에 Job 등록하고 즉시 응답
- Interface Consumer가 비동기로 Job 처리
- 처리 완료 시 Websocket으로 사용자에게 알림
장점:
- 사용자 응답이 빠름: Interface 처리를 기다리지 않음
- Interface API 장애가 사용자 경험에 영향 주지 않음
- 실패한 Job을 재시도하기 쉬움
단점:
- 복잡도 증가: Queue, Consumer, Websocket 모두 관리 필요
- 사용자가 결과를 즉시 알 수 없음 (알림 또는 polling 필요)
Queue Status Table 구조
섹션 제목: “Queue Status Table 구조”| 컬럼 | 타입 | 설명 |
|---|---|---|
id | SERIAL | Primary Key |
job_id | VARCHAR | Bull Queue Job ID |
document_id | VARCHAR | MongoDB Document ID |
status | VARCHAR | QUEUED, PROCESSING, COMPLETED, FAILED |
retry_count | INT | 재시도 횟수 |
error_message | TEXT | 실패 시 에러 메시지 |
created_at | TIMESTAMP | 생성 시각 |
updated_at | TIMESTAMP | 업데이트 시각 |
Upstream 코드 구현
섹션 제목: “Upstream 코드 구현”History 기반 (동기)
섹션 제목: “History 기반 (동기)”@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; }}Queue 기반 (비동기)
섹션 제목: “Queue 기반 (비동기)”@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 트리거 } }}Downstream Process: Websocket 알림
섹션 제목: “Downstream Process: Websocket 알림”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 패턴의 전체 아키텍처는 앞서 다룬 글들과 연결된다: