Module 1 · FundamentalsLesson 7 of 886 minBeginner

WebSockets and real-time updates

Normal HTTP only answers questions. A WebSocket keeps a line open so the server can speak first.

Try it

Play "Polling" and count the empty answers. Then play "WebSocket" and compare how quickly the message arrives.

HTTP works like a question and an answer. The client asks; the server replies; done. But some apps need the server to start the conversation:

  • a new chat message arrives,
  • the price of a stock changes,
  • a teammate edits the document you are both looking at.

Option 1: polling

The client asks "anything new?" every few seconds. It's simple and works everywhere, but:

  • most answers are empty, which wastes bandwidth and server work,
  • updates arrive late, up to a whole polling interval,
  • with a million users polling every second, that is a million requests a second for mostly nothing.

Long polling improves this: the server holds the request open until it has something to say, then the client immediately asks again.

Option 2: WebSockets

A WebSocket starts as a normal HTTP request with an Upgrade header. The server agrees (101 Switching Protocols), and from then on the connection stays open. Both sides can send messages whenever they want, with very little overhead per message.

What it means for your servers

Open connections change how you scale:

  • Each user holds a connection all the time, so servers are limited by how many connections they can keep, not just requests per second.
  • If a user is connected to server A and their friend to server B, a message from one must reach the other. Real-time systems use a shared message bus (like Redis pub/sub or Kafka) between servers.
  • Connections drop on bad networks. Clients must reconnect and catch up on missed messages.

Other options

Server-Sent Events (SSE) is a simpler one-way stream from server to browser over plain HTTP. It's great for live feeds and for streaming AI answers word by word, which you will see in the last module.

Quick check

Why is a WebSocket better than polling every second for a chat app?