Realtime Communication Patterns

Short polling, long polling, SSE, WebSockets and webhooks: how servers push updates.

What is it?

Plain HTTP is request-response: the client asks, the server answers. But many features need the server to tell someone about a change as it happens: a new chat message, a finished payment, a live score.

There are five common ways to get "push"-like behavior:

- Short polling: the client asks "anything new?" every few seconds. - Long polling: the client asks, and the server holds the request open until there's news (or a timeout), then the client asks again. - Server-Sent Events (SSE): one long-lived HTTP response that the server keeps writing events into. Server to client only. - WebSockets: a persistent, two-way connection where either side can send messages at any time. - Webhooks: server-to-server push. When something happens, one server makes an HTTP POST to a URL another server registered in advance.

Explain like I'm 10

Short polling is a kid asking 'are we there yet?' every minute. Long polling is asking once and the driver answering only when you arrive. SSE is a radio broadcast you tune into. A WebSocket is a phone call where both people can talk. A webhook is leaving your number so the shop calls you when your order is ready.

Examples

Server-Sent Events in the browser

// Browser: built-in EventSource API, reconnects automatically
const events = new EventSource("/api/orders/123/events");

events.addEventListener("status", (event) => {
  const update = JSON.parse(event.data);
  showStatus(update.status);
});

// Server response (Content-Type: text/event-stream), written over time:
// id: 17
// event: status
// data: {"status":"shipped"}
//
// (a blank line ends each event)

SSE is just a long HTTP response in a simple text format. If the connection drops, the browser reconnects and sends a Last-Event-ID header so the server can resume.

Verifying a webhook signature

import crypto from "node:crypto";

function isValidWebhook(rawBody, signatureHeader, secret) {
  const expected = crypto
    .createHmac("sha256", secret)
    .update(rawBody)
    .digest("hex");
  const a = Buffer.from(expected);
  const b = Buffer.from(signatureHeader);
  // Constant-time compare avoids leaking the signature through timing.
  return a.length === b.length && crypto.timingSafeEqual(a, b);
}

Anyone can POST to a public webhook URL, so receivers check an HMAC signature computed with a shared secret over the raw request body. Real providers usually also sign a timestamp to block replays.

How it works

Short polling is ordinary requests on a timer. Simple, but most responses are empty, and updates arrive up to one interval late.

Long polling keeps a request open on the server until data is ready or a timeout (often 20-60 seconds) passes. The client immediately reissues the request. Latency is low, but each waiting client ties up a connection, and messages can be missed between requests unless the client sends a cursor.

SSE uses one HTTP response with Content-Type text/event-stream. It works through most proxies, reconnects automatically, and resumes with Last-Event-ID. It is text-only and one-way. On HTTP/1.1, browsers allow only about six connections per domain, so many open tabs can exhaust them; HTTP/2 multiplexing removes that limit.

WebSockets start as an HTTP request with an Upgrade header; the server answers 101 Switching Protocols and the TCP connection becomes a full-duplex message channel. Servers must hold one connection per client, so scaling means sticky routing, a pub/sub backbone to fan messages out across servers, and handling reconnects.

Webhooks are plain HTTP POSTs between servers. The sender must retry on failure (so receivers must handle duplicates), and receivers must verify signatures and respond quickly, doing slow work asynchronously.

Direction        Latency     Server cost         Best for
Short polling  client pulls     interval    many empty reqs     rare updates, simplicity
Long polling   client pulls     low         1 held req/client   fallback when WS/SSE blocked
SSE            server -> client low         1 open conn/client  feeds, notifications, progress
WebSockets     both ways        lowest      1 open conn/client  chat, games, collaboration
Webhooks       server -> server event-driven 1 POST per event   integrations (payments, CI)

Long polling timeline:
Client ---- GET /updates?after=41 ---->  Server (holds request...)
Client <--- 200 [event 42] ------------  (event arrives)
Client ---- GET /updates?after=42 ---->  (immediately asks again)

Why does it exist?

HTTP was designed for documents, not live updates. Polling was the first workaround; long polling (used by early web chat) cut wasted requests; SSE and WebSockets were standardized to give browsers proper streaming channels. Webhooks exist because servers in different companies need to notify each other without anyone keeping a connection open.

When to use it

- Short polling: data changes rarely and a delay of seconds is fine (checking an export job every 10 seconds). - Long polling: you need near-realtime but WebSockets or SSE are blocked. - SSE: one-way server updates to browsers: notifications, live dashboards, streaming LLM output, progress bars. - WebSockets: frequent two-way messages with low latency: chat, multiplayer games, collaborative editors. - Webhooks: telling another system about events (payment succeeded, build finished).

When not to use it

Don't reach for WebSockets when the client only listens; SSE is simpler and works with normal HTTP infrastructure. Don't poll every second for data that changes hourly. Don't use webhooks when the receiver can't expose a public HTTPS endpoint (for example, a browser or a device behind NAT); use polling or a persistent connection instead.

Common mistakes

  • Using WebSockets for one-way updates and then rebuilding reconnection and resume logic that SSE gives for free.

  • Running WebSocket servers behind a load balancer without a pub/sub layer, so a message published on server A never reaches users connected to server B.

  • Not verifying webhook signatures, letting anyone forge 'payment succeeded' events.

  • Doing slow work inside a webhook handler, so the sender times out and retries, creating duplicates.

  • Reconnecting all clients at once after a server restart without jittered backoff, causing a thundering herd.

Practice exercises

  1. Easy:

    For each feature, pick a pattern and justify it: a stock ticker, a chat app, a nightly report status, a Stripe payment notification.

  2. Medium:

    Design how a chat service with 10 WebSocket servers delivers a message from a user on server 3 to a user on server 7.

  3. Hard:

    Design a webhook delivery system for a SaaS product: retries, ordering, signing, replay protection, and what happens when a customer's endpoint is down for a day.

Interview questions

What's the difference between short polling and long polling?

Short polling sends requests on a fixed interval and usually gets empty responses. Long polling sends a request that the server holds open until there's data or a timeout, then the client reconnects. Long polling gives lower latency with fewer wasted requests.

When would you choose SSE over WebSockets?

When updates only flow from server to client. SSE runs over plain HTTP, works with existing proxies and auth, and has built-in reconnection with Last-Event-ID. WebSockets are worth it when the client also sends frequent messages.

How does a WebSocket connection get established?

The client sends an HTTP GET with Upgrade: websocket and a Sec-WebSocket-Key header. The server replies 101 Switching Protocols with a derived Sec-WebSocket-Accept, and from then on the TCP connection carries WebSocket frames in both directions.

What is a webhook and what must a receiver do?

An HTTP callback: when an event happens, the provider POSTs to a URL you registered. The receiver should verify the signature, respond 2xx quickly, process the work asynchronously, and deduplicate by event id because providers retry.

Why are WebSockets harder to scale than regular HTTP?

Each client holds a long-lived connection to one server, so servers are stateful. You need enough file descriptors and memory per connection, load balancers that support long connections, a pub/sub layer to route messages between servers, and graceful handling of reconnect storms during deploys.

How do you avoid missing events when a client reconnects?

Give every event a monotonically increasing id or offset, have the client send the last id it saw on reconnect (Last-Event-ID for SSE, a cursor for others), and keep a short replay buffer or log on the server to resend what was missed.

What limit can bite SSE on HTTP/1.1?

Browsers cap concurrent HTTP/1.1 connections per domain at about six. Each SSE stream holds one open, so several tabs can starve other requests. Serving over HTTP/2, which multiplexes streams on one connection, avoids this.

How would you make webhook delivery reliable as a provider?

Store each event durably, deliver from a queue with exponential backoff and jitter over hours or days, sign every payload with a timestamp, include an event id for deduplication, disable or alert on endpoints that keep failing, and offer an API to list or replay missed events.

A deploy restarts 50 WebSocket servers holding 2 million connections. What goes wrong and how do you mitigate it?

All clients reconnect at once and overload auth, the load balancer and the new servers (a thundering herd). Mitigate with rolling restarts that drain connections gradually, client reconnects with randomized exponential backoff, and connection admission limits on servers.