TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About ยท Labs ยท Cheat sheets ยท Learning paths

All concepts ยท web ยท protocols ยท real-time

WebSocket

A single long-lived, two-way connection between browser and server. It starts as an HTTP request, upgrades with 101 Switching Protocols, and then carries small frames in both directions at any time.

9 min3 animations

๐Ÿ“š Builds on๐Ÿ“ฎ HTTP

๐Ÿ–จ๏ธ Cheat sheet

Letters versus a phone call

HTTP is like writing letters. You only hear back when you write, so to follow a chat you'd have to keep writing "anything new?", and nearly every answer is "no".

A phone call works differently. Once the call is connected, the line stays open, and either of you can speak the moment you have something to say.

Why WebSockets exist

In HTTP the client always starts. Real-time features (chat, live scores, collaborative editing, multiplayer games, dashboards) can work around that with polling (ask every few seconds) or long polling (the server holds the request open until something happens). Both cost a full request with headers for each update, and polling adds delay.

A WebSocket is one persistent, full-duplex connection. Either side can send at any time, and each message costs only a few bytes of framing.

Asking again and again3 steps
๐Ÿง’You๐Ÿง‘Your friend
Press play and watch it happen!

Starting the call

The call starts with an ordinary letter that has a note on the envelope: "can we switch to the phone?" If the other side agrees, it says so, and the same line turns into a call. When you're done, you both say goodbye and hang up.

The upgrade handshake

A WebSocket begins as an HTTP/1.1 request, so it works through the same ports, proxies and TLS as the rest of the site:

1GET /chat HTTP/1.12Upgrade: websocket3Connection: Upgrade4Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==

The server answers 101 Switching Protocols with Sec-WebSocket-Accept, and from then on the TCP connection carries frames: text, binary, ping, pong and close. Use wss:// (WebSocket over TLS) just as you'd use https://. In the browser:

1const ws = new WebSocket("wss://shop.com/chat");2ws.onmessage = (e) => console.log(e.data);3ws.send("hi!");
Turning a letter into a phone call4 steps
๐Ÿง’You๐Ÿง‘Your friend
Press play and watch it happen!

A group call

A chat room is a switchboard with everyone's line plugged in. When one friend speaks, the switchboard repeats it to everyone else. It checks now and then that each line is still alive, and when one drops, that friend's phone calls back by itself.

Broadcasting and staying connected

The server keeps a set of open connections per room and fans out each message to the others. Ping/pong heartbeats keep idle connections alive through proxies and detect dead ones.

Connections will drop (phones change networks, servers redeploy), so clients reconnect with backoff and catch up on what they missed. With several server instances, a message arriving at one must reach clients connected to another, usually through a shared pub/sub channel such as Redis or Kafka.

A group call4 steps
๐Ÿ‘งAna๐Ÿ‘ฆBen๐Ÿง’Cyโ˜Ž๏ธSwitchboard
Press play and watch it happen!
๐Ÿ”ง Going deeper

When not to use it: for one-way updates (notifications, progress, live feeds), Server-Sent Events are simpler. They're plain HTTP, reconnect automatically, and work well with HTTP/2.

Security: browsers allow WebSocket connections to any origin, so servers must check the Origin header and authenticate the connection themselves.

๐Ÿ—๏ธ Design it in CloudArch

Build the architecture on a canvas, push load through it and see what breaks.

  • ๐Ÿ’ฌWhatsAppReal-time messages to billions of phones, even when they are offline.guided design

๐Ÿงฉ Quick quiz

Quick quiz! 3 questions about WebSocket, told the same way as the story.
  1. Why is following a chat by letter tiring?
  2. How does the phone call start?
  3. A friend's line drops. What happens?
Answer every question to check.Passing marks WebSocket as done.
Got the hang of WebSocket? Mark it as done, and your paths show how far youโ€™ve got.

Saved in this browser.

๐ŸŒ How the web talksStep 5 of 5

โ† Previous on the path๐Ÿšง CORSLast step ๐ŸŽ‰Back to the path