DEV Community

Khushi Patel
Khushi Patel

Posted on

Real-Time Communication: WebSockets vs. Polling

Introduction

Imagine sitting in a café and waiting for your order. You want to know
as soon as it is ready. You could keep asking the cashier, "Is my order
ready?", or ask the cashier to notify you when it is ready. This
illustrates two ways applications receive updates: polling and
WebSockets.

What Is Polling?

Polling is a communication technique in which a client repeatedly sends
requests to a server at regular intervals to check whether new
information is available.

Café Example

Imagine asking the cashier every five seconds whether your order is
ready. Even if it is not ready, you keep asking.

How It Works
  1. The client sends an HTTP request.
  2. The server checks for new information and returns a response.
  3. The client waits for a configured interval.
  4. The client sends another request.
  5. This continues until the update arrives or polling stops.
Short Polling

The client sends requests at fixed intervals, such as every five
seconds.

Advantages: Simple to implement, uses ordinary HTTP, and works when
updates are occasional.

Disadvantages: Requests may be wasted when nothing changes, and
updates may be delayed until the next interval.

Long Polling

The client sends a request, but the server holds it open until new data
is available or a timeout occurs. After receiving a response, the client
sends another request.

Café example: You ask the cashier to let you know when the order is
ready. The cashier waits until there is an update, tells you, and you
ask again if you are still waiting.

Advantages: Can reduce unnecessary empty responses compared with
short polling and can deliver updates soon after they occur.

Disadvantages: The server manages requests that remain open, and
clients need to reconnect after each response. Timeouts and retries need
careful handling.

What Are WebSockets?

WebSockets provide a persistent, two-way communication channel between a
client and server over a single connection. Once established, either
side can send messages at any time without creating a new HTTP request
for every message.

Café Example

Instead of asking the cashier repeatedly, you say, "Please let me know
as soon as my order is ready." The cashier notifies you when it is
ready. You can also talk back through the same channel.

How It Works
  1. The client starts a WebSocket handshake, typically using an HTTP request.
  2. The server accepts the handshake and upgrades the connection to the WebSocket protocol.
  3. The connection stays open while both sides need it.
  4. Client and server can send messages independently.
  5. Either side can close the connection when it is no longer needed.
Simple JavaScript Example
const socket = new WebSocket("wss://example.com/socket");

socket.onopen = () => {
  socket.send(JSON.stringify({ type: "join", roomId: "room-123" }));
};

socket.onmessage = (event) => {
  const message = JSON.parse(event.data);
  console.log("New message:", message);
};

socket.onclose = () => {
  console.log("Connection closed");
};
Enter fullscreen mode Exit fullscreen mode

This is a simplified client example. A production application also needs
authentication, message validation, error handling, reconnection logic,
and authorization checks.

Advantages of WebSockets
  • Supports two-way communication over one connection.
  • Enables low-latency updates without repeated polling requests.
  • Works well for frequent, interactive updates.
  • Reduces repeated HTTP request overhead when messages are frequent.
Disadvantages of WebSockets
  • More complex to implement and operate than basic polling.
  • Servers must manage many long-lived connections.
  • Reconnection and connection state need careful handling.
  • Scaling across multiple application servers requires a strategy for routing and distributing messages.

Polling vs. WebSockets


Feature Polling WebSockets


Communication Client repeatedly Two-way communication
requests updates

Connection Separate HTTP requests Persistent connection

Server updates Usually returned in Server can send
response to a client messages whenever
request needed

Update latency Depends on polling Usually low when
interval connection is healthy

Request overhead Repeated requests, Less repeated request
including when nothing overhead for frequent
changes messages

Implementation Simple More complex

Best for Occasional updates Frequent, interactive
updates


WebSockets are not automatically best for every real-time feature. If
updates are rare, polling may be simpler and more cost-effective.

What Are Server-Sent Events (SSE)?

Server-Sent Events (SSE) allow a server to send updates to a client over
a long-lived HTTP connection. Communication is primarily one-way: server
to client.

Café example: The cashier can notify you whenever your order is
ready, but you cannot send messages back through that same notification
channel.

When to Use SSE
  • Live news feeds
  • Monitoring dashboards
  • Notifications
  • Streaming progress updates from a server

If the client also needs to send frequent messages, use normal HTTP
requests alongside SSE or consider WebSockets.

When Should You Use Each Approach?


Use case Suitable approach


Checking order status every 30 Short polling
seconds

Dashboard with occasional updates Polling or SSE

Live chat application WebSockets

Multiplayer online games WebSockets

Live stock price updates WebSockets or streaming technology

Collaborative document editing WebSockets

One-way live notifications SSE

Background job progress SSE, WebSockets, or polling
depending on requirements


How to Choose the Right Approach

Choose Polling When
  • Updates are occasional.
  • A small delay is acceptable.
  • You want a simple implementation.
  • The client only needs to check status periodically.
Choose Long Polling When
  • Updates are infrequent but should be delivered soon after they occur.
  • You want to avoid frequent empty polling responses.
  • WebSockets are not available or are not justified.
Choose WebSockets When
  • You need two-way communication.
  • Updates are frequent.
  • Low latency matters.
  • Users interact continuously, as in chat or multiplayer games.
Choose SSE When
  • The server needs to stream updates to the client.
  • The client does not need a persistent two-way channel.
  • You want an HTTP-based streaming mechanism.

Real-World Example: A Chat Application

Using Polling

The client asks the server every few seconds whether a new message has
arrived. This can work for a basic prototype, but it may cause
unnecessary requests and delayed message delivery.

Using WebSockets

The client establishes a WebSocket connection. When another user sends a
message, the server can push it through the active connection.

A production chat system also needs message persistence, delivery
acknowledgements, offline message handling, authentication,
reconnection, and a strategy for multiple server instances.

Important System Design Considerations for WebSockets

1. Connection Management

Track active connections and clean them up when clients disconnect. Do
not assume an open connection is always healthy.

2. Reconnection

Clients should reconnect after temporary network failures. Use
exponential backoff with jitter so many clients do not reconnect
simultaneously after an outage.

3. Heartbeats

Ping/pong messages can help detect dead or unresponsive connections and
clean up stale connection state.

4. Scaling Across Multiple Servers

A user's WebSocket connection may be held by one application server
while an event is produced on another. A shared message broker or
pub/sub system can distribute events to the server that owns the
connection.

5. Authentication and Authorization

Authenticate clients during connection setup and authorize each
subscription or message. A connected user should not automatically be
allowed to access every room or resource.

6. Load Balancing

Configure infrastructure to support long-lived connections, appropriate
timeouts, and connection limits. Sticky sessions may help in some
designs, but they do not replace a cross-server messaging strategy.

7. Message Delivery

A successful WebSocket send does not necessarily mean the recipient has
processed or permanently stored the message. Applications that need
reliable delivery require acknowledgements, message IDs, persistence,
and retry or replay logic.

Quick Interview Question

Question: You are designing a WhatsApp-like chat application. Would
you use polling or WebSockets?

Sample answer:

"I would choose WebSockets because chat requires low-latency, two-way
communication. Once the connection is established, both users can
exchange messages without repeatedly requesting updates. I would also
design for reconnection, authentication, message delivery, persistence,
and horizontal scaling."

Follow-Up: Are WebSockets Always Better Than Polling?

No. If updates are infrequent and a delay is acceptable, polling can be
simpler and cheaper to operate. The communication pattern should match
the product requirement.

Follow-Up: What If the User Goes Offline?

The server should not rely on an active WebSocket connection to store
messages. Persist messages, track delivery state, and deliver pending
messages when the user reconnects.

Key Takeaway

  • Short polling: The client repeatedly asks, "Any updates?"
  • Long polling: The client asks, and the server waits until something changes or a timeout occurs.
  • WebSockets: Client and server maintain an open, two-way communication channel.
  • SSE: The server continuously sends updates to the client over a one-way stream.

Choose based on how frequently updates happen, how quickly they must
arrive, whether communication is one-way or two-way, and the complexity
your system can support.

Top comments (0)