NestJS Upstream/Downstream Process Design: History- and Queue-Based Interface Patterns
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.
Data Flow Overview
Section titled “Data Flow Overview”Flow:
- An External User calls the document create/update API from the Portal.
- Save the Document data in MongoDB.
- The Interface function retrieves the Document data and transforms it into an RDB format.
- Save the transformed data in the PostgreSQL I/F DB.
- The Legacy system reads the I/F DB and applies the data to the Legacy DB.
Upstream Process: History vs Queue
Section titled “Upstream Process: History vs Queue”1. History Table-Based (Synchronous)
Section titled “1. History Table-Based (Synchronous)”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.
History Table Structure
Section titled “History Table Structure”| Column | Type | Description |
|---|---|---|
id | SERIAL | Primary Key |
document_id | VARCHAR | MongoDB Document ID |
status | VARCHAR | SUCCESS, FAILED, PENDING |
error_message | TEXT | Error message on failure |
created_at | TIMESTAMP | Creation time |
updated_at | TIMESTAMP | Update time |
2. Queue-Based (Asynchronous)
Section titled “2. Queue-Based (Asynchronous)”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).
Queue Status Table Structure
Section titled “Queue Status Table Structure”| Column | Type | Description |
|---|---|---|
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 | Retry count |
error_message | TEXT | Error message on failure |
created_at | TIMESTAMP | Creation time |
updated_at | TIMESTAMP | Update time |
Upstream Code Implementation
Section titled “Upstream Code Implementation”History-Based (Synchronous)
Section titled “History-Based (Synchronous)”@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; }}Queue-Based (Asynchronous)
Section titled “Queue-Based (Asynchronous)”@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});Selection Criteria
Section titled “Selection Criteria”| Criterion | History-Based | Queue-Based |
|---|---|---|
| Implementation complexity | Low | High |
| User response speed | Slow | Fast |
| Failure handling | Immediate notification | Websocket or polling |
| Retry implementation | Manual | Bull Queue automatic |
| Effect of an Interface failure | Entire request fails | No effect on the user experience |
| Recommended scenario | Small scale; synchronous processing required | Large scale; asynchronous processing possible |
Practical Application Principles
Section titled “Practical Application Principles”- 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.
Next Steps
Section titled “Next Steps”The complete architecture of this Upstream/Downstream pattern connects to the articles covered earlier: