Dev Learning Lab

The labs on this site need JavaScript to run. The same content is written out below.

Learn › Networking › HTTP

Polling, SSE, and WebSocket

Four ways to tell the browser what happened on the server

Why it exists — If the browser asks every few seconds so that it can show news right away, most requests come back empty, the load on the server grows, and notifications are still delayed by up to the length of the interval. SSE and WebSocket keep one connection open and let the server send news the moment it occurs, so it arrives immediately without anyone asking.

Where it's used today — SSE is used where the server only needs to send, such as notification badges, delivery status, progress of a long task, and price quotes, and WebSocket is used where both sides exchange messages often, such as chat, collaborative editing, and online games. In Spring they are built with SseEmitter and WebSocketHandler. If the information changes only once every few minutes, simple polling is enough.

HTTP works by the client asking and the server answering, so even when the server has a new notification, it cannot speak first. The options are to ask periodically (polling), to hold the answer back (long polling), to keep the connection open and stream data through it (SSE), or to switch to a two-way channel (WebSocket).

Checked against real execution · The server and browser code on the screen was run on Spring Boot 4.1.1 (DeferredResult, SseEmitter, TextWebSocketHandler) and Chrome 158, and the request counts, empty responses, order of notification arrival, and open channels were compared for all 72 combinations. Proxies and multi-server setups follow the standards and documentation

Concepts in this lab

SSE (server-sent events) and polling
Polling is an approach in which the client repeatedly asks the server, at regular intervals, whether there is new data. SSE keeps one HTTP connection open while the server keeps sending events to the client, and data can travel in one direction only, from the server to the client. For cases such as notifications, where only the server needs to send, it is simpler than WebSocket.
WebSocket
Why it exists — To imitate a two-way conversation with HTTP requests and responses alone, the client has to keep sending requests, and the headers go along every time even with a short message. WebSocket starts a connection with HTTP and then switches the same TCP connection to WebSocket communication, so both sides exchange short messages without HTTP headers.
Where it's used today — In Spring, STOMP support (@MessageMapping) is sometimes used to handle per-topic subscriptions such as chat rooms. When you scale out to several servers, connections are split across the servers, so to send to a user connected to a different server you also use a message relay such as Redis.
A communication protocol that lets a client and a server keep one connection open and send messages freely from either side. In HTTP, the server can respond only after the client sends a request. With this protocol, the server can send data first, so it is used for chat and real-time notifications.
HTTP as a stateless protocol
Why it exists — If the server had to remember the earlier conversation for each request, the resources needed to keep that memory would grow with the number of users, and a conversation could not continue once a connection was cut. HTTP is defined so that a request can be handled by looking at that request alone, so the server does not have to remember anything between requests.
Where it's used today — Receiving web pages and images, a mobile app calling a server API, and a server calling another service's API are all done over HTTP. For features like chat, in which the server also has to send data first at any time, WebSocket is used together with it.
HTTP is a communication protocol in which a client sends a request and a server responds. Stateless means that the server does not remember the content of earlier requests, so each request must carry all the information needed to process it. Because the server keeps no state, any server can take a request, which makes it easy to add servers. Information that must carry over, such as a login state, is kept with cookies, sessions, or tokens.

Try these

Running with the default settings

  1. Every 5 seconds, the browser requests "Are there any new notifications?" The server returns the notifications that have piled up until then, or an empty response if there are none.
  2. 5s: The browser sent a request. It received the 1 notification created in the meantime. They were created at 3.7s, but had to wait until the next request.
  3. 10s: The browser sent a request. There were no new notifications, so it received an empty response.
  4. 15s: The browser sent a request. It received the 1 notification created in the meantime. They were created at 13.7s, but had to wait until the next request.
  5. 20s: The browser sent a request. There were no new notifications, so it received an empty response.
  6. 25s: The browser sent a request. It received the 1 notification created in the meantime. They were created at 23.7s, but had to wait until the next request.
  7. 30s: The browser sent a request. There were no new notifications, so it received an empty response.
  8. Of the 6 requests in 30 seconds, 3 ended empty-handed.

Result of this run

Code

// Browser (lastId and show are an example variable and function; their declarations are omitted)
setInterval(async () => {
    const res = await fetch("/notifications?after=" + lastId);
    show(await res.json());              // an empty array if there is nothing
}, 5000);

Assumptions of this model

Notifications are assumed to occur evenly over the 30-second window. The messages the client sends are fixed at 10 in 30 seconds (one at 0 seconds, then one every 3 seconds). The timeout of long polling is set to 30 seconds. The server code on the screen (waitForNew, stream, and ChatHandler) was compiled as it is and started on Spring Boot 4.1.1 (embedded Tomcat 11.0.24, Spring WebSocket 7.0.9), and the browser code on the screen was run as it is in Chrome 158 on this computer (headless), so all 72 combinations were compared through 36 distinct runs (verify/spring/realtime_probe.out.txt). The number of HTTP requests the browser sent (recorded by the developer tools) and the number the server received, the number of empty responses, the number of notifications each polling request received, and the channel left open at the moment 30 seconds had passed all matched the screen. The only thing changed is the WebSocket address (the ws:// address of this server instead of wss://shop.example/chat). Long polling has no browser code on the screen, so a loop that does what it says ("as soon as it gets a response, it requests again") was added, and the server side of polling, POST /messages, and the example waiters, emitters, broadcast, and show were written separately to run it. The average delivery delay on the screen is calculated from the time a notification occurred and the time of the request that received it. The measured values were 6 to 22ms longer than that for polling, and 0 to 5ms per notification for long polling, SSE, and WebSocket (inside the same computer there is almost no network round trip). Even with polling, the browser did not open a new TCP connection for each request but kept reusing one (HTTP keep-alive). That is why the last column shows not the number of connections but the channel on which the server can send first. Also checked: when the server ended the SSE response, the browser reconnected by itself 3 seconds later, and when the server closed the WebSocket, it did not reconnect for 7 seconds. A long-polling request received an empty array 30 seconds after it was sent. Calling send on the line right after new WebSocket throws InvalidStateError because the connection is not open yet (so the code on the screen sends in onopen). How well these work with proxies and load balancers, and putting Redis publish/subscribe in between when there are several servers, were not run; they follow the HTML standard (EventSource), the WebSocket standard (RFC 6455), and the Spring documentation.

Previous lab: CORS · Next lab: TLS handshake

Concepts in this lab

What this lab shows

Settings

Code


      
    

Diagram

Run comparison

Try these