What is Long Polling and how does it improve on short polling?

Topic: microservices, Real-Time Communication. Level: Intermediate.

Answer

In long polling the client sends a request and the server **holds it open** until data is available (or a timeout), then responds; the client immediately re-requests. This gives near-real-time delivery without constant empty responses — the connection only returns when there's something to send. It works over standard HTTP (firewall/proxy friendly). Drawbacks: a held request consumes a server connection/thread (use async/non-blocking servers), reconnection overhead per message, and it's still request/response (half-duplex), not true push. ```js // Client: re-issues the request as soon as the server responds async function poll() { try { const res = await fetch('/api/updates') // server holds this until data/timeout if (res.ok) handle(await res.json()) } finally { poll() // immediately wait for the next event } } poll() ``` ```java // Server: hold the request asynchronously, complete it when an event arrives @GetMapping("/api/updates") DeferredResult<Update> updates() { DeferredResult<Update> out = new DeferredResult<>(30_000L); // timeout subscribers.add(out); // completed later by publisher return out; } ```