SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
  • Long Polling
  • Server-Sent Events (SSE)
  • WebSockets
  • Webhooks
  • WebRTC
  • Short Polling
  • Push Notifications
  • MQTT
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/APIs and Communication/Real-Time Communication

Long Polling

Ask the server, and it waits to answer until it has news.

⏱ 10 min readBeginnerHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

Long polling is a trick to get news from a server quickly using plain HTTP. The browser asks “Anything new?”. The server does not answer right away. It waits until it has news, then replies.

  • Normal (short) polling asks again and again, and most answers are “nothing new”.
  • Long polling holds the question open, so news arrives almost the moment it happens.
  • After each answer, the browser immediately asks again.
  • It works everywhere, with no special protocol. But it costs more than SSE or WebSockets at scale.

02Concept: What is it?

HTTP is built as request and response. The client always speaks first. The server can never start talking by itself. So how does a web page learn that a new message arrived?

Three ways to get news with plain HTTP

Short polling vs long polling
Short polling
📱Client
↓Anything new?
🖥️ServerNo.
↓Anything new? (3 s later)
🖥️ServerNo.
↓Anything new? (3 s later)
🖥️ServerYes! Here.
Long polling
📱Client
↓Anything new? (I will wait)
⏳Server holds the request...waiting...
↓News! Here.
📱Client asks again at once
Wasted question Held-open question Useful answer
Same goal. Very different number of calls.
🧠Remember
Long polling is still request and response. It just lets the server delay the response until it has something to say.

03Real-Life Example

🍵The impatient friend
You are waiting for an exam result. Short polling: you call the school every 5 minutes. “Is it out?” “No.” Click. Again, and again. Long polling: you call once and say “Please keep the phone on. Tell me the moment it is out.” The clerk stays on the line. When the result comes, they tell you. You hang up and call again for the next news.
Waiting for a result
Long polling
You phoning the school
Browser sending an HTTP request
Clerk keeps the line open
Server holds the request
Result comes out
New data is ready
Clerk tells you
Server sends the response
You call again
Browser sends the next request
Clerk says 'no news for 30 minutes, call again'
Request timeout, then reconnect
One round of long polling
  1. 1
    Client sends GET /updates?since=41
    Please tell me about anything after event 41.
  2. 2
    Server has nothing new, so it waits
    The connection stays open. No answer yet.
  3. 3
    Event 42 happens
    A message arrives for this user.
  4. 4
    Server replies at once with event 42
    200 OK, with the data.
  5. 5
    Client shows it, then sends GET /updates?since=42
    A new held-open request starts.

04Why Do We Need It?

We want fresh data without refreshing the page. Short polling is easy, but it has two problems:

🗑️Many wasted calls
If news is rare, 99 out of 100 calls get the answer 'nothing new'. Each call still costs the server work.
🐌Slow news
If you ask every 10 seconds, news can wait up to 10 seconds before you see it.

Making the gap smaller fixes the delay but makes the waste worse. Long polling gets both: few wasted calls and fast news.

Long polling = fast news over plain HTTP, when you cannot use WebSockets or SSE.

05Where Do We Use It?

💬Old chat systems
Early web chat and notification bars used it before WebSockets were common.
🔔Notifications
A bell icon that updates when something new arrives.
🧱Strict networks
Some firewalls and proxies block WebSockets. Plain HTTP still passes.
📚Fallback
Libraries often try WebSockets first and fall back to long polling if that fails (general idea).
🔌Simple integrations
Waiting for a job to finish, a build, a payment, or a file upload.
🧪Quick prototypes
Easy to build with any normal web framework.

06Types / Parts / How It Works

How a long poll works

  1. 1
    Client sends a request
    It says what it already has, such as the last event id or a timestamp.
  2. 2
    Server checks for news
    If there is something newer, it answers straight away.
  3. 3
    Otherwise the server waits
    It keeps the request open, up to a time limit such as 20 to 60 seconds.
  4. 4
    News arrives, or the time runs out
    News: send it. Timeout: send an empty answer (often 204 No Content).
  5. 5
    Client asks again at once
    Go back to step 1 with the newest id.

Short polling vs long polling

PointShort pollingLong polling
Who decides when to answer?Server answers at onceServer answers when it has news (or times out)
Wasted requestsManyFew
Delay for newsUp to the polling gapAlmost none
Server resourcesShort work, many timesOne held connection per user
Needs special protocol?NoNo

What the client code looks like

JavaScript (general idea)
async function poll(lastId) {
  try {
    const res = await fetch("/updates?since=" + lastId, { signal: AbortSignal.timeout(35000) });
    if (res.status === 200) {
      const data = await res.json();
      show(data.events);
      lastId = data.lastId;
    }
  } catch (e) {
    await sleep(2000);      // network error: wait a little, then retry
  }
  poll(lastId);              // ask again straight away
}
poll(0);
VisualizerShort polling vs long pollingPress Play. Change how often news arrives and compare wasted requests and delay.
📰 News happens on the server
Short polling: ask every 3 s
Long polling: wait up to 10 s for an answer
0 s10 s20 s30 s
got newswasted (empty)waiting
Short: requests
0
Short: wasted
0
Short: avg delay
–
Long: requests
0
Long: wasted
0
Long: avg delay
≈0s
plus network time
Press Play. News arrives every 7 s. Watch how each style finds out about it.

07How to Use It / Steps / Implementation

Build it safely

  1. Send a position. Use since=lastEventId so no event is missed between two requests.
  2. Set a timeout on the server (for example 30 s), shorter than any proxy or load balancer timeout. Reply empty, and the client reconnects.
  3. Wake waiting requests fast. Use a message bus or pub/sub (Redis, for example) to tell the right waiting request that news arrived.
  4. Do not block a thread per request. Use async or event-driven code. Thousands of waiting requests are fine only if each one is cheap.
  5. Back off on errors. If the server fails, wait 1 s, 2 s, 4 s... before asking again. Do not hammer it.
  6. Add jitter. Add a small random wait so that all clients do not reconnect at the same second.
💡Do not lose events
Between one response and the next request, new events may happen. That is why you ask “give me everything after id X”. The server must keep a short history to answer it.

08Key Terms to Know

TermMeaning in easy words
PollingAsking the server again and again if there is news
Short pollingPolling on a timer. The server answers at once, even with 'nothing new'
Long pollingThe server holds the request open until it has news or times out
TimeoutThe longest time the server will hold a request before replying empty
Event id / cursorA marker that tells the server what you already have
BackoffWaiting longer after each failure before trying again
JitterA small random delay so many clients do not act at the same instant
Wasted requestA request whose answer is 'nothing new'
StatelessThe server remembers nothing between requests. Long polling is mostly stateless, apart from the waiting request

09Pros, Cons and Trade-offs

✅ Pros
  • Works with plain HTTP, proxies, firewalls and every browser
  • Easy to understand and to build
  • Far fewer wasted requests than short polling
  • News arrives almost at once
  • Can reuse normal tools: HTTP logs, auth and caching rules
⚠️ Cons
  • Each user holds one open request, which uses server memory and connections
  • Every message needs a new request, so headers are repeated (extra overhead)
  • Gaps between requests can cause missed events if you are careless
  • Only the server can answer once per request. It is not true two-way talk
  • Proxies and load balancers may close long waits too early

Trade-offs: which one to choose?

Long pollingSSEWebSockets
DirectionServer to client (one reply per request)Server to clientBoth ways
ProtocolPlain HTTPHTTP, kept openUpgrades to its own protocol
Auto-reconnectYou write itBuilt in (EventSource)You write it
Firewall friendlyBestGoodSometimes blocked
Cost per messageHighest (new request)LowLowest
Best forFallback, simple needsLive feeds, notificationsChat, games, collaboration

10Common Problems and Mistakes

Common mistakes

  1. No cursor. Events between two polls are lost. Always send the last id.
  2. Timeout longer than the proxy's. A load balancer closes the request at 60 s while your server waits 120 s. Keep the server shorter.
  3. One thread per waiting request. 10,000 users means 10,000 stuck threads. Use async I/O.
  4. Reconnecting in a tight loop on errors. A failing server gets hit even harder. Use backoff.
  5. Thundering herd. After a restart, every client reconnects together. Add jitter.
  6. Waking all waiters for every event. Only wake the users the event is for.
⏱️Duplicate events
A response is lost on the network and the client retries. Give events ids so the client can ignore repeats.
📦Large backlog
A client was away for hours. Return a bounded page of events, or tell it to do a full refresh.

11Real-World Examples

💬Early web chat
Many early browser chat and notification systems used long polling (general idea).
🔁Realtime libraries
Libraries such as Socket.IO can fall back to long polling when WebSockets are unavailable.
🏗️Job status
A page that waits for 'your report is ready' often waits with a long poll.
🔔Queue consumers
Some message systems let consumers 'long poll' for messages, such as Amazon SQS, so they do not waste empty calls.
Many users, one server
👩
👨
🧑
→↓waiting requests
⚖️Load balancertimeout longer than server's
→↓
🖥️App serversasync, many held requests
↔wake-up
📣Pub/sub bus
Each user has one waiting request. A message bus wakes only the right ones.

12Related Topics to Read Next

Server-Sent Events (SSE)→

One long-lived response that keeps pushing events, with built-in reconnect.

WebSockets→

True two-way messages on one open connection.

Webhooks→

Instead of you waiting, the other system calls you.

What is an API?→

The request and response idea that long polling bends.

Message Queues→

Queue consumers often long poll for messages.

What are Load Balancers?→

They decide how long a held request may live.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔What: the client asks, and the server waits to answer until it has news.
  • ✔Why: fewer wasted calls than short polling, and almost no delay.
  • ✔Loop: request, wait, answer, request again at once.
  • ✔Always: send a cursor (last event id), set a timeout, add backoff and jitter.
  • ✔Cost: one held request per user, and headers on every round.
  • ✔Compare: SSE is one-way push. WebSockets are two-way. Long polling is the most compatible.
  • ✔One line: “Long polling fakes a push using plain HTTP by holding the request open.”
← Previous
mTLS and Request Signing (HMAC)
Next →
Server-Sent Events (SSE)