Skip to content

    Frontend System Design

    Polling, Server-Sent Events and WebSockets

    Compare polling, long polling, Server-Sent Events and WebSockets from the browser: latency, request cost, upstream messages and silent failure, with a lab.

    By Published 16 min read

    • frontend-system-design
    • real-time
    • server-sent-events
    • websockets
    Share

    Flagship lessonintermediateInteractive simulatorFrontend System Design

    Before this: DNS, TCP, TLS and the Request Lifecycle, HTTP/1.1, HTTP/2 and HTTP/3 for Front-End Engineers

    What you'll learn: By the end of this lesson you will be able to explain why a page cannot simply wait for the server to speak, describe how short polling, long polling, Server-Sent Events (SSE) and WebSockets each get an update to the browser, estimate what each costs in latency and requests, say which of them lets the client send on the same connection, name what breaks each one (buffering proxies, idle connections, a dead path nobody announces), and choose the weakest transport that meets the freshness a screen needs.

    You are waiting for a parcel. You can walk to the door every hour and look (polling). You can stand at the door and refuse to leave until something arrives or you give up, then walk back and stand there again (long polling). You can ask the courier to leave a one-way radio on your desk that crackles when the parcel is near (SSE). Or you can keep a phone line open so either of you can speak whenever you like (a WebSocket). Every option works. They differ in how often you walk, how long the news waits, who can talk, and how you find out that the line has gone dead.

    The running example is the order-tracking page of the ShopStream grocery marketplace: a shopper watches an order move from "packed" to "delivered". The event feed and every number in the lab are made up for the lesson. Request lifecycle basics are in DNS, TCP, TLS and the Request Lifecycle, and what HTTP/2 changes about connections is in HTTP/1.1, HTTP/2 and HTTP/3 for Front-End Engineers.

    The core idea

    1. A browser asks; a server cannot start the conversation. HTTP is request and response, so every "live" feature is a way around that: ask often, hold the question open, keep one answer open, or change protocol.
    2. The four techniques differ on three things: who can speak (one way or both), how many requests an update costs, and who notices when the connection is broken.
    3. Choose the weakest transport that meets the freshness the screen needs. A page that is fine with ten-second-old data should not hold a connection open, and a chat window should not poll.

    Three illustrations run through the lesson: a minimal example (the lab: one feed of seven events through all four transports), a realistic example (the tracking page) and a failure example (a connection that dies without a word).

    Figure 1. One feed, four ways to reach the page

    The tracking page reaches the same event feed through four different transportsTracking page to Polling; Tracking page to Long polling; Tracking page to SSE; Tracking page to WebSocket; Polling to Order events; Long polling to Order events; SSE to Order events; WebSocket to Order eventsTracking page: in the browserTracking pagein the browserPolling: ask every N sPollingask every N sLong polling: ask, wait, askLong pollingask, wait, askSSE: one open responseSSEone open responseWebSocket: upgrade, framesWebSocketupgrade, framesOrder events: numbered feedOrder eventsnumbered feed

    How to read this: solid arrows are request and response, dashed flowing arrows are a connection that stays open. The feed is the same behind all four; only the way it reaches the page changes.

    Short polling: ask again later

    RFC 6202 describes the traditional technique, "short polling": a client sends regular requests to the server. The server answers at once, with news or without, and the client waits before it asks again. Nothing is held open, so it works wherever HTTP works, which is its great strength.

    Its cost is built in. An event that happens just after a poll waits almost a whole interval, so the worst delay is the interval plus the network, and the average is about half an interval. Shortening the interval cuts the wait and multiplies the requests, most of which answer "nothing yet". The lab prints this trade in its section 2: the same feed polled every 15 s, 5 s, 1 s and 250 ms.

    A polling loop in the browser is small. This is a sketch with browser APIs, not something the lab runs:

    async function pollForever(signal: AbortSignal, onEvents: (events: unknown[]) => void) {
      let after = 0;
      while (!signal.aborted) {
        const res = await fetch(`/api/orders/42/events?after=${after}`, { signal });
        const events: { id: number }[] = await res.json();
        if (events.length > 0) {
          after = events[events.length - 1]!.id;
          onEvents(events);
        }
        await new Promise((r) => setTimeout(r, 5000));
      }
    }

    The after cursor matters: it lets the client say "everything after the last event I saw", so a slow poll loses nothing. Cancelling with an AbortSignal and handling failures are covered in Request Cancellation, Timeouts and Race Conditions; a conditional request can also make an unchanged answer small, which HTTP Caching explains.

    Long polling: hold the question open

    Long polling changes one thing: the server does not answer an empty poll. RFC 6202 says the server holds the request until an event occurs or a timeout passes, and the client sends the next request as soon as it gets an answer. The RFC puts the average latency "close to one network transit" and the maximum "over three network transits", because an event can arrive while the client is between two requests. It adds that if several messages queue up for a client, "they might be delivered in a batch within a single long poll response". On timeouts it says that "generally 30 seconds is a safer value", after experiments that succeeded with timeouts as high as 120 seconds.

    Figure 2. An event that arrives between two long polls waits for the next one

    sequenceDiagram accTitle: Long polling with events queued between two requests accDescr: The client has a request held at the server. Event 4 happens and the server answers. While the client is sending its next request, events 5 and 6 happen. The server holds them until the new request arrives and then answers with both events in one response. participant C as Client participant S as Server C->>S: request (held) Note over S: event 4 happens S-->>C: answer with event 4 Note over S: events 5 and 6 happen while no request is waiting C->>S: next request S-->>C: answer with events 5 and 6 together

    How to read this: only one request is ever waiting. Events that happen in the gap are queued, so they arrive late and together, which is where the "over three network transits" comes from.

    Every long poll is a full HTTP request and response, so RFC 6202 notes that headers can be a large share of the bytes when messages are small. The client also carries the cost of re-asking: a held request uses a connection, and the RFC discusses how many connections a browser will open to one server. The lab's section 3 shows the batch above: events 5 and 6 come back in one answer, with latencies of 120 ms and 90 ms instead of 50.

    Server-Sent Events: one response that never ends

    SSE moves the held request to the browser's standard API. MDN describes EventSource as opening a persistent connection to an HTTP server that sends events in text/event-stream format, and stresses that it is one-way: data flows from the server to the client only.

    The server answers with the media type text/event-stream and writes lines. MDN lists the fields: event names the event type, data is the payload (several consecutive data lines are joined with newlines), id sets the event's id, and retry sets the reconnection time in milliseconds if its value is an integer. A line starting with a colon is a comment, and servers can send one periodically to stop the connection timing out. The HTML standard suggests a comment "every 15 seconds or so" for proxies that drop idle connections.

    The browser does the recovery work. By default, MDN says, a closed connection is restarted. The standard describes the steps: wait the reconnection time, then reconnect and send the last event id in a Last-Event-ID header, so the server knows where to resume. The standard says the connection fails, and does not reconnect, if the response status is not 200 or the content type is wrong, and that a server can stop reconnection with 204 No Content. The initial reconnection time is "an implementation-defined value, probably in the region of a few seconds". The constructor accepts a URL and one option, withCredentials; there is no way to set a header. Authentication therefore rides on cookies (or a token in the URL, which brings its own risks).

    Figure 3. What a page sees of an EventSource connection

    stateDiagram-v2 accTitle: EventSource readyState accDescr: The state starts as connecting. When the connection opens it becomes open. If a non-fatal failure drops the connection, it goes back to connecting and reconnects after the reconnection time. A fatal error, such as a response that is not status 200, or a call to close moves it to closed, which is final. [*] --> CONNECTING CONNECTING --> OPEN: connection opened OPEN --> CONNECTING: connection lost, reconnect after the delay CONNECTING --> CLOSED: fatal error OPEN --> CLOSED: close() CLOSED --> [*]

    How to read this: the three states are 0, 1 and 2 in the standard. The loop between the first two is the automatic recovery; CLOSED is the only state the browser will not leave on its own.

    A sketch of the client side, again not run by the lab:

    const source = new EventSource("/api/orders/42/stream");
    source.addEventListener("status", (e) => render(JSON.parse((e as MessageEvent).data)));
    source.onerror = () => showReconnectingBadge();
    // later: source.close();

    One limit matters on busy pages. MDN says that when SSE is not used over HTTP/2 the limit on open connections is per browser and domain, "set to a very low number (6)", which hurts when a user opens several tabs; with HTTP/2 the number of simultaneous streams is negotiated and defaults to 100.

    WebSockets: change the protocol

    A WebSocket starts as an HTTP request and then stops being HTTP. RFC 6455 requires the opening request to be a GET of at least HTTP/1.1 with Upgrade: websocket, Connection: Upgrade, a Sec-WebSocket-Version of 13 and a random 16-byte key. The server answers 101, and from then on both sides exchange frames, not HTTP messages. MDN describes the API as opening "a two-way interactive communication session", so the page can send and receive without polling. The browser object has four states, CONNECTING, OPEN, CLOSING and CLOSED (0 to 3), and a send() method.

    Two limits are worth knowing now. First, MDN states that the WebSocket interface has no way to apply backpressure: if messages arrive faster than the page processes them, the page fills memory, burns CPU, or both. Second, the constructor takes a URL and optional sub-protocol names, with no option for custom headers, and RFC 6455 says the protocol "doesn't prescribe any particular way that servers can authenticate clients during the WebSocket handshake" (cookies, HTTP authentication and TLS are the examples it names). RFC 8441 defines how to run WebSockets over one stream of an HTTP/2 connection, with an extended CONNECT instead of the key and accept headers. Frames, masking, closing and the rest are the subject of the next lesson, WebSockets in Depth.

    The other side of this topic

    The backend lesson WebSockets, Server-Sent Events and Long Polling covers what the server holds for each transport: held requests, event ids and replay, idle timeouts, and what a load balancer does. The front end's side is smaller but just as real: the cost of an open connection per tab, what to show while reconnecting, and what to do when a connection that looks open has stopped delivering.

    Comparing the four

    Short polling Long polling SSE WebSocket
    Who can speak on it Client asks, server answers Client asks, server answers late Server only Both
    Requests per update One per interval, mostly empty One per answer One request in total One upgrade in total
    Wait for an update (lab, illustrative) Up to an interval About one network transit, more after a gap One network transit One network transit
    Client messages Another request Another request Another request A frame on the same connection
    Recovery from a drop The next poll The next request Built in, with Last-Event-ID You write it
    Data Anything HTTP carries Anything HTTP carries Text events Text or binary frames
    Main weakness Latency or wasted requests Re-asking, batches, held connections One direction, six connections over HTTP/1.x No backpressure, no header, you own recovery

    Figure 4. A way to choose

    flowchart TD accTitle: Choosing a real-time transport accDescr: First ask whether the screen needs updates faster than every several seconds. If not, poll. If it does, ask whether the client must send messages often on the same channel. If so, use a WebSocket. If not, use SSE. If streaming does not survive the network in between, fall back to long polling or polling. A{"Is an update every
    few seconds enough?"} -->|"yes"| P["Short polling
    at that interval"] A -->|"no"| B{"Does the client send
    often on the same channel?"} B -->|"yes"| W["WebSocket"] B -->|"no"| S["SSE"] S --> F{"Does the stream survive
    every network on the path?"} W --> F F -->|"no"| L["Fall back to long
    polling or polling"] F -->|"yes"| K["Keep the stream
    and watch it"]

    How to read this: start with the weakest transport and move right only when the screen needs it. The last step is real: RFC 6202 notes that an intermediary may legally buffer an entire response before passing it on, in which case streaming over HTTP does not work through it.

    When a connection dies without a word

    A held connection that fails in the middle gives the page no news. If a router drops the path, or a proxy buffers a stream, the page just stops hearing. It cannot tell "nothing happened" from "nothing is arriving". The usual defence is a heartbeat, a message with no event in it sent at a steady rhythm, plus a watchdog on the client that gives up on the connection after a limit of silence and reconnects. Polling needs neither: every poll is its own test.

    The lab models this with one made-up feed and a path that goes dead at 52 s. Without a heartbeat, a 15 s limit trips twice on healthy gaps in the feed (false alarms), and a 25 s limit avoids those but waits longer. A 5 s heartbeat allows the short limit with no false alarms. Heartbeats and what they cost are the subject of a later lesson, Heartbeats, Backpressure and Delivery Guarantees.

    Build it: four transports over one feed

    Goal. Run one feed of seven server events through four transports in a model and read what each does to latency, requests, upstream messages and silent failure.

    Setup. The lab is in the course's example workspace (Node 26.13.1, pnpm). It is pure logic in virtual milliseconds: no network, no timer, no browser.

    cd examples/frontend
    pnpm install
    cd labs/push-transports-model
    pnpm test           # 17 tests
    node src/demo.ts

    Steps.

    1. Run the tests, then the demo, and compare it with the output below.
    2. In section 1, find the event that waits 3900 ms under polling and 50 ms under SSE. Polling's wait comes from the 5000 ms interval, not the network.
    3. In section 3, find the answer that carries two events: they happened in the gap between two long polls.
    4. In section 5, read the rows for a silent feed twice: the same 15 s limit gives two false alarms without a heartbeat and none with one.

    Expected output, captured from a real run (Node 26.13.1, 2026-12-01):

    Four ways to move server events to a page (virtual time, illustrative numbers)
    one-way delay 50 ms, window 20000 ms, 7 server events
    
    === 1. Same events, four transports
    transport        requests  empty   got  max ms  mean ms  per-event latency (ms)
    polling                 5      2     7    3900     1859  3900 3800 1000 1100 1070 1040 1100
    long-polling            7      1     7     120       66  50 50 50 50 120 90 50
    sse                     1      0     7      50       50  50 50 50 50 50 50 50
    websocket               1      0     7      50       50  50 50 50 50 50 50 50
    (polling every 5000 ms; long polling holds 30000 ms; 'got' is events the client holds at the end)
    
    === 2. Polling: a shorter interval buys lower latency with more requests
    interval ms  requests  empty  max ms  mean ms
          15000         2      1   13900     8287
           5000         5      2    3900     1859
           1000        21     16    1040      573
            250        81     76     290      144
    
    === 3. Long polling: events during the gap between requests arrive together
    request  sent->answer arrives (ms)  events in the answer
          1      0 ->  1250               #1
          2   1250 ->  1350               #2
          3   1350 ->  4150               #3
          4   4150 ->  9050               #4
          5   9050 ->  9150               #5 #6
          6   9150 -> 14050               #7
          7  14050 -> 44150               (none: hold timed out)
    answer 5 carried #5 and #6 together: latencies 120 and 90 ms
    
    === 4. The client also has to talk: messages sent up while listening (4 messages)
    transport        extra requests for 4 upstream messages
    polling            4
    long-polling       4
    sse                4
    websocket          0
    
    === 5. A connection that dies without a word (the path goes dead at 52000 ms)
    setup                               limit ms  false alarms  noticed at ms  delay after death ms
    polling every 5000                     15000             0          65100                 13100
    long polling, hold 30000               15000             2          56050                  4050
    long polling, hold 30000               35000             0          76050                 24050
    SSE or WebSocket, no heartbeat         15000             2          56050                  4050
    SSE or WebSocket, no heartbeat         25000             0          66050                 14050
    SSE or WebSocket, heartbeat 5000       15000             0          65050                 13050
    (limit: silence after which the client gives up; a false alarm is a healthy gap longer than the limit)

    What the lab does not show. It is a model. The 50 ms delay, the intervals and the feed are made up. It measures no real latency, no header sizes, no proxy, no browser reconnection and no battery or radio cost. Its SSE and WebSocket rows are identical on purpose, because the model keeps only what separates them: the upstream request in section 4. Request 7 in section 3 is still being held when the 20 s window ends. The short "delay after death" in the no-heartbeat rows (4050 ms) is not fast detection: that watchdog had already tripped on healthy gaps.

    Break it. In src/model.ts, in simulateLongPolling, change sent = received; to sent = received + 1000; (the client waits a second before asking again). The test "queues events that happen between two requests and returns them in one answer" fails, because the late request makes the batch arrive later. Restore it.

    In practice: an order-tracking page that polls too much

    NOTE

    This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.

    The situation

    The tracking page of a grocery marketplace polls /events?after=N every 5 seconds. Most answers are empty, because an order changes state a handful of times in an hour. Shoppers complain that "near you" arrives late, and the API team sees a steady load of empty polls from tens of thousands of open pages at the evening peak (illustrative). The page sends nothing upstream.

    Starting architecture

    Figure 5. Starting point: every open page asks every 5 seconds

    Starting architecture: each open page polls the events endpoint on a fixed intervalOpen tracking pages to Events API (poll every 5 s); Events API to Order events (read after N)Open tracking pages: one per tabOpen trackingpagesone per tabEvents API: answers at onceEvents APIanswers at onceOrder events: numberedOrder eventsnumberedpoll every 5 sread after N

    How to read this: the load grows with open pages times polls per page, not with how often orders change.

    Options considered

    Option What it fixes What it costs Risk
    Poll every second Latency of about one interval Five times the requests, nearly all empty The API pays for the freshness of every idle page
    Long polling Updates arrive in about one transit A held request per page, batches after gaps Re-asking logic and a timeout to tune
    SSE with Last-Event-ID Updates arrive in about one transit over one request One open response per page, a heartbeat, a watchdog A buffering proxy can make it silent
    WebSocket Same latency A new protocol for a page that sends nothing You own reconnection and authentication, and gain nothing here

    The decision

    Field Decision record
    Context The page only receives updates, wants them within a couple of seconds, and the polling load is mostly empty answers.
    Decision Use SSE with event ids so a reconnect resumes where it stopped. Send a comment heartbeat. Run a client watchdog, and fall back to polling every 15 s when the stream is silent.
    Consequences, good Latency drops to about one network transit; idle pages cost one open response instead of a request every 5 s; the browser handles reconnection.
    Consequences, bad Open connections to hold (per-tab limit over HTTP/1.x), a heartbeat to run, and a fallback path to keep working.
    Revisit when The page needs to send frequent messages upstream (move to a WebSocket), or the per-tab connection limit starts to bite.

    Rollout and verification

    1. Ship behind a flag to a small share of sessions and keep polling for everyone else.
    2. Compare the delay from event to screen and the empty-answer rate for flagged and unflagged sessions.
    3. Test the fallback on purpose: block the stream in a test network and confirm the page switches to polling and says so.
    4. Open several tabs on HTTP/1.x to see the per-origin limit before users do.

    The 2 a.m. failure

    Support reports that on one corporate network the tracking page says "Live" but never changes until the shopper reloads. Error tracking is empty: nothing failed. A proxy on that network buffers the streamed response, so events do not reach the page (illustrative cause; RFC 6202 allows intermediaries to buffer a whole response).

    First three checks: (1) compare the time of the last event the server sent with the time of the last one the page received; (2) check whether comment heartbeats arrive on that network (none arriving means buffering or a dead path); (3) check what the page shows when it has heard nothing for a while. Mitigation: the watchdog gives up after the silence limit and switches to polling, and the page shows "Updating every 15 s" rather than "Live". Follow-up: record watchdog trips as a metric, so a network that always forces the fallback is visible, and test the fallback in CI.

    Architect's notes

    • Start from the freshness the user needs, then pick the weakest transport that gives it. Many screens are fine with a ten-second poll.
    • Make recovery a design decision, not a library default. Decide what the page does on a drop, how it asks for what it missed, and what it shows meanwhile.
    • Number your events. A cursor or an event id turns every transport into "everything after N", which is what makes reconnecting safe.
    • Keep a fallback that does not depend on streaming. Polling is boring and works everywhere HTTP does.
    • Show the connection state in the interface. "Live", "Reconnecting" and "Updating every 15 s" are three different promises.

    Common mistakes

    • Choosing a WebSocket for a one-way feed, and then rebuilding reconnection, authentication and ordering that SSE gives for free.
    • Polling fast "to feel live," so the server pays for every idle page.
    • No heartbeat and no watchdog, so a dead connection looks like a quiet feed.
    • A watchdog limit shorter than the longest healthy quiet gap, which drops good connections.
    • Ignoring the per-origin connection limit when every tab opens its own stream over HTTP/1.x.
    • Assuming the network passes streams through. Test behind the proxies your users have.

    Key takeaways

    • A browser asks and the server answers; every real-time technique is a workaround for that.
    • Short polling is simple and universal, and its latency is its interval; long polling answers when something happens but re-asks after every answer and delivers batches after a gap.
    • SSE is one open response, one-way, with built-in reconnection and Last-Event-ID; the constructor cannot set headers.
    • A WebSocket is a protocol upgrade giving two-way frames, with no backpressure in the browser API and recovery left to you.
    • A client cannot tell a quiet feed from a dead path: use a heartbeat and a watchdog.
    • Pick the weakest transport that meets the freshness the screen needs, and keep a polling fallback.

    Practice exercises

    Exercise 1 — Starter (45 min): In the lab's demo.ts, change the feed to events one every 10 s for 60 s. Predict, then run, the latency and request count for polling every 5 s and every 30 s. Explain the result in two sentences.

    Exercise 2 — Intermediate (2 hours): Add a bytes column to the lab: a made-up header size per HTTP response and a payload per event. Compare polling every second with SSE for a feed that changes once a minute. State which numbers are assumptions.

    Exercise 3 — Advanced (half day): Write the client state machine for the decision in this lesson: SSE while it is healthy, polling when the watchdog trips, and a retry back to SSE later. List every state, event and transition, and write the tests as a table before any code.

    In this course:

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments