Free course

WebSockets free course for API builders.

WebSockets give APIs a persistent, bidirectional channel after an HTTP upgrade. This short course explains how that works, where teams use it, which security controls matter, and then lets you practice against a hosted lab from the browser.

What WebSockets are vs HTTP

HTTP is request/response: the client opens a connection (or reuses one), sends a request, and waits for a response. WebSockets start with that same HTTP machinery, then upgrade the connection into a long-lived, full-duplex pipe. After the handshake succeeds, either side can send frames at any time without a new request cycle.

  • Client sends Upgrade: websocket and related handshake headers.
  • Server answers with 101 Switching Protocols when it accepts the upgrade.
  • The TCP (or TLS) connection stays open; application messages ride WebSocket frames.
  • Ideal when the server must push updates without the client polling.

If your use case is occasional reads or idempotent writes, plain HTTP (or HTTP/2) is often simpler and easier to cache, authenticate, and observe. Choose WebSockets when latency and push matter more than request-shaped APIs.

Frames, text vs binary, ping/pong

Application data is split into frames. Most JSON APIs use text frames; file chunks, protobuf, or compressed blobs often use binary frames. Control frames keep the connection healthy: ping / pong for liveness, and close frames for an orderly shutdown with a status code and optional reason.

  • Text frames are UTF-8; binary frames are opaque bytes.
  • Large messages may be fragmented across multiple frames.
  • Idle connections should still heartbeat so proxies do not drop them silently.
  • Always handle close codes—origin rejection and rate limits often show up there.

Typical API patterns

Teams reach for WebSockets when polling would waste bandwidth or delay updates. Common patterns include:

PatternWhy WebSocketsWatch-outs
NotificationsPush alerts as events happenFan-out and offline delivery still need a store
Chat / collaborationLow-latency bidirectional messagingAuth, rooms, and abuse controls get complex
Live metricsStream ticks without pollingBackpressure if clients cannot keep up
Command channelsInteractive control of a sessionMust authorize every action, not just connect

Many products keep REST or GraphQL for CRUD and reserve WebSockets for the real-time slice. That split keeps most of your security and caching story familiar.

Security essentials

A WebSocket endpoint is still an API surface. The handshake is your authentication gate; everything after is an open channel until you close it.

  • Origin checks — browsers send Origin; validate it server-side so random sites cannot open your socket from a victim’s browser.
  • Auth on handshake — verify cookies, bearer tokens, or tickets during upgrade. Do not wait until the first message.
  • No secrets in query strings — tokens in URLs leak via logs, proxies, and Referer. Prefer headers or a short-lived ticket exchanged over HTTPS first.
  • TLS (wss) — treat cleartext ws:// like cleartext HTTP: fine for local demos, wrong for production.
  • Rate limits and size limits — bound messages per second and max frame size so one client cannot flood memory.
  • Input validation — parse JSON carefully; reject unknown types; never eval client payloads.

For broader API hardening ideas, pair this course with the API security checklist and how to secure public API endpoints.

Live lab

Connect to the hosted educational server and watch frames in both directions. Pick a scenario, connect, send a message, and read the server hint fields in the event log—they explain what just happened in plain language.

Not connected.

Event log

Direction, timestamp, and teaching notes from the server JSON.

    The live lab connects to ws(s)://<page-host>:8766/ws/… (derived from window.location in assets/js/websocket-lab.js). Start the educational server with python server.py inside gui-demo/demo-servers/websocket-lab/ — it is separate from the agent control channel on port 8765.

    Hardening checklist

    • Serve only wss:// in production and terminate TLS at a trusted edge.
    • Authenticate and authorize during the upgrade, then re-check authorization on sensitive actions.
    • Enforce Origin allowlists for browser clients; use separate rules for native or service clients.
    • Cap message size, connection count, and send rate per identity.
    • Validate and schema-check every inbound payload; treat binary as untrusted bytes.
    • Log connect, close, auth failures, and abuse signals without storing secrets.
    • Plan reconnects client-side with backoff; do not assume a socket lives forever.

    Next steps: review API authentication best practices, decode sample tokens with the JWT decoder online, or stress quotas with the rate limit tester.

    Keep going

    Harden the rest of your API surface too.