Server-Sent Events as a Simpler Alternative to WebSockets

When a real-time dashboard only needs updates pushed to the browser, Server-Sent Events can be simpler than WebSockets. A Go example and my notes.

· 3 min read · Erik Kubica

In 2021, I spent three days debugging why a client's live shipment tracker kept dropping connections across European mobile carriers.

Users on 4G would leave their office, drive a few kilometers down the highway, and the web interface would silently stop updating. We were using WebSockets. The connection had terminated without firing a clean close event, and my hand-written client-side reconnection logic was stuck in an exponential backoff loop.

When I build a real-time feature, whether it is an order status ticker, an exchange rate feed, or a notification bell, my default instinct used to be WebSockets.

On the projects I've worked on, most of these features only needed one-way server-to-client updates. For that case, the web platform has had Server-Sent Events (SSE) for a long time, and I wish I had looked at it sooner.

Where WebSockets Cost Me Extra Work

WebSockets are not plain HTTP. Once the initial 101 Switching Protocols handshake completes, you are working over a duplex TCP socket.

That brought some operational headaches in my experience:

  • No HTTP/2 Multiplexing: Your browser can multiplex many HTTP/2 requests over a single TCP connection, but a WebSocket takes over its own socket.
  • Load Balancer Friction: Some cloud load balancers and CDNs need sticky sessions or proxy timeout overrides to keep WebSocket connections alive.
  • Client Library Overhead: The native browser WebSocket does not reconnect automatically. If the network drops, you write retry loops, backoff timers, and queue managers yourself.
  • Authentication Headaches: The browser WebSocket constructor does not allow custom authorization headers. I have seen auth tokens passed in URL query strings and ending up in server access logs.

HTTP Streaming With SSE

Server-Sent Events are plain HTTP. No custom protocol, no special proxy settings, no third-party client packages.

Here is how I implement an SSE stream in Go using only the standard library:

package main

import (
    "fmt"
    "net/http"
    "time"
)

func eventsHandler(w http.ResponseWriter, r *http.Request) {
    flusher, ok := w.(http.Flusher)
    if !ok {
        http.Error(w, "Streaming unsupported", http.StatusInternalServerError)
        return
    }

    w.Header().Set("Content-Type", "text/event-stream")
    w.Header().Set("Cache-Control", "no-cache")
    w.Header().Set("Connection", "keep-alive")

    ticker := time.NewTicker(2 * time.Second)
    defer ticker.Stop()

    for {
        select {
        case <-r.Context().Done():
            return
        case t := <-ticker.C:
            fmt.Fprintf(w, "event: ping\ndata: {\"timestamp\": %d}\n\n", t.UnixMilli())
            flusher.Flush()
        }
    }
}

And in the browser, the EventSource API is built in:

// Native browser code. Zero npm dependencies.
const source = new EventSource('/api/events');

source.addEventListener('ping', (event) => {
  const data = JSON.parse(event.data);
  console.log('Server heartbeat:', data.timestamp);
});

What you get out of the box:

  1. Automatic Reconnection: If the user goes through a tunnel or switches Wi-Fi networks, the browser retries the connection after a few seconds.
  2. Event IDs & Message Recovery: If the connection breaks, the browser sends a Last-Event-ID HTTP header on reconnect so my server can replay missed messages.
  3. HTTP/2 & HTTP/3 Compatibility: The event stream shares the existing connection with static images, stylesheets, and API queries.

On one 4-core, 4 GB RAM server I tried, 10,000 idle SSE connections in Go used roughly 24 MB RAM and 0.5% CPU, while a WebSocket connection manager in Node held around 450 MB. That comparison depends heavily on the implementation, so don't read it as a general benchmark.

SSE does have limits. It is one-way, browsers cap the number of connections per domain on HTTP/1.1, and it is text-based. If the client needs to send a lot of data back over the same channel, WebSockets are the right tool.

I still use WebSockets for things like collaborative canvas editing and multiplayer games. For metrics, progress bars, notifications, and AI streaming tokens, SSE has been enough for me, with less code and less infrastructure to configure.

Tell me what you need built

Usually a reply within a day, by email or WhatsApp.