Understanding Real-Time Push Technologies: Short Polling, Long Polling, WebSocket, and Server‑Sent Events

This article explains the concepts and practical implementations of real-time push techniques—including short polling, long polling, WebSocket, and Server‑Sent Events—detailing their principles, advantages, drawbacks, and providing complete JavaScript code examples for both client and server sides.

Top Architect
Top Architect
Top Architect
Understanding Real-Time Push Technologies: Short Polling, Long Polling, WebSocket, and Server‑Sent Events

Real‑time push refers to the server notifying the client when subscribed data changes, creating an illusion of instantaneous updates without the client repeatedly requesting.

Short Polling

In short polling the client repeatedly sends HTTP requests at fixed intervals; the server immediately returns data. It requires no extra infrastructure but causes high request overhead and latency trade‑offs.

Frequent request/connection creation puts pressure on the server.

Balancing interval length is difficult: short intervals increase load, long intervals increase latency.

Code Implementation

var ShortPollingNotification = {
  datasInterval: null,
  subscribe: function() {
    this.datasInterval = setInterval(function() {
      Request.getDatas().then(function(res) {
        window.ChatroomDOM.renderData(res);
      });
    }, TIMEOUT);
    return this.unsubscribe;
  },
  unsubscribe: function() {
    this.datasInterval && clearInterval(this.datasInterval);
  }
}

Long Polling

Long polling holds the client request on the server until data changes or a timeout occurs, then returns the response and the client immediately issues a new request, reducing connection overhead.

The server determines when data changes, so the client only receives updates.

Fewer HTTP connections compared with short polling.

Code Implementation

// client
var LongPollingNotification = {
    subscribe: function() {
      var that = this;
      Request.getV2Datas(this.getKey(),{ timeout: 10000 }).then(function(res) {
        var data = res.data;
        window.ChatroomDOM.renderData(res);
        that.subscribe();
      }).catch(function (error) {
        that.subscribe();
      });
      return this.unsubscribe;
    }
}
// server
router.get('/v2/datas', function(req, res) {
  const key = _.get(req.query, 'key', '');
  let contentKey = chatRoom.getContentKey();
  while (key === contentKey) {
    sleep.sleep(5);
    contentKey = chatRoom.getContentKey();
  }
  const connectors = chatRoom.getConnectors();
  const messages = chatRoom.getMessages();
  res.json({
    code: 200,
    data: { connectors: connectors, messages: messages, key: contentKey },
  });
});
// express‑longpoll snippet
function pushDataToClient(key, longpoll) {
  var contentKey = chatRoom.getContentKey();
  if (key !== contentKey) {
    var connectors = chatRoom.getConnectors();
    var messages = chatRoom.getMessages();
    longpoll.publish('/v2/datas', {
      code: 200,
      data: {connectors: connectors, messages: messages, key: contentKey},
    });
  }
}
longpoll.create("/v2/datas", function(req, res, next) {
  key = _.get(req.query, 'key', '');
  pushDataToClient(key, longpoll);
  next();
});
intervalId = setInterval(function() {
  pushDataToClient(key, longpoll);
}, LONG_POLLING_TIMEOUT);

WebSocket

The WebSocket protocol enables full‑duplex communication over a single TCP connection, reducing the need for multiple HTTP requests.

Features

Bidirectional communication with lower overhead.

Handshake uses HTTP, so it works through proxies and on ports 80/443.

No same‑origin restriction; supports text and binary frames.

Protocol identifier is ws (or wss for TLS).

Code Implementation

// client
var WebsocketNotification = {
  subscribe: function(args) {
    var connector = args[1];
    this.socket = io();
    this.socket.emit('register', connector);
    this.socket.on('register done', function() {
      window.ChatroomDOM.renderAfterRegister();
    });
    this.socket.on('data', function(res) {
      window.ChatroomDOM.renderData(res);
    });
    this.socket.on('disconnect', function() {
      window.ChatroomDOM.renderAfterLogout();
    });
  }
}
// server
var io = socketIo(httpServer);
io.on('connection', (socket) => {
  socket.on('register', function(connector) {
    chatRoom.onConnect(connector);
    io.emit('register done');
    var data = chatRoom.getDatas();
    io.emit('data', { data });
  });
  socket.on('chat', function(message) {
    chatRoom.receive(message);
    var data = chatRoom.getDatas();
    io.emit('data', { data });
  });
});

Server‑Sent Events (SSE)

SSE uses a single HTTP long‑lived connection that streams text/event‑stream data from server to client; the client receives messages via the EventSource API.

SSE works over standard HTTP, while WebSocket is a separate protocol. SSE is lightweight and simpler to implement. Automatic reconnection is built‑in. Only text payloads; binary data requires encoding. Custom event types are supported.

Compatibility

Supported by all modern browsers except older versions of Internet Explorer.

Code Implementation

// client
var SSENotification = {
  source: null,
  subscribe: function() {
    if ('EventSource' in window) {
      this.source = new EventSource('/sse');
      this.source.addEventListener('message', function(res) {
        const d = res.data;
        window.ChatroomDOM.renderData(JSON.parse(d));
      });
    }
    return this.unsubscribe;
  },
  unsubscribe: function() {
    this.source && this.source.close();
  }
}
// server
router.get('/sse', function(req, res) {
  const connectors = chatRoom.getConnectors();
  const messages = chatRoom.getMessages();
  const response = { code: 200, data: { connectors, messages } };
  res.writeHead(200, {
    "Content-Type":"text/event-stream",
    "Cache-Control":"no-cache",
    "Connection":"keep-alive",
    "Access-Control-Allow-Origin": '*',
  });
  res.write("retry: 10000
");
  res.write("data: " + JSON.stringify(response) + "

");
  var unsubscribe = Event.subscribe(function() {
    const connectors = chatRoom.getConnectors();
    const messages = chatRoom.getMessages();
    const response = { code: 200, data: { connectors, messages } };
    res.write("data: " + JSON.stringify(response) + "

");
  });
  req.connection.addListener("close", function() {
    unsubscribe();
  }, false);
});

Summary

Short and long polling are simple to implement but unsuitable for high‑frequency real‑time scenarios due to latency and server load.

WebSocket provides low‑cost, full‑duplex communication ideal for interactive, high‑frequency applications.

SSE offers server‑to‑client push without bidirectional needs, making it a lightweight alternative for one‑way updates.

References

https://tools.ietf.org/html/rfc6455

https://developer.mozilla.org/en-US/docs/Web/API/WebSocket

https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events

http://www.ruanyifeng.com/blog/2017/05/websocket.html

https://www.ruanyifeng.com/blog/2017/05/server-sent_events.html

https://juejin.im/post/6844903955240058893

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendReal-TimeWebSocketPollingSSE
Top Architect
Written by

Top Architect

Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.