0
0
NestJSframework~8 mins

WebSocket gateway creation in NestJS - Performance & Optimization

Choose your learning style9 modes available
Performance: WebSocket gateway creation
MEDIUM IMPACT
This affects the real-time communication speed and responsiveness between client and server.
Setting up a WebSocket gateway for real-time messaging
NestJS
import { WebSocketGateway, SubscribeMessage, MessageBody } from '@nestjs/websockets';

@WebSocketGateway()
export class ChatGateway {
  @SubscribeMessage('message')
  async handleMessage(client: any, payload: any): Promise<void> {
    // offload heavy work asynchronously
    await someAsyncProcessing(payload);
    client.emit('message', payload);
  }
}

async function someAsyncProcessing(data: any) {
  return new Promise(resolve => setTimeout(resolve, 0));
}
Offloading heavy work asynchronously prevents blocking, keeping the event loop free for other tasks.
📈 Performance GainImproves INP by avoiding event loop blocking
Setting up a WebSocket gateway for real-time messaging
NestJS
import { WebSocketGateway, SubscribeMessage, MessageBody } from '@nestjs/websockets';

@WebSocketGateway()
export class ChatGateway {
  @SubscribeMessage('message')
  handleMessage(client: any, payload: any): void {
    // heavy synchronous processing
    for (let i = 0; i < 1000000000; i++) {}
    client.emit('message', payload);
  }
}
Heavy synchronous processing blocks the event loop, delaying message handling and response.
📉 Performance CostBlocks event loop causing high input latency and poor INP
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Synchronous heavy processing in gateway000[X] Bad
Asynchronous non-blocking message handling000[OK] Good
Rendering Pipeline
WebSocket gateway creation impacts the interaction responsiveness by controlling how quickly messages are processed and sent back to clients.
Event Loop
Network I/O
JavaScript Execution
⚠️ BottleneckBlocking synchronous code in message handlers
Core Web Vital Affected
INP
This affects the real-time communication speed and responsiveness between client and server.
Optimization Tips
1Avoid heavy synchronous processing in WebSocket message handlers.
2Use asynchronous code to keep the event loop free.
3Monitor event loop blocking to maintain low input latency.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance risk when handling WebSocket messages with heavy synchronous code?
AAdding large bundle size
BBlocking the event loop and increasing input latency
CIncreasing DOM reflows
DCausing layout shifts
DevTools: Performance
How to check: Record a performance profile while sending WebSocket messages and look for long tasks blocking the main thread.
What to look for: Look for long tasks or event loop blocking that delay message handling and increase input latency.