Skip to content

NestJS Upstream/Downstream Process Design: History- and Queue-Based Interface Patterns

Interactive Diagram

새 탭 ↗

When a user creates a document on a collaboration platform, the data passes through internal and Legacy systems before ultimately being stored in the final DB. This flow is divided into Upstream (document creation and Interface invocation) and Downstream (real-time notifications and status lookups), and compares the History-based synchronous approach with the Queue-based asynchronous approach in the Upstream process.

PlantUML Diagram

Flow:

  1. An External User calls the document create/update API from the Portal.
  2. Save the Document data in MongoDB.
  3. The Interface function retrieves the Document data and transforms it into an RDB format.
  4. Save the transformed data in the PostgreSQL I/F DB.
  5. The Legacy system reads the I/F DB and applies the data to the Legacy DB.
PlantUML Diagram

Characteristics:

  • Document creation and the Interface API invocation run sequentially within a single request.
  • The Interface API invocation result (success/failure) is recorded in the History table.
  • The user waits for a response: they can immediately know if the Interface fails.

Advantages:

  • Simple structure: Transaction management is clear.
  • On failure, you can retry or roll back immediately.

Disadvantages:

  • If the Interface API is slow, the user response is slow.
  • If the Interface API fails, the entire request fails.
ColumnTypeDescription
idSERIALPrimary Key
document_idVARCHARMongoDB Document ID
statusVARCHARSUCCESS, FAILED, PENDING
error_messageTEXTError message on failure
created_atTIMESTAMPCreation time
updated_atTIMESTAMPUpdate time
PlantUML Diagram

Characteristics:

  • After creating a Document, register a Job in the Queue and respond immediately.
  • The Interface Consumer processes the Job asynchronously.
  • When processing is complete, notify the user through Websocket.

Advantages:

  • The user response is fast: it does not wait for Interface processing.
  • An Interface API failure does not affect the user experience.
  • It is easy to retry failed Jobs.

Disadvantages:

  • Increased complexity: the Queue, Consumer, and Websocket must all be managed.
  • The user cannot know the result immediately (a notification or polling is required).
ColumnTypeDescription
idSERIALPrimary Key
job_idVARCHARBull Queue Job ID
document_idVARCHARMongoDB Document ID
statusVARCHARQUEUED, PROCESSING, COMPLETED, FAILED
retry_countINTRetry count
error_messageTEXTError message on failure
created_atTIMESTAMPCreation time
updated_atTIMESTAMPUpdate time
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. store into Document DB
const todo = await this.todoRepository.save(createTodoDto);
try {
// 2. call the Interface API
await this.interfaceService.sendToLegacy(todo);
// 3. record History success
await this.historyService.create({
documentId: todo.id,
status: 'SUCCESS',
});
} catch (error) {
// 3. record History failure
await this.historyService.create({
documentId: todo.id,
status: 'FAILED',
errorMessage: error.message,
});
throw error; // return the error to the user
}
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. store into Document DB
const todo = await this.todoRepository.save(createTodoDto);
// 2. enqueue the Job
await this.interfaceQueue.add('process-interface', {
todoId: todo.id,
});
// 3. respond immediately (does not wait for Interface processing)
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. update Queue status to PROCESSING
await this.queueStatusService.update(job.id, 'PROCESSING');
// 2. call the Interface API
await this.interfaceService.sendToLegacy(todoId);
// 3. update Queue status to COMPLETED
await this.queueStatusService.update(job.id, 'COMPLETED');
// 4. notify the user over Websocket
this.websocketGateway.server.emit('interface:completed', { todoId });
} catch (error) {
// 3. update Queue status to FAILED
await this.queueStatusService.update(job.id, 'FAILED', error.message);
// 4. send a failure notification over Websocket
this.websocketGateway.server.emit('interface:failed', {
todoId,
error: error.message,
});
throw error; // triggers Bull Queue retry
}
}
}

Downstream Process: Websocket Notifications

Section titled “Downstream Process: Websocket Notifications”

In the Queue-based Upstream process, send the user a real-time notification when processing is complete.

// 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);
// update the UI
});
socket.on('interface:failed', (data) => {
console.error('Interface failed:', data.todoId, data.error);
// show the error message
});
CriterionHistory-BasedQueue-Based
Implementation complexityLowHigh
User response speedSlowFast
Failure handlingImmediate notificationWebsocket or polling
Retry implementationManualBull Queue automatic
Effect of an Interface failureEntire request failsNo effect on the user experience
Recommended scenarioSmall scale; synchronous processing requiredLarge scale; asynchronous processing possible
  • Use History-based processing for small projects: the structure is simple and troubleshooting is easy.
  • Use Queue-based processing for large-scale projects or when the Interface is slow: it does not harm the user experience.
  • A status table is essential in the Queue-based approach: map the Job ID and Document ID so users can check progress.
  • Websocket notification is essential: in the Queue-based approach, it is the only way for users to know processing has completed.
  • Monitor with the Bull Dashboard: manually retry Failed Jobs or detect Queue backlogs.

The complete architecture of this Upstream/Downstream pattern connects to the articles covered earlier: