All guides

Long polling vs WebSockets vs Server-Sent Events: which one to use

How the three ways to push data from a server to a browser differ in direction, reconnection and proxy behavior, and when to pick each.

By Roman · · 4 min read

Python, FastAPI

If your server only pushes data, you probably don’t need WebSockets.

Notifications, dashboards, build logs and LLM token streams all go from server to client. For that kind of traffic, Server-Sent Events (SSE) run over plain HTTP, and the browser reconnects and resumes for you. Each technique needs different code.

TL;DR

  • Use SSE when only the server pushes. The browser reconnects on its own and sends Last-Event-ID so your server can resume.
  • Use WebSockets when the client also sends frequent, latency-sensitive messages: chat with typing indicators, collaborative editing, games. You write the reconnect logic yourself.
  • Use long polling as the fallback for networks or platforms that buffer or cut off streaming responses.

Three ways to keep a channel open

With long polling, the client sends an ordinary request and the server holds it until it has data or hits a timeout. The client handles the response and immediately asks again. Every message costs a full request and response (often hundreds of bytes of headers once cookies are included). Events that arrive between polls have to be buffered on the server and fetched with a cursor.

With SSE, the client makes one GET request and the response never ends. The server writes text/event-stream lines, and the browser’s EventSource parses them into events. It carries only UTF-8 text, and only from server to client.

WebSockets start as an HTTP request with Upgrade: websocket. The server answers 101 Switching Protocols, and after that the TCP connection carries RFC 6455 frames in both directions, as text or binary.

Long polling SSE WebSockets
Direction Server to client (client sends via normal requests) Server to client Both
Wire protocol Plain HTTP Plain HTTP HTTP upgrade, then frames
Payload Anything HTTP carries UTF-8 text Text and binary
Reconnect and resume You build it Built in You build it
Per-message overhead Full HTTP headers A few bytes 2–14 byte frame header
Custom auth headers from browser Yes (fetch) No, cookies or a URL token No, cookies or a token in the first message
Proxy friction Lowest Buffering must be off Upgrade must be forwarded

One SSE trap: over HTTP/1.1, browsers allow 6 connections per host, and each open EventSource takes one of them. If a user opens your app in a seventh tab, that tab hangs. HTTP/2 multiplexes the streams over one connection, so serve SSE over HTTP/2.

Decision flow: WebSockets if the client sends often, otherwise SSE, or long polling if streams get buffered.

Pick SSE for one-way feeds

The server examples are endpoints of one FastAPI app in main.py, started with uvicorn main:app --port 8000 (Python 3.11+). Browser code stays JavaScript.

The server writes id:, event: and data: lines and ends each event with a blank line.

Server (Python, main.py):

import asyncio
import json
import time

from fastapi import FastAPI, Request
from fastapi.responses import StreamingResponse

app = FastAPI()

@app.get("/events")
async def events(request: Request):
    # On reconnect the browser sends the last id it saw
    last_id = int(request.headers.get("last-event-id", 0))

    async def stream():
        yield "retry: 3000\n\n"  # reconnect delay the browser should use
        event_id = last_id
        while True:
            event_id += 1
            data = json.dumps({"at": time.time()})
            yield f"id: {event_id}\nevent: tick\ndata: {data}\n\n"
            await asyncio.sleep(1)

    return StreamingResponse(stream(), media_type="text/event-stream",
                             headers={"Cache-Control": "no-cache"})

Client (browser JavaScript):

const es = new EventSource("/events");
es.addEventListener("tick", (e) => console.log(e.lastEventId, JSON.parse(e.data)));
es.onerror = () => console.log("dropped; browser retries unless readyState is CLOSED");

If the server responds with a non-200 status or the wrong Content-Type, EventSource gives up for good. Return 200 even when there is nothing to send yet.

Pick WebSockets for chatty, two-way traffic

This endpoint keeps the open sockets in a set and sends every message to all of them.

Server (Python, main.py):

from fastapi import WebSocket, WebSocketDisconnect

clients: set[WebSocket] = set()

@app.websocket("/ws")
async def ws(socket: WebSocket):
    await socket.accept()
    clients.add(socket)
    try:
        while True:
            text = await socket.receive_text()
            for client in list(clients):
                try:
                    await client.send_text(text)
                except (WebSocketDisconnect, RuntimeError):
                    clients.discard(client)  # that client disconnected; keep serving the sender
    except WebSocketDisconnect:
        pass
    finally:
        clients.discard(socket)

Nothing reconnects for you. Add jitter to the retry delay so a server restart doesn’t bring every client back in the same millisecond:

Client (browser JavaScript):

function connect() {
  const ws = new WebSocket("wss://example.com/ws");
  ws.onopen = () => ws.send("hello");
  ws.onmessage = (e) => console.log(e.data);
  ws.onclose = () => setTimeout(connect, 1000 + Math.random() * 2000);
  return ws;
}
connect();

Fall back to long polling when streams get buffered

Some corporate proxies and serverless platforms hold the whole response before forwarding it, which breaks SSE and blocks upgrades. Long polling works anywhere HTTP works. Have the server hold each request for about 25 seconds and answer 204 if nothing arrived. Call publish() wherever your app produces events.

Server (Python, main.py):

from fastapi import Response

log: list[dict] = []  # cursor = index into this list
changed = asyncio.Condition()

async def publish(event: dict):
    async with changed:
        log.append(event)
        changed.notify_all()

@app.get("/updates")
async def updates(after: int = 0):
    async with changed:
        try:
            await asyncio.wait_for(changed.wait_for(lambda: len(log) > after), timeout=25)
        except TimeoutError:
            return Response(status_code=204)  # nothing new, client asks again
        return {"events": log[after:], "next": len(log)}

The client asks again as soon as each response arrives:

Client (browser JavaScript):

async function poll(cursor = 0) {
  while (true) {
    try {
      const res = await fetch(`/updates?after=${cursor}`);
      if (!res.ok) throw new Error(String(res.status)); // back off on 4xx/5xx
      if (res.status === 200) {
        const { events, next } = await res.json();
        events.forEach((ev) => console.log(ev));
        cursor = next; // server keys missed events by cursor
      } // 204: server timed out with nothing new, ask again
    } catch {
      await new Promise((r) => setTimeout(r, 2000));
    }
  }
}
poll();

Official docs