0
0
NestJSframework~8 mins

WebSocket guards and pipes in NestJS - Performance & Optimization

Choose your learning style9 modes available
Performance: WebSocket guards and pipes
MEDIUM IMPACT
This concept affects the responsiveness and throughput of WebSocket message handling by controlling access and transforming data before processing.
Validating and transforming incoming WebSocket messages
NestJS
import { SubscribeMessage, WebSocketGateway } from '@nestjs/websockets';
import { UseGuards, UsePipes, ValidationPipe } from '@nestjs/common';
import { WsGuard } from './ws.guard';

@WebSocketGateway()
export class ChatGateway {
  @UseGuards(WsGuard)
  @UsePipes(new ValidationPipe({ transform: true }))
  @SubscribeMessage('message')
  handleMessage(client, payload) {
    // Payload is already validated and transformed
    return { text: payload.text };
  }
}
Using guards and pipes offloads validation and transformation before handler execution, reducing handler complexity and improving throughput.
📈 Performance GainReduces event loop blocking time per message, improving INP and overall responsiveness.
Validating and transforming incoming WebSocket messages
NestJS
import { SubscribeMessage, WebSocketGateway } from '@nestjs/websockets';

@WebSocketGateway()
export class ChatGateway {
  @SubscribeMessage('message')
  handleMessage(client, payload) {
    // Manual validation and transformation inside handler
    if (!payload.text || typeof payload.text !== 'string') {
      return { error: 'Invalid message' };
    }
    const transformed = payload.text.trim().toLowerCase();
    // Process message
    return { text: transformed };
  }
}
Manual validation and transformation inside the handler causes repeated code and blocks the event loop longer, delaying message processing.
📉 Performance CostBlocks event loop per message, increasing INP latency especially under high message volume.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Manual validation in handlerN/AN/AN/A[X] Bad
Validation and transformation via guards and pipesN/AN/AN/A[OK] Good
Rendering Pipeline
WebSocket guards and pipes operate before the message reaches the handler, filtering and transforming data to optimize processing.
Message Reception
Pre-processing
Handler Execution
⚠️ BottleneckHandler Execution stage can be delayed if validation/transformation is done inside handlers.
Core Web Vital Affected
INP
This concept affects the responsiveness and throughput of WebSocket message handling by controlling access and transforming data before processing.
Optimization Tips
1Use guards to block unauthorized WebSocket messages early.
2Use pipes to validate and transform messages before handlers run.
3Avoid heavy processing inside message handlers to keep responsiveness high.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance benefit of using WebSocket guards in NestJS?
AThey increase the size of the WebSocket payload.
BThey prevent unauthorized messages early, reducing unnecessary processing.
CThey delay message handling to batch process messages.
DThey add extra logging for debugging.
DevTools: Performance
How to check: Record a session while sending multiple WebSocket messages. Look for long tasks or delays in the main thread related to message handling.
What to look for: Reduced blocking time and faster message processing indicate efficient use of guards and pipes.