Long Polling vs WebSocket: What to Choose for Real-Time?

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Long Polling vs WebSocket in JavaScript: An Epic Battle for Real-Time

\n\n

Once upon a time, in an era when the internet was slow and browsers were simple, the only way to find out that new data had appeared on the server was to press F5. Then AJAX came along, and we learned to manually poll the server. But what if data should arrive on its own, without our involvement? Welcome to the world of real-time communications.

\n\n

In this article, we will break down the two main approaches that still divide the developer community: the good old Long Polling and the modern, bold WebSocket. We will write code in JavaScript, look under the hood, and understand which tool to choose for your next project. If you want to understand long polling vs websocket once and for all — you are in the right place.

\n\n

The Problem: How to Make the Server Speak First?

\n\n

HTTP is a unidirectional protocol. The client (browser) sends a request, the server responds — and that's it, lunch is over. But in the real world (chats, stock quotes, notifications), data needs to flow in the opposite direction. For a long time, developers had to improvise. Here are the two main ways to solve this problem.

\n\n

Long Polling: A Clever Trick with Time

\n\n

Imagine you call customer support and say: "I'll wait on the line until an operator is free." You don't hang up. That's exactly how Long Polling works.

\n\n

How it works:

\n
    \n
  • The client sends a regular HTTP request.
  • \n
  • The server does not respond immediately if there is no data. It "hangs" and waits.
  • \n
  • As soon as data appears — the server sends a response.
  • \n
  • The client processes the response and immediately opens a new connection.
  • \n
\n\n

Client-side code (JavaScript):

\n
function longPoll() {\n  fetch('/updates')\n    .then(response => response.json())\n    .then(data => {\n      console.log('New data:', data);\n      // Immediately start a new poll\n      longPoll();\n    })\n    .catch(error => {\n      console.error('Error, reconnecting in 2 sec:', error);\n      setTimeout(longPoll, 2000);\n    });\n}\n\n// Start\nlongPoll();
\n\n

Pros:

\n
    \n
  • Works on any server and any browser (even IE6).
  • \n
  • Does not require special protocols — pure HTTP.
  • \n
  • Passes through any corporate proxies and firewalls.
  • \n
\n\n

Cons:

\n
    \n
  • Each message is a new HTTP request (headers, cookies, overhead).
  • \n
  • The server holds many open connections (the C10k problem — 10 thousand clients).
  • \n
  • Latency is higher than WebSocket.
  • \n
\n\n

WebSocket: A Permanent Communication Channel

\n\n

WebSocket is like an open line between a spaceship and mission control. You establish the connection once, and then both sides can send data at any time, without any extra ceremony.

\n\n

How it works:

\n
    \n
  • The client initiates a handshake via HTTP.
  • \n
  • The server switches the protocol to ws:// or wss://.
  • \n
  • A permanent bidirectional connection is established.
  • \n
  • Data is transmitted in frames — lightweight and fast.
  • \n
\n\n

Client-side code (JavaScript):

\n
const socket = new WebSocket('wss://example.com/chat');\n\n// When the connection is open\nsocket.onopen = function() {\n  console.log('Connection established');\n  socket.send(JSON.stringify({ type: 'greeting', text: 'Hello, server!' }));\n};\n\n// When a message arrives\nsocket.onmessage = function(event) {\n  const data = JSON.parse(event.data);\n  console.log('Message from server:', data);\n};\n\n// On error\nsocket.onerror = function(error) {\n  console.error('WebSocket error:', error);\n};\n\n// On close\nsocket.onclose = function(event) {\n  console.log('Connection closed. Code:', even                

Blogs

Book Recommendations