Skip to content

Server-sent events and WebSockets: a channel that stays open

Long polling ends every answer and starts a new request. The next two techniques do not end. They keep one connection open for the whole conversation, and the server writes to it whenever it has news. The client does not ask again, and does not pay a request for each update.

Mental model. Polling is knocking on a door. A server-sent event stream is a radio that stays on: the server talks and you listen. A WebSocket is a phone call: after the first exchange either of you can speak at any time.

Server-sent events, SSE, are defined by the HTML Standard for one-way communication from the server to the client. In a browser the client creates an EventSource for an address and listens for open, message and error. The server answers once, with the content type text/event-stream, and never finishes the response. Every update is written on it as lines of text:

id: 3
event: status
data: label printed

The fields are data: for the content, event: for a name, id: to mark the event, and retry: for the delay before reconnecting in milliseconds. A blank line ends the event and dispatches it. A line that starts with a colon is a comment, and the standard advises sending one about every 15 seconds so that a proxy does not close a connection that looks idle.

The part that matters in practice is the reconnection. If the connection closes unexpectedly, the browser reconnects by itself after a delay, and it sends the Last-Event-ID header with the id of the last event it received. A server that keeps its events with ids can resume from there. The code below does that with a log of five events and a connection that drops after two.

C# exampleWriting events with ids and resuming after a dropped connection
server-sent-events.cs
// Server-sent events: the server writes "id:", "event:" and "data:" lines ending in a blank line,
// and a client that reconnects sends Last-Event-ID so that the server can resume after the last event it saw.
var server = new EventServer(["order placed", "payment taken", "label printed", "parcel sent", "parcel delivered"]);
var seen = new List<string>();
string? lastEventId = null;
// First connection: the connection drops after two events.
Console.WriteLine("connect, Last-Event-ID: (none)");
foreach (var frame in server.Stream(lastEventId).Take(2))
{
Console.Write(frame);
lastEventId = Parse(frame, seen);
}
// The client reconnects by itself and says where it was.
Console.WriteLine($"connect, Last-Event-ID: {lastEventId}");
foreach (var frame in server.Stream(lastEventId))
{
Console.Write(frame);
lastEventId = Parse(frame, seen);
}
Console.WriteLine($"client saw: {string.Join(" | ", seen)}");
static string? Parse(string frame, List<string> seen)
{
string? id = null;
foreach (var line in frame.Split('\n', StringSplitOptions.RemoveEmptyEntries))
{
if (line.StartsWith("id: ")) id = line[4..];
else if (line.StartsWith("data: ")) seen.Add(line[6..]);
}
return id;
}
class EventServer(string[] log)
{
// Each event is "id: n", "event: status", "data: text" and a blank line.
public IEnumerable<string> Stream(string? lastEventId)
{
var from = lastEventId is null ? 0 : int.Parse(lastEventId);
for (var i = from; i < log.Length; i++)
yield return $"id: {i + 1}\nevent: status\ndata: {log[i]}\n\n";
}
}
Output
connect, Last-Event-ID: (none)
id: 1
event: status
data: order placed
id: 2
event: status
data: payment taken
connect, Last-Event-ID: 2
id: 3
event: status
data: label printed
id: 4
event: status
data: parcel sent
id: 5
event: status
data: parcel delivered
client saw: order placed | payment taken | label printed | parcel sent | parcel delivered

This is the exact code that produced this output, run with the .NET SDK when the site was built. Nothing runs in your browser.

The first connection delivers events 1 and 2 and drops. The client reconnects with Last-Event-ID: 2 and receives 3, 4 and 5. In the end it has seen all five once, in order. The code in the page is never run in the browser: the output was produced by a CI run of the same file.

SSE is an ordinary HTTP response that does not end, not a new protocol. It is one-way. If the client has something to say, it sends an ordinary request. The standard also mentions the limit on connections per server that a browser applies when a user opens several pages.

A WebSocket starts as an HTTP request and then stops being one. RFC 6455 defines an opening handshake followed by message framing on top of TCP. The client sends a GET with Upgrade: websocket and a random Sec-WebSocket-Key. The server answers 101 Switching Protocols with a Sec-WebSocket-Accept derived from that key, and from then on the connection carries WebSocket frames in both directions.

The RFC states what the change buys: two-way communication between a client and a server without the several HTTP connections and the header on every message that HTTP polling needed. A few details of the protocol are worth knowing:

  • A client must mask all the frames that it sends to the server; a server must not mask the ones it sends.
  • Ping and pong frames let either side check that the other is still there, and an endpoint that gets a ping must answer with a pong.
  • A close handshake ends the connection from either side.

The parts of RFC 6455 used here (the handshake, the frames, ping and pong, and the close) have no counterpart of Last-Event-ID. If the connection drops, the application opens a new one, and an application that needs to resume adds ids of its own.

Return to the flow of the last lesson. Pick Server-Sent Events and WebSocket, and compare them with Long polling.

How an update reaches the client

80 ms
1 s
Compare

The client asks every interval whether there is anything new, and the server answers at once, with or without an update. An update that appears just after a poll waits for the next one.

2.2 s
  1. Opening the channel40 ms
    GET /updates (poll 1)
    Client to Server: GET /updates (poll 1). Arrives at 40 ms.
  2. 80 ms
    200, no update
    Server to Client: 200, no update. Arrives at 80 ms.Processing: 1 s
  3. First update1.1 s
    GET /updates (poll 2)
    Client to Server: GET /updates (poll 2). Arrives at 1.1 s.
  4. 1.2 s
    200 + update 1
    Server to Client: 200 + update 1. Arrives at 1.2 s.Processing: 1 s
  5. Second update2.2 s
    GET /updates (poll 3)
    Client to Server: GET /updates (poll 3). Arrives at 2.2 s.
  6. 2.2 s
    200 + update 2
    Server to Client: 200 + update 2. Arrives at 2.2 s.

Time until the client has both updates: 2.2 s3 round trips on the wire · 2 s of processing

Model notes

Assumptions

  • Each message takes half the round-trip time of the link it crosses. Messages are never lost, never queue and never overlap, and each leaves when the one before it has arrived, once its receiver has finished any processing.
  • Two updates are waiting for the client. The first is ready at the server as soon as it has accepted the client’s first request; for polling, that is just after it answered the first poll, which is the worst moment for polling. The second becomes ready the moment the first reaches the client. The connection to the server is already open, as in the connection-setup flow.

Simplifications

  • The wait between two polls is shown as processing time. The client waits for the interval after each answer; a client that polls on a timer measures the interval from the previous request instead.
  • The headers of an event stream and its first event are drawn as one message, and so are the WebSocket 101 response and the server’s first frame. A server can send them in the same flight, and the client sees the update when they arrive.
  • A long poll that waits too long is answered with nothing after a timeout and the client asks again; an event stream or a WebSocket that drops is reopened by the client after a delay; proxies that close idle connections are not drawn.
  • Only time and the number of messages are counted. The size of the HTTP headers that every poll repeats, the cost of keeping a connection open per client at the server and the load of many short requests are not modelled.

Parameter values are illustrative. They are not benchmarks of any real product.

At a round-trip time of 80 ms, server-sent events send 3 messages: the request, the response with the first update, and the second update. The first update reaches the client after 80 ms, and both are there after 120 ms, which is 1.5 round trips on the wire. A WebSocket sends 3 messages too: the upgrade request, the 101 response with the first frame, and the second frame. It also takes 120 ms. Long polling needs 160 ms, because the second update waits for the client’s new request.

Look at what the two channels have in common: after the first message, the server sends the second update without waiting for anything. That saves what long polling spends on its new request crossing to the server, half a round trip: 40 ms here, and the saving grows with the round-trip time. At 300 ms, long polling takes 600 ms and the two open channels take 450 ms.

The flow does not show what a WebSocket is for. It sends only from the server to the client, where server-sent events do as well, so the two tie. A WebSocket pays off when the client sends many messages too, such as a chat, a shared editor or a game, and the flow has no message from the client after the opening. The flow also does not charge the server for the open connection that each client holds, which is the cost of both channels and of long polling.

Short polling Long polling Server-sent events WebSocket
Who can send after the start Client asks Client asks Server only Both
Connection A request each time A request held open, then again One response that never ends One upgraded connection
Resume after a drop The next poll The next request Built in, with Last-Event-ID The application’s job, with ids of its own
Messages for two updates in the flow 6 4 3 3

A feed that the server writes and the browser only reads, such as a dashboard, a progress bar or a score, fits server-sent events and needs nothing more. A conversation in both directions fits a WebSocket. Long polling remains for an environment that can only make requests. Whichever you choose, the server now holds a connection per client for as long as the client is there, so the number of simultaneous clients becomes a capacity question, as for the connection pools earlier in the course.

Mobile networks and proxies drop connections often. With server-sent events the browser reconnects and says which event it last saw. The server resumes after that id, and an update sent while the client was away is not lost, as long as the server kept it. With a WebSocket, the application must reconnect and ask for what it missed. With long polling, the next request starts again. In every case the server needs to remember events for a while, or accept that a client that was away misses them. That is a delivery guarantee, the subject of the messaging module, applied to the last hop.

  • Server-sent events keep one HTTP response open and write events on it: one way, from the server to the client, with ids, and with reconnection that resumes from Last-Event-ID.
  • A WebSocket upgrades a GET with a 101 response, and then either side can send frames. The protocol does not reconnect for you.
  • In the flow at 80 ms, server-sent events and a WebSocket need 3 messages and 120 ms for two updates, long polling needs 4 messages and 160 ms, and short polling 6 messages and 2.2 s.
  • The two open channels save the new request that long polling needs, half a round trip: 40 ms at 80 ms, 150 ms at 300 ms.
  • Server-sent events fit a feed the browser only reads; a WebSocket fits a conversation in both directions; both cost an open connection for each client.

Next: webhooks, when the server calls you.

Your progress

Built by GhaziAlibi.

© ShardCraft. All rights reserved.