Skip to content

WebSockets Are Not Always the Answer

Why Server-Sent Events are the simpler choice for most real-time requirements and when the price of a real WebSocket connection actually pays off.

≈ 10 min readSoftwareNode.jsBackend

WebSockets Are Not Always the Answer

A dashboard that shows new orders. A notification when the build has finished. A progress bar for an import that takes twenty minutes. Three typical “real-time” requirements – and in all three cases, the data flows in one direction only: from the server to the client. Still, the first technical answer is surprisingly often: WebSockets, socket.io, a persistent bidirectional connection.

The reflex “real-time equals WebSocket” runs deep, and it is understandable. WebSockets are the most prominent tool on the shelf; every other tutorial series builds a chat with them. But a chat is bidirectional. An order dashboard is not. If you fire up the heavy machinery for pure server-to-client push, you pay for capabilities you never use – and the price is not zero.

What “real-time” really means in the requirements#

If you seriously take the requirement apart, it rarely says “client and server continuously exchange messages in both directions”. It says: the user should see something as soon as it happens, without pressing F5. That is notification, not conversation. The client still talks to the server through ordinary requests – it clicks, it saves, it loads more. The only new thing is that the server may say something on its own.

Incidentally, for some of these cases, simple polling is even enough. A progress bar that sends a GET every two seconds is not an elegant solution, but it is one that everyone on the team understands, that every cache and every proxy knows, and that can be thrown away and replaced in a minute. So the question is not just “WebSocket or not”, but how much machinery the requirement justifies in the first place.

This became clear to me in a shop project this spring. The team had built socket.io into an order dashboard, and the connection itself was never the problem. The problem was everything around it: after every deployment, clients hung on dead connections until the homegrown reconnect kicked in. The load balancer needed special treatment for the protocol upgrade. And when a browser was offline for thirty seconds, exactly the orders from those thirty seconds were missing – nobody had built resuming from the last known state, simply because the protocol doesn’t provide it.

The price of a WebSocket connection#

A WebSocket starts as an HTTP request, but leaves HTTP after the upgrade handshake and becomes its own protocol (RFC 6455) on a raw TCP connection. From that moment on, none of the infrastructure and semantics that the HTTP world brings along apply anymore. Concretely, you buy into:

  • Connection state management on the server: Who is connected, since when, with which session?
  • Your own heartbeats, because dead TCP connections don’t reveal themselves – ping/pong is manual work or a library feature, but always part of your own responsibility.
  • Reconnect logic in the client, including backoff and the question of what was missed during the silence.
  • Special cases in the infrastructure: proxies, load balancers and corporate firewalls that don’t know the upgrade or cut long silent connections.

None of this is unsolvable. Libraries like socket.io take a lot off your hands; that is exactly why they exist. But it remains complexity that has to be operated, monitored and understood when something goes wrong. For a channel that only sends in one direction, that is a bad trade.

const WebSocket = require('ws')
const server = new WebSocket.Server({ port: 8080 })

server.on('connection', socket => {
  socket.isAlive = true
  socket.on('pong', () => { socket.isAlive = true })
})

// dead connections are not detected for free – ping/pong is on us
setInterval(() => {
  server.clients.forEach(socket => {
    if (!socket.isAlive) return socket.terminate()
    socket.isAlive = false
    socket.ping()
  })
}, 30000)

That is just the heartbeat. Reconnect, message buffers and resuming after an interruption are a different story – and in most projects I have seen, surprisingly little of that story has been written.

Server-Sent Events: push over ordinary HTTP#

Server-Sent Events are the unspectacular counterpart: a perfectly normal HTTP GET request whose response never ends. The server keeps the connection open and writes events into it as text; the browser consumes them through the EventSource API. No protocol switch, no upgrade, no new vocabulary for the infrastructure. An SSE endpoint in Express is a few lines:

const express = require('express')
const app = express()

let nextEventId = 0
const eventLog = []
const clients = []

app.get('/events', (req, res) => {
  res.set({
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache',
    Connection: 'keep-alive'
  })
  res.flushHeaders()

  // replay everything the client missed while it was offline
  const lastEventId = Number(req.get('Last-Event-ID') || 0)
  eventLog
    .filter(event => event.id > lastEventId)
    .forEach(event => res.write(toMessage(event)))

  clients.push(res)
  req.on('close', () => clients.splice(clients.indexOf(res), 1))
})

function broadcast(data) {
  const event = { id: ++nextEventId, data }
  eventLog.push(event)
  clients.forEach(res => res.write(toMessage(event)))
}

function toMessage({ id, data }) {
  return `id: ${id}\ndata: ${JSON.stringify(data)}\n\n`
}

app.listen(3000)

The client is even shorter – and that is the real point:

const source = new EventSource('/events')

source.onmessage = event => {
  const order = JSON.parse(event.data)
  renderOrder(order)
}

// no reconnect code here: EventSource reconnects on its own
// and sends the Last-Event-ID header with every new attempt

The comment in the client code is not a claim but the specification. If the connection drops, EventSource reconnects on its own – the server can even set the waiting time via the retry: field in the stream. And when reconnecting, the browser automatically sends the Last-Event-ID header with the ID of the last event received. The server can use it to continue exactly where the client left off. The very feature that was so painfully missing in the shop project is part of the protocol here.

sequenceDiagram
    participant B as Browser (EventSource)
    participant S as Server (Express)
    B->>S: GET /events
    S-->>B: Event 41 (order A-1041)
    S-->>B: Event 42 (order A-1042)
    Note over B,S: Connection drops<br/>(deployment, dead zone, proxy timeout)
    B->>S: GET /events with header Last-Event-ID 42
    S-->>B: Event 43 (everything since 42 is delivered)

On top of that comes an advantage you only learn to appreciate in operations: the entire channel is ordinary HTTP. Load balancers route it like any other request, authentication runs over the same headers and cookies as the rest of the application, and debugging needs no special tooling:

$ curl -N http://localhost:3000/events
id: 1
data: {"orderId":"A-1041","total":89.9}

id: 2
data: {"orderId":"A-1042","total":24.5}

If you have ever tried to go through a WebSocket frame capture together with a colleague from operations, you know what this one curl call is worth. The stream is readable text, every event carries its ID, and the browser sees the same output.

Where SSE honestly hits its limits#

So that this doesn’t turn into an advertisement: Server-Sent Events have limits, and they belong on the table before the decision is made.

The channel is strictly unidirectional. If the client wants to say something, it does so through a normal POST – for forms, clicks and commands, that is perfectly fine and the natural way anyway; for a high-frequency back channel, it isn’t. Second: Internet Explorer and Edge still don’t support EventSource to this day; there you need a polyfill. The available polyfills work decently, but it is one more building block you have to plan for. Third, under HTTP/1.1, SSE shares the browser limit of roughly six connections per host – if you open several streams per tab, you run into it. Under HTTP/2, this eases considerably, because all streams run over a single multiplexed connection. And finally: buffering proxies occasionally have to be convinced by configuration to pass the stream through immediately instead of collecting it – but that is one line of nginx configuration, not an architecture problem.

GraphQL subscriptions: the same reflex, one floor up#

It gets interesting when the reflex moves into frameworks. In the Apollo ecosystem, GraphQL subscriptions run over subscriptions-transport-ws by default, that is, over WebSockets. Yet subscriptions are the textbook example of unidirectional data flow: the client registers once what it is interested in, and from then on only the server talks. Queries and mutations go over HTTP anyway. The bidirectional capability of the transport is used for a single handshake – after that it lies idle, while its operating costs remain.

This kept me busy enough this spring to try it out: subscriptions-transport-sse is my API-compatible SSE variant of this transport, created in my GitHub organization CodeCommission. On the server side, the SubscriptionServer attaches to an Express app and the SubscriptionManager from graphql-subscriptions; on the client side, the SubscriptionClient is attached to Apollo’s network interface as usual:

import { SubscriptionClient, addGraphQLSubscriptions } from 'subscriptions-transport-sse'

const httpClient = createNetworkInterface({ uri: 'https://example.com/graphql' })
const sseClient = new SubscriptionClient('https://example.com/subscriptions')
const apolloClient = new ApolloClient({
  networkInterface: addGraphQLSubscriptions(httpClient, sseClient)
})

apolloClient.subscribeToMore({
  document: gql`
    subscription onOrderCreated {
      orderCreated {
        id
        total
      }
    }`,
  updateQuery: (prev, { subscriptionData }) => {
    // merge the new order into the store and return the new state
  }
})

From the application’s point of view, nothing changes – the same subscription, the same subscribeToMore. Only the transport underneath is now ordinary HTTP with everything described above: automatic reconnect, Last-Event-ID, curl debugging. As a practical test, I built a small presence list with it in April – who is online right now, React and Apollo in the frontend, Node in the backend, events over SSE. Both are deliberately lean projects, more evidence than product. I wanted to show that “GraphQL subscriptions need WebSockets” is a convention, not a necessity.

When WebSockets are the right answer#

After so much counterargument, the other side, because it exists. WebSockets are the right choice when both sides actually send continuously and with low latency:

  • Collaborative editing, where keystrokes and operations from both sides converge
  • Cursor positions and presence signals that flow in both directions many times per second
  • Games and simulations in which every round reconciles client input against server state
  • Frontends where the overhead of a separate POST per client message really matters

The common denominator: the back channel is not an occasional command but a stream. Then the protocol pays off, and then the operational complexity is justified too – after all, you use what you pay for. The deciding question is therefore not “Do we need real-time?” but “Where does the data flow, and how often?”.

flowchart TD
    A[Requirement: real-time] --> B{Does data flow continuously<br/>in both directions?}
    B -- no --> C[Server-Sent Events<br/>plus normal HTTP requests]
    B -- yes --> D{Is the back channel a stream<br/>with latency requirements?}
    D -- no --> C
    D -- yes --> E[WebSockets –<br/>plan for operating costs]

If you answer these two questions honestly, in my experience you end up on the left side of the diagram in the vast majority of cases. The order dashboard, the build monitor, the import progress, the notification bell in the top right of the application – all cases for SSE. The editor with your colleagues’ live cursors is the rare, genuine case for the right side.

The bottom line#

From the shop project and the two SSE experiments, I take away one observation above all: the costs of a technology rarely sit where its strengths are advertised – they sit in operations, in debugging and in the failure cases the protocol doesn’t cover on its own. WebSockets can do something SSE can’t, and if you need that something, they are unrivaled. But “real-time” in the requirements is not yet evidence that you need it. Most of the time, a server just wants to tell you something, and for that, an HTTP request that never ends is enough – with built-in reconnect, built-in resuming and a debugging experience that consists of a single curl call.

The more boring technology wins here not despite but because of its boredom. It has fewer moving parts – and every moving part you never build in can’t break at three in the morning.

Further reading#

Revised and translated from German with the help of AI.