Bird
Raised Fist0
NestJSframework~8 mins

Why WebSockets enable real-time features in NestJS - Performance Evidence

Choose your learning style10 modes available
Performance: Why WebSockets enable real-time features
HIGH IMPACT
WebSockets impact the interaction speed between client and server by enabling instant two-way communication, improving responsiveness and user experience.
Implementing real-time chat updates
NestJS
const socket = new WebSocket('wss://example.com/chat');
socket.onmessage = event => updateUI(JSON.parse(event.data));
Maintains a single open connection that pushes updates instantly without repeated requests.
📈 Performance GainReduces network requests to 1 connection; improves input responsiveness (INP); lowers CPU and network load
Implementing real-time chat updates
NestJS
setInterval(() => fetch('/api/messages').then(res => res.json()).then(updateUI), 3000);
Polling repeatedly requests the server, causing unnecessary network traffic and delayed updates.
📉 Performance CostBlocks rendering briefly every 3 seconds; adds network overhead and increases CPU usage
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Polling with HTTP requestsMultiple DOM updates per pollTriggers reflow each updateHigher paint cost due to frequent updates[X] Bad
WebSocket real-time updatesDOM updates only on new dataMinimal reflows triggeredLower paint cost with targeted updates[OK] Good
Rendering Pipeline
WebSockets keep a persistent connection open, allowing the server to push data directly to the client without repeated HTTP requests, minimizing delays in the rendering pipeline.
→Network
→JavaScript Execution
→Paint
⚠️ BottleneckNetwork latency and JavaScript event handling
Core Web Vital Affected
INP
WebSockets impact the interaction speed between client and server by enabling instant two-way communication, improving responsiveness and user experience.
Optimization Tips
1Use WebSockets to keep a single persistent connection for real-time data.
2Avoid repeated HTTP polling to reduce network and CPU load.
3Handle incoming WebSocket messages efficiently to minimize DOM updates.
Performance Quiz - 3 Questions
Test your performance knowledge
How do WebSockets improve real-time feature performance compared to HTTP polling?
ABy caching all data on the client
BBy keeping a persistent connection open to push data instantly
CBy sending repeated HTTP requests faster
DBy reducing the size of data packets
DevTools: Performance
How to check: Record a session while interacting with the app; look for network requests and JavaScript event timing related to data updates.
What to look for: Fewer network requests and faster event handling indicate good WebSocket usage; frequent polling shows as repeated network activity spikes.

Practice

(1/5)
1. Why do WebSockets enable real-time features in a NestJS application?
easy
A. Because they create a persistent connection allowing instant two-way communication
B. Because they use HTTP requests to fetch data periodically
C. Because they store data locally on the client device
D. Because they only send data when the user refreshes the page

Solution

  1. Step 1: Understand WebSocket connection type

    WebSockets create a persistent connection between client and server, unlike HTTP which is request-response based.
  2. Step 2: Recognize real-time communication benefit

    This persistent connection allows instant two-way communication, enabling real-time data exchange without delays.
  3. Final Answer:

    Because they create a persistent connection allowing instant two-way communication -> Option A
  4. Quick Check:

    Persistent connection = Real-time communication [OK]
Hint: Remember: WebSockets keep connection open for instant data [OK]
Common Mistakes:
  • Thinking WebSockets use periodic HTTP requests
  • Confusing local storage with real-time data transfer
  • Assuming data sends only on page refresh
2. Which of the following is the correct way to create a WebSocket gateway in NestJS?
easy
A. function createGateway() { return new WebSocket(); }
B. @WebSocketGateway() export class MyGateway {}
C. @GatewaySocket() class MyGateway {}
D. class MyGateway extends WebSocket {}

Solution

  1. Step 1: Identify NestJS WebSocket decorator

    In NestJS, the correct decorator to create a WebSocket gateway is @WebSocketGateway().
  2. Step 2: Confirm class declaration syntax

    The gateway is defined as a class exported with the decorator, matching @WebSocketGateway() export class MyGateway {}.
  3. Final Answer:

    @WebSocketGateway() export class MyGateway {} -> Option B
  4. Quick Check:

    Use @WebSocketGateway() for gateways [OK]
Hint: Look for @WebSocketGateway() decorator in NestJS [OK]
Common Mistakes:
  • Using incorrect decorator names like @GatewaySocket
  • Trying to extend WebSocket directly
  • Using plain functions instead of classes
3. Given this NestJS WebSocket gateway code snippet, what will be the output when a client sends a message 'hello'?
@WebSocketGateway()
export class ChatGateway {
  @SubscribeMessage('message')
  handleMessage(client: any, payload: string): string {
    return `Received: ${payload}`;
  }
}
medium
A. The server throws an error because of missing return type
B. The server broadcasts 'hello' to all clients
C. The server sends back 'Received: hello' to the client
D. The server ignores the message and sends nothing

Solution

  1. Step 1: Analyze the handleMessage method

    The method listens for 'message' events and returns a string with the payload included.
  2. Step 2: Understand return behavior in NestJS WebSocket

    Returning a string sends that string back only to the client who sent the message.
  3. Final Answer:

    The server sends back 'Received: hello' to the client -> Option C
  4. Quick Check:

    Return string = reply to sender [OK]
Hint: Returned string replies only to sender client [OK]
Common Mistakes:
  • Assuming message is broadcast to all clients
  • Expecting an error due to missing explicit return type
  • Thinking server ignores the message
4. Identify the error in this NestJS WebSocket gateway code:
@WebSocketGateway()
export class MyGateway {
  @SubscribeMessage('chat')
  handleChat(client, payload) {
    client.emit('chat', payload);
  }
}
medium
A. Using client.emit instead of this.server.emit for broadcasting
B. Missing type annotations for client and payload parameters
C. handleChat method should return a value to send response
D. The @SubscribeMessage decorator is misspelled

Solution

  1. Step 1: Understand client.emit vs server.emit

    Using client.emit sends message only to that client, but this.server.emit broadcasts to all connected clients.
  2. Step 2: Identify intended behavior

    Since the event is 'chat', usually the message should broadcast to all clients, so this.server.emit is correct.
  3. Final Answer:

    Using client.emit instead of this.server.emit for broadcasting -> Option A
  4. Quick Check:

    Broadcast needs this.server.emit, not client.emit [OK]
Hint: Broadcast uses this.server.emit, not client.emit [OK]
Common Mistakes:
  • Confusing client.emit with broadcast emit
  • Thinking missing types cause runtime error
  • Assuming decorator spelling is wrong
5. You want to build a live sports score update feature using NestJS WebSockets. Which approach best ensures all connected clients receive updates instantly and efficiently?
hard
A. Use client-side timers to simulate score changes without server communication
B. Send HTTP requests every 5 seconds from clients to fetch latest scores
C. Store scores in a database and let clients query on page load only
D. Use a WebSocket gateway with this.server.emit to broadcast score updates to all clients

Solution

  1. Step 1: Identify real-time update requirement

    Live sports scores need instant updates pushed to all clients without delay.
  2. Step 2: Choose efficient communication method

    Using WebSocket gateway with this.server.emit broadcasts updates instantly to all connected clients efficiently.
  3. Final Answer:

    Use a WebSocket gateway with this.server.emit to broadcast score updates to all clients -> Option D
  4. Quick Check:

    Broadcast via WebSocket = instant updates [OK]
Hint: Broadcast with this.server.emit for instant updates [OK]
Common Mistakes:
  • Using periodic HTTP polling instead of WebSockets
  • Relying on client-only timers without server data
  • Fetching data only on page load, missing live updates
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard