Leadership

What is the WebSocket API?

HTTP is request-response. The client asks, the server answers. That works for most things. But when you need real-time, bidirectional communication -- cha...

13 Oct 2023

What is the WebSocket API?

HTTP is request-response. The client asks, the server answers. That works for most things. But when you need real-time, bidirectional communication -- chat apps, live dashboards, collaborative editing -- you need WebSockets.

The WebSocket API opens a persistent TCP connection between client and server. Either side can push messages at any time. No polling. No long-polling hacks. Just a clean, full-duplex channel.

It uses ws:// (unsecured) or wss:// (secured) protocols and works in any modern browser.

Why WebSockets Beat AJAX for Real-Time

AJAX was a clever hack. It was never designed for real-time communication. Polling the server every few seconds wastes bandwidth and adds latency. Long-polling is better but still clunky.

WebSockets were built specifically for bidirectional message pushing. The connection stays open. Messages flow instantly in both directions. That is a fundamentally different model.

Basic Usage

Typescript
// Create a socket instance
var socket = new WebSocket('ws://localhost:8080');

From there you handle onopen, onmessage, onclose, and onerror events. The API is minimal and intentional.

When to Use Them

Use WebSockets when you need low-latency, real-time updates: chat, notifications, live collaboration, multiplayer games, financial tickers.

Do not use them for everything. Standard REST APIs are simpler, more cacheable, and easier to debug for typical CRUD operations. WebSockets add connection management complexity that is only justified when you actually need real-time behavior.

Go further
Live cohort on Maven

Production-Ready Systems with LLMs and Agents

A live Maven cohort, 5 October to 2 November: eight 90-minute sessions where you build LLM and agent systems that survive real traffic, real cost and real failure. Tuesdays and Thursdays, 7:30 to 9:00pm London.

Cohort 2 starts 5 October. Eight live sessions, $1,500.

View the live cohort

Keep reading