Thuta Learning
AdvancedWeb Developmentbeginner

Polling, WebSocket, and Server-Sent Events

What you'll walk away with

  • Explain the core ideas behind Polling, WebSocket, and Server-Sent Events
  • Read the diagram and trace how a request, piece of data, or event flows through the system
  • Explain how this piece connects into the larger web architecture picture

Build the mental model

Ordinary HTTP follows a simple back-and-forth pattern: the client sends a request, and the server sends back one response, then the connection's job for that exchange is done.

That pattern works fine for loading a page or submitting a form, but it breaks down for anything that needs to update the moment something changes elsewhere, a chat message arriving, a live dashboard metric ticking upward, a notification, a multiplayer game move, a trading price shifting.

In all of these cases, the browser cannot simply wait for the user to click something; it needs to learn about changes it did not ask for at that exact moment.

Polling is the simplest fix: the client repeatedly sends a new request, asking essentially anything new on a timer. It is simple to build and works with plain HTTP, but it wastes requests when nothing has changed and introduces delay equal to however long the interval between checks is.

WebSocket takes a different approach: after an initial handshake, it opens one long-lived connection where both the client and the server can send messages at any time, in either direction, without starting a new request each time.

This fits chat, live notifications, real-time collaboration, and multiplayer interaction well. WebSocket does not replace HTTP; it exists alongside it as a different tool suited to sustained two-way traffic rather than typical request-response exchanges.

Server-Sent Events (SSE) sit between the two: the server keeps a connection open and continuously pushes updates to the client, but only in one direction, server to client. It fits streaming AI responses, live feeds, and notifications where the client mostly just needs to listen.

DimensionPolling / WebSocket / SSE
DirectionPolling: client asks, server answers (one-way ask, one-way answer). WebSocket: both directions, any time. SSE: server to client only.
Connection lifetimePolling: short-lived, repeated requests. WebSocket: one long-lived connection. SSE: one long-lived connection.
ComplexityPolling: simplest, plain HTTP. WebSocket: more setup, needs a persistent connection. SSE: simpler than WebSocket, built on HTTP streaming.
Typical use casePolling: rare updates, simple status checks. WebSocket: chat, multiplayer, collaboration. SSE: live feeds, AI streaming, notifications.
text
POLLING vs WEBSOCKET vs SSE
---------------------------
POLLING vs WEBSOCKET vs SSE
-------------------------------
POLLING (client repeatedly asks)
  Client -> "anything new?" -> Server
  Client <- "no, nothing yet" <- Server
        ... wait for interval ...
  Client -> "anything new?" -> Server
  Client <- "yes, here it is" <- Server

WEBSOCKET (persistent, two-way)
  Client <==== one open connection ====> Server
  Client  -- message -------------->     Server
  Client  <------------- message --      Server
  (connection stays open until closed)

SSE (one-way stream, server to client)
  Client -- opens a stream --> Server
  Client <-- update 1 --          Server
  Client <-- update 2 --          Server
  (client does not send data back on this channel)

Connect it to a real scenario

Say a team is building three different features and needs to pick a real-time approach for each one.

First, a new version available banner that only needs to appear a few times a year, polling once every several minutes is more than adequate, and building a persistent connection for something this rare would be unnecessary complexity.

Second, a customer support chat window where messages must feel instant in both directions, this is exactly what WebSocket is designed for, since both sides need to send messages at any time over one connection that stays open for the whole conversation.

Third, an AI assistant that streams its answer back token by token as it is generated, Server-Sent Events fit naturally here, because the data only flows one way, from server to client, and the client never needs to send anything back over that same channel.

Choosing wrong is not fatal, just wasteful or clunky: WebSocket for the rare banner burns server resources on idle connections, and polling for the chat window feels laggy and chatty compared to a real persistent connection.

Try the working example

javascript
function simulateApproaches(newDataEvents, { pollIntervalSeconds, totalDurationSeconds }) {
  // Polling: the client checks on a fixed timer, regardless of whether
  // anything actually changed.
  let pollingRequests = 0;
  for (let t = pollIntervalSeconds; t <= totalDurationSeconds; t += pollIntervalSeconds) {
    pollingRequests++;
  }
  const pollingDelays = newDataEvents.map((eventTime) => {
    const nextPoll = Math.ceil(eventTime / pollIntervalSeconds) * pollIntervalSeconds;
    return nextPoll - eventTime;
  });
  const avg = (arr) => arr.reduce((a, b) => a + b, 0) / arr.length;

  // WebSocket: one persistent connection opened up front; the server
  // pushes each update the instant it happens.
  const webSocket = {
    connectionsOpened: 1,
    delays: newDataEvents.map(() => 0),
  };

  // SSE: also one persistent connection, one-way server-to-client.
  const sse = {
    connectionsOpened: 1,
    delays: newDataEvents.map(() => 0),
  };

  return {
    polling: {
      totalRequests: pollingRequests,
      averageDelaySeconds: Number(avg(pollingDelays).toFixed(2)),
    },
    webSocket: {
      totalConnections: webSocket.connectionsOpened,
      averageDelaySeconds: Number(avg(webSocket.delays).toFixed(2)),
    },
    sse: {
      totalConnections: sse.connectionsOpened,
      averageDelaySeconds: Number(avg(sse.delays).toFixed(2)),
    },
  };
}

// New data actually appears at these moments over a 30-second window.
const newDataEvents = [3, 7, 7.5, 15, 16, 30];

const result = simulateApproaches(newDataEvents, {
  pollIntervalSeconds: 5,
  totalDurationSeconds: 30,
});

console.log(JSON.stringify(result, null, 2));
You should see
Over a 30-second window with new data at 3, 7, 7.5, 15, 16, and 30 seconds and a 5-second poll interval: polling makes 6 requests with an average notice delay of 1.92 seconds; WebSocket and SSE each use 1 persistent connection with an average delay of 0 seconds, since the server pushes updates the instant they happen.

5-minute try-it

For your own app idea, list three features that might need live updates. For each, decide whether polling, WebSocket, or SSE fits best, and justify it using direction of data flow and how often updates actually happen.

One important caution

Reaching for WebSocket by default for anything that updates — a rarely-changing value is often cheaper and simpler with polling.

Thinking WebSocket replaces HTTP entirely — most applications still use normal HTTP requests for most of their traffic alongside WebSocket for the parts that need it.

MDN — WebSockets APIHow the Web Works

Easy traps

  • Reaching for WebSocket by default for anything that updates — a rarely-changing value is often cheaper and simpler with polling.
  • Thinking WebSocket replaces HTTP entirely — most applications still use normal HTTP requests for most of their traffic alongside WebSocket for the parts that need it.
  • This course is a system map, not a deep-dive on every piece -- for depth on REST, DNS/hosting, databases, or security, continue to the API Tutorial, Cloud & Deployment, SQL, or Cybersecurity tutorials.

Exercise

For your own app idea, list three features that might need live updates. For each, decide whether polling, WebSocket, or SSE fits best, and justify it using direction of data flow and how often updates actually happen.

You'll know it worked when: Over a 30-second window with new data at 3, 7, 7.5, 15, 16, and 30 seconds and a 5-second poll interval: polling makes 6 requests with an average notice delay of 1.92 seconds; WebSocket and SSE each use 1 persistent connection with an average delay of 0 seconds, since the server pushes updates the instant they happen.

Polling, WebSocket, and Server-Sent Events | Thuta Learning