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 · 1 min read

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
// 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.
Ehsan Gazar helps software engineers take LLM and agent systems from demo to production. He writes about building LLM systems that hold up in production: evals, tracing, RAG, agent architecture and cost control. He teaches the Senior to Staff AI Engineer cohort on Maven, where engineers learn to design and defend these systems.
Forward Deployed AI Engineering: From Customer Problem to Production Value
A live Maven cohort for engineers: 10 live 90-minute sessions taking one AI engagement from customer problem to production, ending with eight artefacts and a working slice in your own repo.
January cohort starts Tue 12 Jan 2027, Tue & Thu 6:30pm London. Enrolling now, 20 seats, $1,800.
View the live cohortKeep reading
- Your 2027 AI Plan Should Fit on One Page: Six Questions to Answer First
- The AI System Works. So Why Is Nobody Using It?
- If AI Had Existed When Your Workflow Was Designed, Would It Look Like This?
- AI Transformation Is Not Digital Transformation With a New Tool
- Your AI Pilot Saved Time. Why Didn't the Business Change?
- A Chatbot Answers. An Agent Does the Work. Here Is the Difference