API Fundamentals
/Intermediate
Long Polling
Definition
A variation of standard polling where the server holds the client's HTTP request open until new data actually becomes available, rather than instantly returning an empty response.
Explain Like I'm New
The kid asks 'Are we there yet?'. The parent doesn't answer immediately. The parent waits 2 hours in silence, and the exact second they arrive, the parent says 'Yes'. The kid instantly hangs up, celebrates, and calls back later if needed.
Real World Example
Early chat applications before WebSockets were invented. The browser sends an HTTP request. The Node.js server literally `awaits` a new message event in its code. The connection stays pending in the browser's network tab for up to 30 seconds. Once a message arrives, the server completes the response.
Common Use Cases
- •Real-time data without WebSockets
- •Strict corporate firewalls
Terminal Output
bash / terminal
/*
Conceptual Flow of Long Polling
*/
// 1. Client: GET /api/messages/wait
// 2. Server: (Does not respond immediately. Keeps connection open in memory.)
// ... 15 seconds pass ...
// 3. User B sends a message to the database.
// 4. Server: Sees the message, immediately sends it to Client and closes the connection.
// 5. Client: Receives message, processes it, and INSTANTLY sends a new GET /api/messages/wait.
Interview Questions
basic
- Does Long Polling reduce the number of HTTP requests compared to standard (Short) Polling?
intermediate
- What happens if no data arrives during a Long Polling request and the server's timeout limit (e.g., 30 seconds) is reached?