0
0
Expressframework~8 mins

Emitting and receiving messages in Express - Performance & Optimization

Choose your learning style9 modes available
Performance: Emitting and receiving messages
MEDIUM IMPACT
This concept affects server response time and network latency impacting how fast messages are sent and received between client and server.
Sending real-time messages between client and server
Express
app.get('/send', (req, res) => {
  // Using setImmediate to batch emits asynchronously
  let i = 0;
  function emitBatch() {
    for(let count = 0; count < 100; count++, i++) {
      io.emit('message', { text: `Message ${i}` });
      if(i >= 10000) return res.send('Messages sent');
    }
    setImmediate(emitBatch);
  }
  emitBatch();
});
Batching emits asynchronously prevents blocking the event loop, allowing other requests to be handled smoothly.
📈 Performance GainNon-blocking emits reduce INP and improve server responsiveness
Sending real-time messages between client and server
Express
app.get('/send', (req, res) => {
  // Emitting message inside a heavy synchronous loop
  for(let i = 0; i < 10000; i++) {
    io.emit('message', { text: `Message ${i}` });
  }
  res.send('Messages sent');
});
Emitting many messages synchronously blocks the event loop, delaying other requests and responses.
📉 Performance CostBlocks event loop causing delayed responses and higher INP
Performance Comparison
PatternEvent Loop ImpactNetwork LoadClient ResponsivenessVerdict
Synchronous heavy emitsBlocks event loopHigh burst loadDelayed input response[X] Bad
Asynchronous batched emitsNon-blocking event loopEvenly distributed loadFast input response[OK] Good
Rendering Pipeline
Message emitting triggers network I/O and event loop processing on the server, affecting how quickly clients receive updates.
Event Loop
Network I/O
Client Rendering
⚠️ BottleneckEvent Loop blocking due to synchronous heavy emits
Core Web Vital Affected
INP
This concept affects server response time and network latency impacting how fast messages are sent and received between client and server.
Optimization Tips
1Avoid synchronous loops emitting many messages to prevent event loop blocking.
2Batch or throttle message emits to spread network load evenly.
3Monitor event loop delays and network timing to optimize message flow.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance issue with emitting many messages synchronously in Express?
AIt increases bundle size significantly
BIt causes layout shifts on the client
CIt blocks the event loop causing delayed responses
DIt reduces server memory usage
DevTools: Network and Performance panels
How to check: Open DevTools, go to Network panel to observe message packets timing and size; use Performance panel to record server response and event loop delays.
What to look for: Look for long blocking tasks in Performance and clustered network packets causing delays in Network panel