0
0
Node.jsframework~8 mins

Long polling as fallback in Node.js - Performance & Optimization

Choose your learning style9 modes available
Performance: Long polling as fallback
MEDIUM IMPACT
This affects the responsiveness and load on the server and client during real-time data updates when WebSocket is unavailable.
Implementing real-time updates when WebSocket is not supported
Node.js
app.get('/updates', (req, res) => {
  const checkForUpdates = () => {
    if (dataAvailable()) {
      res.json({ data: getData() });
    } else {
      setTimeout(checkForUpdates, 1000); // retry after 1 second
    }
  };
  checkForUpdates();
});
This pattern checks for data availability before responding, reducing unnecessary open connections and improving responsiveness.
📈 Performance GainReduces server load by closing connections promptly when no data is available
Implementing real-time updates when WebSocket is not supported
Node.js
app.get('/updates', (req, res) => {
  setTimeout(() => {
    res.json({ data: 'new data' });
  }, 10000); // waits 10 seconds before responding
});
This naive long polling holds connections open for a fixed time regardless of data availability, causing unnecessary server resource use and delayed updates.
📉 Performance CostTriggers many open connections and high server memory usage under load
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Naive long polling with fixed delayMinimal DOM changes0 reflows triggered by polling itselfDelayed paint due to waiting on response[X] Bad
Conditional long polling with data checkMinimal DOM changes0 reflows triggered by polling itselfFaster paint when data is ready[OK] Good
Rendering Pipeline
Long polling affects the interaction responsiveness by keeping HTTP connections open, which delays the browser's next paint until data arrives and the response completes.
Network
JavaScript Execution
Paint
⚠️ BottleneckNetwork latency and server response time are the main bottlenecks.
Core Web Vital Affected
INP
This affects the responsiveness and load on the server and client during real-time data updates when WebSocket is unavailable.
Optimization Tips
1Avoid holding HTTP connections open longer than necessary.
2Check for data availability before responding to reduce latency.
3Use long polling only as a fallback when WebSocket is unavailable.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance drawback of naive long polling?
AIt holds HTTP connections open unnecessarily long, increasing server load.
BIt causes excessive DOM reflows on the client.
CIt blocks the browser's main thread permanently.
DIt increases the size of JavaScript bundles.
DevTools: Network
How to check: Open DevTools, go to Network tab, filter XHR requests, observe the duration of long polling requests and their frequency.
What to look for: Look for long-held HTTP connections and delayed responses indicating inefficient long polling.