Performance: Message patterns (request-response)
This affects the responsiveness and throughput of backend services handling request-response messaging patterns.
import { Controller } from '@nestjs/common'; import { MessagePattern } from '@nestjs/microservices'; @Controller() export class AppController { @MessagePattern('sum') async handleSum(data: number[]) { // offload heavy processing asynchronously return await new Promise((resolve) => { setImmediate(() => { let result = 0; for (const num of data) { for (let j = 0; j < 1000000; j++) { result += num; } } resolve(result); }); }); } }
import { Controller } from '@nestjs/common'; import { MessagePattern } from '@nestjs/microservices'; @Controller() export class AppController { @MessagePattern('sum') async handleSum(data: number[]) { // heavy synchronous processing let result = 0; for (let i = 0; i < data.length; i++) { for (let j = 0; j < 1000000; j++) { result += data[i]; } } return result; } }
| Pattern | Event Loop Blocking | Response Delay | Throughput Impact | Verdict |
|---|---|---|---|---|
| Synchronous heavy processing | High (blocks event loop) | High (delays response) | Low (reduces throughput) | [X] Bad |
| Asynchronous offloading | Low (non-blocking) | Low (fast response) | High (better throughput) | [OK] Good |
@MessagePattern decorator in NestJS?@MessagePattern@MessagePattern is for message-based communication, not HTTP or database setup.@MessagePattern listens for messages [OK]@MessagePattern listens, not sends [OK]@MessagePattern with HTTP route decorators@MessagePattern is the correct decorator to listen for messages, not @Get, @Post, or @Subscribe.@MessagePattern, and the handler method processes the data.@MessagePattern('pattern') for message handlers [OK]@MessagePattern for message handlers, not HTTP decorators [OK]@Get or @Post for message patterns@Subscribe@MessagePattern@MessagePattern('multiply')
handleMultiply(data: number[]) {
return data[0] * data[1];
}@MessagePattern('greet')
async handleGreet(name: string) {
console.log('Greeting:', name);
}{ a: 5, b: 7 }. Which of the following handler implementations correctly achieves this?a and b, so the handler must accept an object with those properties.data.a and data.b and returns their sum.Pass the test and this pattern moves unknown