Topic Overview
Keep-alive vs Long Polling
Compare HTTP keep-alive and long polling techniques for maintaining connections and real-time communication.
Keep-alive vs Long Polling
Why This Matters
Think of keep-alive like reusing the same phone line for multiple calls. Instead of hanging up and dialing again for each call, you keep the line open and make multiple calls. Long polling is like calling someone and staying on the line until they have something to tell you. Keep-alive reduces connection overhead, while long polling enables real-time updates.
This matters because creating TCP connections has overhead (three-way handshake). If you're making many requests, creating a new connection for each request is slow. Keep-alive reuses connections, reducing overhead. Long polling enables real-time updates without the overhead of constant polling, but it ties up server resources.
In interviews, when someone asks "How would you implement real-time updates?", they're testing whether you understand keep-alive, long polling, and WebSockets. Do you know when to use each? Do you understand the trade-offs? Most engineers don't. They just use polling and wonder why it's inefficient.
What Engineers Usually Get Wrong
Most engineers think "long polling is the same as keep-alive." But they're different. Keep-alive reuses TCP connections for multiple HTTP requests. Long polling is a technique where the server holds a request open until it has data to send. Keep-alive reduces connection overhead, while long polling enables real-time updates.
Engineers also don't understand that long polling ties up server resources. Each long-polling request holds a connection open. If you have 10,000 clients doing long polling, you have 10,000 open connections. This can exhaust server resources. WebSockets are often better for real-time updates because they're more efficient.
How This Breaks Systems in the Real World
A service was using long polling for real-time updates. Each client held a connection open for up to 30 seconds. With 10,000 clients, the service had 10,000 open connections. The server ran out of file descriptors. New connections were rejected. The service became unavailable. The fix? Use WebSockets instead of long polling. WebSockets are more efficient—one connection per client, bidirectional, and lower overhead.
Another story: A service was making many HTTP requests but wasn't using keep-alive. Each request created a new TCP connection. The three-way handshake overhead (50-100ms per request) added up. Response times were slow. The fix? Enable HTTP keep-alive. Reuse TCP connections for multiple requests. This reduced connection overhead significantly.
HTTP Keep-alive
Keep-alive reuses the same TCP connection for multiple HTTP requests.
Without Keep-alive
Request 1: TCP connection → Request → Response → Close
Request 2: TCP connection → Request → Response → Close
Request 3: TCP connection → Request → Response → Close
Overhead: 3-way handshake for each request
With Keep-alive
TCP connection (established once)
Request 1 → Response 1
Request 2 → Response 2
Request 3 → Response 3
Connection stays open
Benefits: Reuse connection, reduce overhead
Long Polling
Long polling holds HTTP request open until server has data to send.
How Long Polling Works
1. Client sends request
2. Server holds request (doesn't respond immediately)
3. When data available: Server responds
4. Client immediately sends new request
5. Repeat
Use case: Real-time updates when WebSockets not available
Comparison
| Feature | Keep-alive | Long Polling |
|---|---|---|
| Purpose | Reuse connection | Real-time updates |
| Connection | Stays open | Held open until data |
| Overhead | Reduced (reuse) | Higher (held connections) |
| Use case | Multiple requests | Real-time notifications |
| Latency | Request-response | Lower (server push) |
Examples
HTTP Keep-alive
1import axios from 'axios';23// Session with keep-alive (axios reuses connections by default)4const session = axios.create({5 httpAgent: new (require('http').Agent)({ keepAlive: true }),6 httpsAgent: new (require('https').Agent)({ keepAlive: true })7});89// Multiple requests reuse connection10const response1 = await session.get('https://api.example.com/data1');
Long Polling
1import axios from 'axios';23async function longPoll(url: string, timeout: number = 30000) {4 // Long polling request5 while (true) {6 try {7 // Server holds request until data available8 const response = await axios.get(url, { timeout });910 if (response.status === 200) {11 const data = response.data;12 processData(data);13 }
Long Polling Server
1import express from 'express';23const app = express();45app.get('/poll', async (req, res) => {6 // Long polling endpoint7 // Wait for data (max 30 seconds)8 const startTime = Date.now();9 const timeout = 30000;1011 while (Date.now() - startTime < timeout) {12 // Check if data available13 const data = await checkForUpdates();14 if data
Common Pitfalls
- Keep-alive timeout: Connection closed prematurely. Fix: Configure appropriate timeout
- Long polling connections: Too many held connections. Fix: Limit connections, use timeouts
- Not using keep-alive: Wasting resources. Fix: Enable keep-alive for multiple requests
- Long polling overhead: High server load. Fix: Use WebSockets for better performance
Interview Questions
Beginner
Q: What is HTTP keep-alive and how does it differ from long polling?
A:
HTTP Keep-alive:
Reuses TCP connection for multiple requests:
TCP connection (established once)
Request 1 → Response 1
Request 2 → Response 2
Request 3 → Response 3
Connection stays open
Benefits:
- Reduced overhead: No new handshake per request
- Faster: Reuse existing connection
- Efficient: Multiple requests on one connection
Long Polling:
Holds HTTP request open until data available:
1. Client sends request
2. Server holds request (doesn't respond)
3. When data available: Server responds
4. Client immediately sends new request
Use case: Real-time updates (when WebSockets not available)
Differences:
| Feature | Keep-alive | Long Polling |
|---|---|---|
| Purpose | Reuse connection | Real-time updates |
| Connection | Open for requests | Held until data |
| Overhead | Reduced | Higher |
Intermediate
Q: Explain how long polling works and when you would use it vs WebSockets.
A:
Long Polling Process:
-
Client sends request
GET /updates -
Server holds request
Server doesn't respond immediately Waits for data (up to timeout) -
Data available
Server responds with data -
Client immediately requests again
GET /updates (new request)
Example:
1// Client2while (true) {3 const response = await fetch('/updates', {4 signal: AbortSignal.timeout(30000)5 });6 if (response.status === 200) {7 const data = await response.json();8 process(data);9 }10 // Immediately send new request11}
Long Polling vs WebSockets:
| Feature | Long Polling | WebSockets |
|---|---|---|
| Protocol | HTTP | WebSocket |
| Connection | HTTP request held | Persistent connection |
| Overhead | Higher (new request each time) | Lower (one connection) |
| Latency | Higher | Lower |
| Complexity | Simpler | More complex |
| Browser support | Universal | Modern browsers |
When to use:
- Long polling: Simple, works everywhere, WebSockets not available
- WebSockets: Real-time, low latency, bidirectional
Senior
Q: Design a system that uses both keep-alive and long polling efficiently. How do you manage connections, handle timeouts, and optimize for performance?
A:
1class HybridConnectionSystem {2 private keepAliveManager: KeepAliveManager;3 private longPollManager: LongPollManager;45 constructor() {6 this.keepAliveManager = new KeepAliveManager();7 this.longPollManager = new LongPollManager();8 }910 // 1. Keep-alive for Regular Requests11 class KeepAliveManager {12 private connections: Map<string, Connection>;1314 async getConnection(host: string): Promise<Connection>
Features:
- Keep-alive: Reuse connections for regular requests
- Long polling: Real-time updates
- Connection management: Optimize, limit, timeout
Failure Stories You'll Recognize
The Exhausted Connections: A service was using long polling for real-time updates. Each client held a connection open for up to 30 seconds. With 10,000 clients, the service had 10,000 open connections. The server ran out of file descriptors. New connections were rejected. The service became unavailable. The fix? Use WebSockets instead of long polling. WebSockets are more efficient—one connection per client, bidirectional, and lower overhead.
The Slow Requests: A service was making many HTTP requests but wasn't using keep-alive. Each request created a new TCP connection. The three-way handshake overhead (50-100ms per request) added up. Response times were slow. The fix? Enable HTTP keep-alive. Reuse TCP connections for multiple requests. This reduced connection overhead significantly.
The Resource Exhaustion: A service was using long polling but didn't set connection limits. During a traffic spike, 50,000 clients were doing long polling simultaneously. The server ran out of resources (memory, file descriptors). The service crashed. The fix? Set connection limits. Use load balancers to distribute connections. Or use WebSockets, which are more efficient.
What Interviewers Are Really Testing
They want to hear you talk about keep-alive and long polling as tools with trade-offs, not just techniques. Junior engineers say "keep-alive reuses connections, long polling holds requests open." Senior engineers say "keep-alive reduces connection overhead by reusing TCP connections. Long polling enables real-time updates but ties up server resources. For real-time updates, WebSockets are often better—more efficient and bidirectional."
When they ask "How would you implement real-time updates?", they're testing:
-
Do you understand keep-alive, long polling, and WebSockets?
-
Do you know when to use each?
-
Can you optimize connection usage?
-
HTTP/1 vs HTTP/2 vs HTTP/3 - HTTP keep-alive is a feature of HTTP/1.1, understanding HTTP versions explains keep-alive benefits
-
Connection Pooling - Keep-alive enables connection pooling, understanding pooling helps optimize keep-alive usage
-
WebSockets - WebSockets are an alternative to long polling, understanding polling helps appreciate WebSocket benefits
-
Three-Way Handshake (TCP) - Keep-alive avoids repeated TCP handshakes, understanding handshake overhead explains keep-alive benefits
-
TCP Connection Termination - Keep-alive maintains connections, understanding connection termination explains when keep-alive is useful
-
Keep-alive: Reuse TCP connection for multiple HTTP requests
-
Long polling: Hold HTTP request open until data available
-
Keep-alive benefits: Reduced overhead, faster, efficient
-
Long polling use: Real-time updates when WebSockets not available
-
Comparison: Keep-alive for efficiency, long polling for real-time
-
Best practices: Use keep-alive for multiple requests, long polling for real-time, consider WebSockets
How InterviewCrafted Will Teach This
We'll teach this through production failures, not definitions. Instead of memorizing "keep-alive reuses connections," you'll learn through scenarios like "why did our server run out of file descriptors?"
You'll see how connection management affects performance and resource usage. When an interviewer asks "how would you implement real-time updates?", you'll think about keep-alive, long polling, WebSockets, and trade-offs—not just "use long polling."
Key Takeaways
Keep-alive: Reuse TCP connection for multiple HTTP requests
Long polling: Hold HTTP request open until data available
Keep-alive benefits: Reduced overhead, faster, efficient
Long polling use: Real-time updates when WebSockets not available
Comparison: Keep-alive for efficiency, long polling for real-time
Best practices: Use keep-alive for multiple requests, long polling for real-time, consider WebSockets
Related Topics
HTTP/1 vs HTTP/2 vs HTTP/3
HTTP keep-alive is a feature of HTTP/1.1, understanding HTTP versions explains keep-alive benefits
Connection Pooling
Keep-alive enables connection pooling, understanding pooling helps optimize keep-alive usage
WebSockets
WebSockets are an alternative to long polling, understanding polling helps appreciate WebSocket benefits
Three-Way Handshake (TCP)
Keep-alive avoids repeated TCP handshakes, understanding handshake overhead explains keep-alive benefits
TCP Connection Termination
Keep-alive maintains connections, understanding connection termination explains when keep-alive is useful
What's next?