πŸ“ Tutorials
Β· 3 min read
Last updated on

What is WebSockets? Real-Time Communication Explained


WebSockets are a way for a browser and server to keep a connection open and send messages back and forth in real time. Unlike regular HTTP where the browser asks and the server answers, WebSockets let the server push data to the browser whenever it wants.

HTTP vs. WebSockets

HTTP (request-response):

Browser: "Any new messages?"  β†’ Server: "No."
Browser: "Any new messages?"  β†’ Server: "No."
Browser: "Any new messages?"  β†’ Server: "Yes, here's one."
Browser: "Any new messages?"  β†’ Server: "No."

The browser has to keep asking (polling). Wasteful and slow.

WebSockets (persistent connection):

Browser: "Let's open a connection."
Server: "OK, connected."
... (connection stays open) ...
Server: "New message: Hello!"     ← Server pushes instantly
Server: "New message: How are you?" ← No need to ask
Browser: "I'm typing..."          ← Browser can send too

One connection, instant two-way communication.

When to use WebSockets

  • Chat apps β€” messages appear instantly
  • Live notifications β€” new email, new follower
  • Collaborative editing β€” Google Docs, Figma
  • Live dashboards β€” stock prices, server metrics
  • Multiplayer games β€” real-time player positions
  • Live sports scores β€” updates as they happen

When NOT to use WebSockets

  • Regular web pages β€” just use HTTP
  • REST APIs β€” request-response is fine
  • Infrequent updates β€” polling every 30 seconds is simpler
  • Static content β€” no real-time needed

Simple example

Server (Node.js):

import { WebSocketServer } from 'ws';

const wss = new WebSocketServer({ port: 8080 });

wss.on('connection', (ws) => {
  console.log('Client connected');

  ws.on('message', (data) => {
    console.log('Received:', data.toString());

    // Broadcast to all connected clients
    wss.clients.forEach((client) => {
      if (client.readyState === 1) {
        client.send(data.toString());
      }
    });
  });

  ws.send('Welcome!');
});

Client (browser):

const ws = new WebSocket('ws://localhost:8080');

ws.onopen = () => {
  console.log('Connected');
  ws.send('Hello from browser!');
};

ws.onmessage = (event) => {
  console.log('Received:', event.data);
};

ws.onclose = () => {
  console.log('Disconnected');
};

That’s a working chat server in ~30 lines.

WebSockets vs. alternatives

TechnologyHow it worksBest for
WebSocketsPersistent two-way connectionChat, games, collaboration
Server-Sent Events (SSE)Server pushes, client listens (one-way)Notifications, live feeds
Long pollingClient asks, server holds response until data is readySimple real-time, fallback
HTTP pollingClient asks repeatedly on a timerInfrequent updates

SSE is simpler than WebSockets if you only need server β†’ client communication (no messages from the client). It works over regular HTTP and reconnects automatically.

In production

For production apps, most people use a library instead of raw WebSockets:

  • Socket.IO β€” most popular, handles reconnection and fallbacks
  • Pusher / Ably β€” managed WebSocket services (no server to maintain)
  • Supabase Realtime β€” real-time database subscriptions
// Socket.IO example (much simpler)
import { io } from 'socket.io-client';

const socket = io('http://localhost:3000');
socket.on('message', (data) => console.log(data));
socket.emit('message', 'Hello!');

For a deeper technical dive, see how WebSockets actually work under the hood. If you’re building AI features with streaming responses, check out streaming AI responses in Node.js.

FAQ

Do WebSockets work through firewalls and proxies?

Usually yes. WebSockets start as an HTTP request (the upgrade handshake), so they pass through most firewalls. However, some corporate proxies and older load balancers may terminate WebSocket connections. Using WSS (WebSocket Secure, over TLS) helps avoid most issues.

How many WebSocket connections can a server handle?

A single server can handle tens of thousands to hundreds of thousands of concurrent WebSocket connections, depending on hardware and what each connection does. The main bottleneck is usually memory (each connection uses some RAM) rather than CPU.

Should I use WebSockets or Server-Sent Events (SSE)?

Use SSE if you only need server-to-client communication (notifications, live feeds, streaming responses). Use WebSockets if you need bidirectional communication (chat, collaborative editing, games). SSE is simpler to implement and works over standard HTTP.

Related: How WebSockets Actually Work Β· System Design: Real-Time Chat App Β· REST vs GraphQL