What you'll learn: By the end of this lesson you will be able to explain how long polling, Server-Sent Events (SSE) and WebSockets each push updates to a client, show what each one writes on the wire, make a stream resumable with event ids, choose between them for a given conversation, and name what breaks each of them in production: idle timeouts, proxies, dead clients and several server instances.
You order a pizza and want to know when it is ready. You can phone the shop every minute (polling, mostly "not yet"). You can phone once and say "I'll hold", and the shop speaks only when something changes, then you phone again (long polling). You can leave a one-way radio on the counter that the shop talks into whenever it likes (SSE). Or you can keep an open phone line where either of you speaks at any time (a WebSocket).
HTTP connections are in HTTP/1.1, HTTP/2 and HTTP/3 on the Server, and the choice between API styles is in REST, gRPC, GraphQL and WebSockets: Choosing an API Style. This lesson is the dedicated treatment of the three push transports: what they put on the wire, how they recover and where they break.
Verified with RFC 6455, RFC 6202, the WHATWG HTML standard, MDN and the Spring Framework reference (the 7.1.0 pages; the lab runs Spring Framework 7.0.10 from Spring Boot 4.1.2), on 2026-12-01.
The core idea
All three keep a request or a connection open so that the server can answer when it has something, instead of the client asking again and again. They differ in direction and in who owns recovery. Long polling answers one request per event batch; SSE streams many events down one response; a WebSocket upgrades the connection to a two-way message channel. Only WebSockets let the client speak at any moment on the same connection.
Three illustrations run through it: a minimal example (the lab, one order's status feed through all three transports), a realistic example (live order tracking on the ShopStream grocery marketplace) and a failure example (a connection that dies without telling anyone).
Figure 1. The three transports over one numbered feed. How to read this: the feed assigns each event a number; every transport can ask for "everything after N", which is what makes recovery possible.
Long polling: hold the request
RFC 6202 contrasts it with periodic polling. With short polling the server "returns an empty response and the client waits for some time before sending another poll request"; with long polling the server holds the request and responds "only when a particular event, status, or timeout has occurred". The RFC puts the average latency "close to one network transit", the maximum "over three network transits", and says events queue while the client is between requests, so several may arrive "in a batch within a single long poll response". Long poll requests are "completely transparent for intermediary entities", and on timeouts the RFC says "generally 30 seconds is a safer value".
In Spring MVC the held request is a DeferredResult: the servlet thread is released and another thread (an event, a scheduler) sets the result later, at which point Spring dispatches the request back to the container. The constructor can take a timeout and a default result to use on timeout. The key design point is the cursor: the client sends the id of the last event it saw (after=N) and the answer carries everything after it, so a late poll loses nothing.
Server-Sent Events: one response that stays open
SSE is a response with media type text/event-stream, UTF-8, made of lines. The standard names the fields: event sets the event type, data the payload (several data lines are joined with a newline), id sets the last event id, and retry sets the reconnection time in milliseconds when its value is digits only. A line starting with a colon is a comment and is ignored; the standard suggests sending one "every 15 seconds or so" to keep legacy proxies from dropping an idle connection. A blank line ends an event.
Recovery is built in. When the connection drops the browser reconnects after the reconnection time and, if it has seen an id, sends it in the Last-Event-ID request header; the server replays what came after. The client only reconnects if the response was a 200 with text/event-stream: any other status or media type fails the connection, and a 204 tells the client to stop reconnecting. One cost: MDN notes that over HTTP/1.x the limit is per browser and domain, "set to a very low number (6)", which hurts with many tabs; over HTTP/2 the number of streams is negotiated and "defaults to 100".
Figure 2. Resume by id. How to read this: the server never has to know whether the client saw an event; the client says where it stopped.
In Spring, an SseEmitter returned from a controller writes this format, and its event builder sets id, event name and data; the lab also uses the builder's reconnectTime and comment, and the output below shows what they write.
WebSockets: an HTTP upgrade, then frames
A WebSocket starts as an HTTP request. RFC 6455 requires a GET of at least HTTP/1.1 with Upgrade: websocket, Connection: Upgrade, Sec-WebSocket-Version: 13 and a random 16-byte, base64-encoded Sec-WebSocket-Key; a browser client must include Origin. The server accepts with a 101 response and a Sec-WebSocket-Accept header: the key plus the fixed GUID 258EAFA5-E914-47DA-95CA-C5AB0DC85B11, hashed with SHA-1 and base64-encoded. After that the bytes are frames, not HTTP.
A frame has an opcode (text, binary, close, ping, pong), a length (7 bits, or 16 or 64 more), and for client-to-server frames a mask. The RFC says a client must mask every frame and a server must not mask any, and that a server must close the connection on an unmasked client frame. Control frames carry at most 125 bytes. A ping must be answered with a pong with the same data, and an unsolicited pong is allowed as a one-way heartbeat.
Figure 3. Handshake, then frames. How to read this: everything above the 101 is HTTP; everything below is the WebSocket protocol on the same TCP connection.
The handshake is the security boundary. A browser sends Origin, but RFC 6455 says the check exists to stop malicious JavaScript in a trusted browser from faking a handshake, not to stop non-browser clients; a server limited to certain sites should verify the origin and should answer 403 when it is not one it expects. Spring's default is to accept only same-origin WebSocket requests, and its reference warns that "nothing prevents other types of clients from modifying the Origin header value". Authenticate on the handshake request (a cookie or a short-lived ticket): there is no per-message HTTP header afterwards.
In Spring you implement WebSocketHandler or extend TextWebSocketHandler. The reference warns that the underlying session does not allow concurrent sending, so writes must be synchronized, for example with ConcurrentWebSocketSessionDecorator, and that message buffer sizes and idle timeouts are server settings you can configure.
Build it: one feed, three transports
This is the minimal example. The lab is examples/spring-labs/labs/realtime-transports: an in-memory numbered log of order events, a DeferredResult endpoint, an SseEmitter endpoint, a TextWebSocketHandler and a small model of the RFC 6455 wire format.
What it is not. MockMvc runs the two HTTP endpoints in memory, and the timeout and the disconnect are simulated by firing the container's async listeners. The WebSocket handler is called with a mocked session, so there is no handshake and no frame on a real connection; the wire model is a few dozen lines written for this lesson and checked against the examples in RFC 6455 section 5.7, not the code a server or browser uses. No browser, no proxy, no second instance, no Docker.
cd examples/spring-labs && ./gradlew :labs:realtime-transports:test
Eleven tests assert the behaviour below and one compares the report with examples/spring-labs/golden/realtime-transports.txt.
Expected output, captured from a real run (Java 25 language level, Spring Framework 7.0.10, Spring Boot 4.1.2, 2026-12-01), the long-poll scenarios:
== Long polling: DeferredResult held until an event or the timeout
--- 1. Poll with nothing to report: the request is held
request : GET /v1/orders/42/status/poll?after=0
held : true, pollers waiting: 1
(the order is then paid: event 1 is published)
answer : 200 application/json
body : [{"id":1,"orderId":42,"status":"PAID"}]
pollers waiting after the answer: 0
--- 2. Poll again with the cursor, while newer events already exist
request : GET /v1/orders/42/status/poll?after=1
answer : 200 application/json
body : [{"id":2,"orderId":42,"status":"PACKED"},{"id":3,"orderId":42,"status":"SHIPPED"}]
--- 3. Poll with nothing new until the hold time ends
request : GET /v1/orders/42/status/poll?after=3
held : true, pollers waiting: 1
answer : 204
body : (empty)
pollers waiting after the timeout: 0
Scenario 1 shows the request held with one poller registered, answered when the event is published. Scenario 2 shows the cursor: with after=1 the answer carries events 2 and 3 at once. In scenario 3 the lab fires the timeout and the controller's timeout result, a 204 with no body, comes back and the poller is released. The 204 is this lab's choice for "nothing yet, ask again", not something RFC 6202 prescribes.
Expected output, captured from a real run (same run), the SSE scenarios 5 to 7:
--- 5. A new event and a keep-alive comment arrive on the open stream
Content-Type: text/event-stream
| retry:3000
|
| id:1
| event:status
| data:{"id":1,"orderId":42,"status":"PLACED"}
|
| id:2
| event:status
| data:{"id":2,"orderId":42,"status":"PAID"}
|
| id:3
| event:status
| data:{"id":3,"orderId":42,"status":"PACKED"}
|
| :keep-alive
|
--- 6. The client goes away; two events happen while it is gone
open streams: 0, feed followers: 0
--- 7. It reconnects and sends the id of the last event it saw
request : GET /v1/orders/42/events (Last-Event-ID: 3)
Content-Type: text/event-stream
| retry:3000
|
| id:4
| event:status
| data:{"id":4,"orderId":42,"status":"SHIPPED"}
|
| id:5
| event:status
| data:{"id":5,"orderId":42,"status":"DELIVERED"}
|
The stream is plain text: retry:3000, then events with id:, event: and data: lines ended by a blank line, and :keep-alive as a comment. After the client goes away the registration is gone, and the reconnect with Last-Event-ID: 3 receives only events 4 and 5.
Expected output, captured from a real run (same run), the WebSocket handler with a mocked session:
== WebSocket: the handler with a mocked session
--- 8. The handler with a mocked session (no handshake, no frames)
client -> server: subscribe 42 3
server -> client: status 4 42 SHIPPED
(the order is delivered: event 5 is published)
server -> client: status 5 42 DELIVERED
client -> server: ack 5
client -> server: bogus
server -> client: error unknown command
connection closed with code 1000, feed followers: 0
acks recorded: [session-1 acked 5]
Here the client speaks as well as listens: subscribe 42 3 asks for the backlog after event 3 and live events after that, and ack 5 travels the other way. Closing the session removes the subscription.
Expected output, captured from a real run (same run), the wire model:
== WebSocket: the wire format of RFC 6455 (a model, not a server)
--- 9. The handshake answer for the sample key of RFC 6455
Sec-WebSocket-Key : dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
| HTTP/1.1 101 Switching Protocols
| Upgrade: websocket
| Connection: Upgrade
| Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
--- 10. The frames of the text message "Hello"
server -> client (unmasked): 81 05 48 65 6c 6c 6f
client -> server (masked) : 81 85 37 fa 21 3d 7f 9f 4d 51 58
the server decodes it to : "Hello" (opcode 1, masked true)
ping, 'Hello' : 89 05 48 65 6c 6c 6f
pong, 'Hello', from client : 8a 85 37 fa 21 3d 7f 9f 4d 51 58
--- 11. The length field grows with the payload
126-byte payload : first 4 bytes 81 7e 00 7e
65536-byte payload : first 10 bytes 81 7f 00 00 00 00 00 01 00 00
--- 12. A client frame that is not masked
refused: client frame is not masked: the server must close the connection
The accept value and the "Hello" frames are the examples RFC 6455 gives. The first byte 81 is FIN plus the text opcode; the second is the mask bit plus the length. A 126-byte payload switches to the 16-bit length form (7e 00 7e) and 65,536 bytes to the 64-bit form (7f).
Choosing a transport
without asking?"] -->|"no, minutes are fine"| P["Plain polling"] A -->|"yes"| B{"Does the client also send
frequent messages?"} B -->|"yes"| W["WebSocket"] B -->|"no, server to client only"| C{"Are long-lived responses
allowed end to end?"} C -->|"yes"| S["SSE"] C -->|"no"| L["Long polling"]
Figure 4. A first cut, not a rule. How to read this: start from direction. Most dashboards, order trackers and notification feeds only receive.
| Transport | Direction | Recovery | Works through | Cost |
|---|---|---|---|---|
| Long polling | Server to client, one answer per request | Cursor in the next request | Ordinary HTTP intermediaries | A request per batch; latency up to a few network transits |
| SSE | Server to client | Built in: Last-Event-ID and retry |
HTTP, if the proxy streams and does not buffer | Connection limits over HTTP/1.x |
| WebSocket | Both | You build it: ids, resume, heartbeats | Needs upgrade support everywhere | Its own protocol, auth and origin rules |
What breaks them in production
- Idle timeouts. Proxies and load balancers close connections that carry nothing. Heartbeats (an SSE comment, a WebSocket ping) keep them open, and RFC 6202 warns that a hold longer than the infrastructure's timeouts turns into 408 or 504 responses.
- Dead clients. The Servlet API gives no notice when a client disappears. Spring's reference says it is "important to send data periodically, since the write fails if the client has disconnected". A stream that stays quiet can remain registered until a write finally fails.
- Several instances. An event published on instance A must reach a client connected to instance B. The lab has one process; in production the instances need a shared channel or a broker, and each instance forwards only to its own connections.
- Slow consumers. Buffers grow for a client that reads slowly; decide whether to drop, coalesce or disconnect, as in Backpressure.
In practice: ShopStream live order tracking
This is the realistic example, an educational scenario on ShopStream; nothing in it describes a real company.
This is a realistic scenario, not a case history.
The situation
Shoppers watch an order move from placed to delivered on a phone. The app polls GET /v1/orders/{id} every 5 seconds; during a sale that traffic dominates the API's load and the status is still up to 5 seconds late.
Starting architecture
Phones call the API through the gateway; the orders service reads the status from its database.
Options considered
| Option | Behaviour | Problem |
|---|---|---|
| A. Poll every second | Fresher | Five times the load |
| B. Long polling with a cursor | Near-immediate, plain HTTP | One held request per shopper, a new request per update |
| C. SSE with ids | One stream per order screen, resumable | Needs streaming through the gateway; receive-only |
| D. WebSocket | Two-way | Overkill: the shopper sends nothing |
The decision
Option C, with long polling as the fallback where streaming is blocked. The stream sends a keep-alive comment more often than the shortest timeout in the path, numbers events and replays from Last-Event-ID. The screen is receive-only, so a WebSocket would add work for no gain.
Rollout and verification
Test the replay and cleanup paths with MockMvc as in the lab, then verify the real path: stream through the actual gateway and load balancer for longer than their idle timeouts, and check whether the response is buffered. The lab cannot show either.
The 2 a.m. failure
After a gateway upgrade, screens freeze: the gateway now buffers streaming responses until they end. First checks: does the first event reach a client at all, and does the connection die at a round number of seconds (an idle timeout)? Mitigate by switching clients to the long-poll fallback; fix lastingly by turning off buffering for the events path and adding a synthetic check that reads a stream through the gateway.
Architect's notes
- Number every event. Without ids, no transport can resume.
- Use the lightest transport that fits the direction of traffic. SSE and long polling reuse HTTP infrastructure; WebSockets need support at every hop.
- Send heartbeats on purpose, shorter than the shortest timeout in the path.
- Authenticate at the connection start and decide how a long-lived connection learns that a token expired.
Common mistakes
- WebSockets for receive-only data, then rebuilding resume and auth by hand.
- No cursor in long polling, so events between two polls are lost.
- Trusting
Originas authentication. Non-browser clients can set any value. - No heartbeat, so dead connections linger and proxies cut quiet ones.
Key takeaways
- The three transports differ in direction, recovery and what intermediaries must allow.
- Long polling needs a cursor; SSE has
id,Last-Event-IDandretry; WebSockets leave recovery to you. - A WebSocket is an HTTP upgrade followed by masked client frames and unmasked server frames.
- Heartbeats, timeouts and multi-instance fan-out decide whether a push system survives production.
Practice exercises
Exercise 1 (20 min). Run the lab and list, for each transport, what the client sends to resume and what the server sends back.
Exercise 2 (45 min). Add an after cursor test that publishes two events for another order between two polls and proves they never appear.
Exercise 3 (60 min). Add a ping command to OrderSocketHandler that answers pong and a test for it.
The other side of this topic
The front end owns the other half: opening an EventSource or a WebSocket, reconnecting with back-off, merging pushed updates into state and showing a "reconnecting" state. That half is the front-end lesson on polling, SSE and WebSockets in the browser, which pairs with this one.
Related reading
- HTTP/1.1, HTTP/2 and HTTP/3 on the Server: connections, multiplexing and the limits SSE meets.
- REST, gRPC, GraphQL and WebSockets: Choosing an API Style: where push fits among API styles.
- Backpressure: what to do when the client cannot keep up.
- Timeouts, Retries, Backoff and Jitter: the reconnect policy a client needs.
Official documentation
- IETF, RFC 6455: The WebSocket Protocol: the handshake, frames, masking, control frames and origin considerations.
- IETF, RFC 6202: Known Issues and Best Practices for the Use of Long Polling and Streaming in Bidirectional HTTP: definitions, latency, timeouts and intermediaries.
- WHATWG, HTML Standard: Server-sent events: the stream format, reconnection and
Last-Event-ID. - MDN, Using server-sent events: fields and the connection limits.
- Spring Framework, Asynchronous Requests:
DeferredResult,SseEmitterand disconnects. - Spring Framework, WebSocket Server: handlers, allowed origins and server configuration.