Choosing Between Long Polling vs WebSockets for Server Updates

WebSockets vs Long Polling: What should you choose for your application?

Mahesh Samarasinghe
Bits and Pieces

--

Real-time communication in web applications has become crucial to today’s software development. As a result, many technologies have been invented to achieve real-time communication, and two of the most popular technologies are long polling and WebSockets.

Although both these technologies provide real-time communication, they have their differences, making each technology a better candidate than the other for different scenarios.

Therefore it is crucial to understand how each technology handles communication and know their differences so that developers can make informed decisions on when to use which technique. Hence, this article will provide developers with all the information they will need to select between Long Polling and WebSockets.

Long Polling

Long polling is a variation of the standard polling method where the client regularly sends HTTP requests to the server. If the server has updates, it will send the data in the subsequent request received.

However, one significant downside of the standard polling technique was that most requests do not return new data and increase the network overhead. Furthermore, the server has to process unnecessary requests even though it does not have any new data to return.

Therefore, long polling was introduced to solve the issues of network overhead and delays. In long polling, instead of sending requests periodically, it opens up a new connection with the server and keeps the connection open until the server has new data to send. Then, the server will use the active connection to send instant updates to the client.

Additionally, the connection will timeout if no updates are received from the server over a specified period. Hereafter, the client will create a new connection and continue waiting for updates from the server.

Doing so makes Long Polling more efficient than the standard polling technique, as there are fewer request calls. Long Polling can be implemented using any language. The snippet shown below depicts the implementation of Long Polling in Node.js.

const express = require("express");
const app = express();

app.get("/poll", (req, res) => {
let counter = 0;
const intervalId = setInterval(() => {
counter++;
if (counter === 5 ) {
clearInterval(intervalId);
return res.send("Data received after 5 seconds");
}
}, 1000);

// Close the connection after 10 seconds if data has not yet been received
setTimeout(() => {
clearInterval(intervalId);
return res.send("Timeout: data not received");
}, 10000);
});

app.listen(3000, () => console.log("Server listening on port 3000"));

The snippet above highlights a simple example of the long polling technique. The client will send a request to the poll endpoint to achieve long-polling. When the poll endpoint is invoked, it will keep the request open for as long as 10 seconds and wait for any new updates from the server. After 5 seconds, the server will return the latest updates and close the connection or terminate if it doesn't get new data after 10 seconds.

The client will then need to make a subsequent request to the poll endpoint to initiate the long-polling of data.

WebSockets

WebSockets are a real-time communication technology that provides a full-duplex and persistent communication channel that operates over HTTP through a single TCP/IP connection between a client and a server. Additionally, WebSockets supports TLS encryption, HTTP Proxies and intermediaries as it is designed to work over ports 80 and 443

When creating a WebSocket connection with the server, a client will send a request which contains the Upgrade header to switch to the WebSocket protocol.

Once the server receives the request, it will process it and send a response to the client acknowledging the WebSocket handshake request only if the WebSocket connection can be created.

Once the client receives a successful acknowledgement on the WebSocket handshake, a WebSocket connection will be opened, and both the server and the client can communicate via the channel.

However, if a WebSocket connection cannot be created, the server will send a response acknowledging that it cannot create a socket connection.

Like Long-Polling, WebSockets can also be implemented in any programming language that supports networking. For example, my implementation below shows how developers can build WebSockets with Node.js.

const WebSocket = require("ws");

const server = new WebSocket.Server({ port: 8080 });

server.on("connection", (socket) => {
console.log("Client connected");

socket.on("message", (message) => {
console.log(`Received message: ${message}`);
socket.send(`You said: ${message}`);
});

socket.on("close", () => {
console.log("Client disconnected");
});
});

The code snippet above shows a simple example of a WebSocket server implementation using the ws library.

It shows that when a client is connected, the connection event will trigger and establish a WebSocket connection. Then the server can listen to any data received from the client side using the message event and send using the send method provided by the ws library.

When the connection closes, the close event is triggered, and these callbacks can be used for any required cleanup tasks.

Hereafter, it’s essential to provide an implementation for the client to establish a connection to the socket and listen to new updates to the server.

const WebSocket = require('ws');

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

socket.onopen = () => {
console.log("Connected to server");
socket.send("Hello server");
};

socket.onmessage = (event) => {
console.log(`Received message: ${event.data}`);
};

socket.onclose = () => {
console.log("Disconnected from server");
};

When the connection is established with the server, the onopen event is triggered. Likewise, the onmessage event is triggered when a message is received from the server, while the send method provided by the ws library can send messages to the server. Furthermore, onclose event will be triggered once either side closes the connection.

Long polling vs WebSockets

Choose between Long Polling and Websockets

Long polling and Websockets have their own ups and downs, making them the best candidates for different scenarios. Therefore, let us discuss some guidelines on when to use what.

Websockets can be used when,

  • The application requires a full-duplex communication channel
  • The application requires low latency, real-time communication
  • Scalability is crucial for the application
  • Application is a mission-critical application that requires robust error handling

Long Polling can be used when,

  • The application does not need a bi-directional communication channel
  • Near real-time communication is sufficient for the application
  • The application has limited bandwidth and network resources
  • Time to market or simplicity is critical

Conclusion

Long polling and WebSockets techniques can provide real-time updates in your application, but depending on the requirement, one might be a better candidate.

Generally speaking, WebSockets has many advantages over long polling due to better scalability, robust error handling, and low latency. But long polling might be a better choice for simple applications where real-time communication is not crucial.

I hope this article helps you make a better decision on your use case. Thank you for reading.

From Monolithic to Composable Software with Bit

Bit’s open-source tool helps 250,000+ devs to build apps with components.

Turn any UI, feature, or page into a reusable component — and share it across your applications. It’s easier to collaborate and build faster.

Learn more

Split apps into components to make app development easier, and enjoy the best experience for the workflows you want:

Micro-Frontends

Design System

Code-Sharing and reuse

Monorepo

--

--