Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Tip

The usual AJAX request/response we’re all used to doesn’t keep the connection open for this sort of use case. Instead we need a push-based method like WebSockets, Long Polling, Server-Sent Events (SSE) and more recently HTTP2 push.

Long Polling

Overview

Long polling is essentially a more efficient form of the original polling technique (with JavaScript - XMLHttpRequest). Making repeated requests to a server wastes resources, as each new incoming connection must be established, the HTTP headers must be parsed, a query for new data must be performed, and a response (usually with no new data to offer) must be generated and delivered.

The connection must then be closed and any resources cleaned up. Rather than having to repeat this process multiple times for every client until new data for a given client becomes available, long polling is a technique where the server elects to hold a client’s connection open for as long as possible, delivering a response only after data becomes available or a timeout threshold is reached.

  1. A client initiates an XHR/AJAX request, requesting some data from a server.

  2. The server does not immediately respond with request information but waits until there is new information available.

  3. When there is new information available, the server responds with new information.

  4. The client receives the new information and immediately sends another request to the server restarting the process.

vvv

challenges

  1. Message ordering and delivery guarantees : Cannot be guaranteed if the same client opens multiple connections to the server or if client was not able to receive the message then there will be possible message loss.

  2. Performance and scaling.

  3. Device support and fallbacks.

WebSockets

Server-Sent Events

On this page.

Table of Contents