Interview's MateAI Engineering
Interview's Mate

AI Engineering

LLMs, RAG, agents & evals

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
AI Engineering topics
Lesson 145/ 160
08. Backend

WebSockets

Bidirectional sockets for chat, agent progress, and collaborative sessions.

IntermediateBidirectional · Frames3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidHands-onQuiz (3)Practice

In plain words

A WebSocket keeps a two-way line open between your browser and the server so both can send messages instantly, without asking for each message separately.

Think of it like…

A phone call instead of postcards. Either side can speak at any moment without redialling; but you have to keep the line alive, handle dropped calls by calling back politely and make sure the switchboard doesn't get flooded when everyone redials at once.

Where you’ve seen it

A voice agent connects with wss://api.example.com/v1/realtime. Browsers cannot set an Authorization header on a WebSocket, so the client first obtains a short-lived signed token (60-second lifetime, single use) from an authenticated endpoint and passes it in the query string or as the first message; the server validates it during the handshake, binds the connection to a user and tenant and rejects the upgrade with 401 otherwise. Messages are JSON envelopes with a type, a monotonically increasing seq and an id for acknowledgements: audio.chunk, response.delta, response.cancel, tool.request, tool.approve. A user speaking over the assistant sends response.cancel; the server stops generation within about 100 ms, which would be impossible over a one-way SSE stream without a second request. Proxies close idle connections after about 60 seconds, so the server pings every 25 seconds and drops connections that miss a pong for 10 seconds; with 10,000 connected clients that is 10,000 / 25 = 400 pings a second. At roughly 30 KB per connection of buffers and state (measure your own), 10,000 connections need about 300 MB per instance. After a deploy kills the old instances, 10,000 clients reconnect: with no jitter that is 10,000 handshakes in the same instant; with jittered exponential backoff spread uniformly over 30 seconds it is about 333 a second. Because connections are stateful, the load balancer uses connection-level routing and, to fan messages out to a user's session that may live on another instance, servers publish through Redis pub/sub or a message broker. Slow consumers are handled with bounded send queues: if a client lags beyond 1 MB of buffered output, the server closes it with code 1013 rather than growing memory.

Words you’ll hear

Upgrade handshake
The HTTP request and 101 response that switch the connection to the WebSocket protocol.
Frame
The unit of WebSocket data: text, binary, ping, pong or close.
Ping/pong
Control frames used as heartbeats to detect dead connections.
Backpressure
Slowing or dropping producers when the receiver cannot keep up.

Visual diagram

Loading interactive diagram

Theory & deep dive

Protocol, framing and message design

The handshake is an ordinary HTTP GET with Upgrade: websocket and Sec-WebSocket-Key; the server replies 101 Switching Protocols and the TCP connection becomes a frame stream. After that, frames are small (2 to 14 bytes of header) and either side may send at any time. Control frames (ping, pong, close with a code and reason) manage the connection, and clients and servers should use them for liveness and clean shutdown. Use wss:// (TLS) always. Browsers cannot attach arbitrary headers to the handshake, so authenticate with a short-lived, single-use token (obtained from an authenticated HTTP call, valid for about 60 seconds), a cookie on the same origin or the Sec-WebSocket-Protocol subprotocol field, and validate the Origin header to stop cross-site connections.

Design messages as envelopes: type, id, a seq number, a ts and a typed payload. Sequence numbers allow acknowledgements, ordering checks and resume: after a reconnect, the client sends last_seq and the server replays what was missed from a short buffer. Version the protocol (protocol: 2 in the first message) so old clients can be supported, and limit message size (for example 1 MB) to prevent abuse. For binary media such as audio, use binary frames with a small header carrying the sequence number and timestamp.

Envelope

{"type":"response.delta","seq":412,"id":"r_9","payload":{"text":"Hello"}}. Client cancel: {"type":"response.cancel","id":"r_9"}. On reconnect: {"type":"resume","last_seq":412}.

Key takeaway: Upgrade over HTTP, authenticate with short-lived tokens, and design sequenced, versioned message envelopes.

Operating stateful connections at scale

Heartbeats and timeouts: intermediaries close idle connections (often at 60 seconds), and half-open TCP connections look alive for minutes, so ping every 25 seconds and close a connection that misses a pong for 10 seconds. At 10,000 connections that is 400 pings a second, which is cheap but should be measured. Memory and limits: each connection holds buffers and state (assume tens of KB and measure: 30 KB × 10,000 = 300 MB), uses a file descriptor and counts against per-instance limits, so cap connections per user and per instance and shed load by refusing new upgrades with 503. Backpressure: give every connection a bounded outbound queue (for example 1 MB or 1,000 messages) and close laggards with an explicit code (1013, try again later) instead of letting memory grow.

Scaling and deploys: the load balancer must support the upgrade and route per connection; a user's session may be connected to any instance, so publish outbound messages through Redis pub/sub or a message bus and have each instance deliver to its local connections. Deploys and autoscaling disconnect clients, so drain gracefully (stop accepting, send a reconnect hint, close after a grace period) and have clients reconnect with exponential backoff and jitter: 10,000 clients redialling together is a 10,000-handshake spike, while spreading them over 30 seconds gives about 333 per second. Compare with the alternatives: for one-way token streaming SSE is simpler and sufficient; WebSockets earn their cost when you need bidirectional, low-latency traffic such as barge-in voice, collaboration or interactive agent control.

Reconnect storm

Deploy restarts all instances; 10,000 clients lose their connections. No jitter: 10,000 handshakes at once. Backoff with uniform jitter over 30 s: 10,000 / 30 ≈ 333 handshakes per second, which the authentication service and the broker can absorb.

Key takeaway: Budget memory per connection, heartbeat, bound queues, fan out through a broker and reconnect with jitter.

How it works, step by step

Step 1 of 4
Architect

1. Decide whether you need duplex

Use SSE for one-way token streams and WebSockets only for interactions that need client messages mid-stream.

barge-in voice → WebSocket
Key numbers at this step
Compare
SSE first

When to use it & trade-offs

What it is

A WebSocket is a persistent, full-duplex connection between a client and a server. It starts as an HTTP request with an Upgrade: websocket header; the server answers 101 Switching Protocols and from then on both sides exchange frames (text, binary, ping, pong, close) at any time, with very little per-message overhead. For AI products this suits interactions where the client also talks while the server streams: interrupting a generation, sending audio chunks to a voice assistant, receiving agent progress while approving tool calls or collaborating in a shared session. Operating WebSockets means handling authentication at connect time, heartbeats, backpressure, reconnection, and scaling a stateful connection across many servers.

Why it matters: SSE is enough for one-way token streams, but features such as barge-in on a voice agent, live cancel buttons and multi-user sessions need messages flowing both ways with low latency. WebSockets provide that, at the cost of statefulness: each connection pins memory and a file descriptor to a server, deploys disconnect everyone, load balancers need to keep a connection on one backend and a missed heartbeat leaves ghost connections. Treating these as first-class design concerns avoids the typical outage where a deploy triggers a reconnect storm.

When to reach for it

  • Voice and realtime assistants with interruption
  • Collaborative sessions and live agent control
  • Progress streams that need client acknowledgements

When to avoid or be careful

  • WebSockets when SSE already meets the need
  • Unbounded per-connection send buffers
  • Reconnect loops without jitter

Realtime options

WebSockets
Best for: Bidirectional low-latency interaction

Strengths: Full duplex; binary support; low overhead.

Watch out: Stateful; harder to scale and deploy.

Server-Sent Events
Best for: One-way streams to browsers

Strengths: Simple; HTTP-native; auto-reconnect.

Watch out: No client-to-server channel.

Polling
Best for: Low-frequency updates

Strengths: Trivial and stateless.

Watch out: Latency and request overhead.

Interview signals & numbers to know

When this topic comes up

  • “WebSockets or SSE for a chat product?”
  • How you authenticate a WebSocket
  • Heartbeats and dead connections
  • Scaling stateful connections
  • Reconnect storms after a deploy

Benchmarks & rules of thumb

10,000 / 25 s = 400/s -
pings for 10,000 connections at a 25-second interval
≈ 300 MB -
memory for 10,000 connections at about 30 KB each
10,000 → 333/s -
handshakes without versus with jitter over 30 s

Common mistakes & follow-ups

Common interview mistakes

  • Putting long-lived credentials in the WebSocket URL.
  • Forgetting to check the Origin header.
  • Letting a slow client grow server memory without limit.

Likely interviewer follow-ups

  • How would you scale a WebSocket service to many instances?
  • How do you handle deploys without disconnecting everyone at once?
  • How can a client resume after a reconnect?
Interview tip: Describe the reconnect storm and the jitter fix; it shows you have thought about how stateful systems fail.
Loading hands-on exercise

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply WebSockets with generative AI interview Q&A and hands-on practice.

Open Generative AI Q&A →Tech Learn Q&A
Previous topic
Streaming with SSE
Next topic
Authentication with JWT