Search posts

Local-first PWA sync: last-writer-wins done carefully
Exactly-once doesn’t come for free: Kafka, Flink and ClickHouse
Building an end-to-end encrypted chat app with libsodium

SSE cost 118 KB per device on Spring MVC: moving to Centrifugo

Each held-open SseEmitter cost ~118 KB of heap. Moving device connections to Centrifugo: publishing from Spring, recovery, GOMEMLIMIT, proxy memory.

Written by
Published
Reading time
10 min
Written against
Spring Boot 3.5, Centrifugo 6
SSE cost 118 KB per device on Spring MVC: moving to Centrifugo

My planner app kept one Server-Sent Events stream open per device so it could say "something changed, pull now". A load test showed what that costs on Spring MVC: each open stream held about 118 KB of live heap, and the test had to stop near 3,000 devices, close to the API's 768 MB container limit. Doubling the memory would only double the number. So I moved every device connection out of the API into Centrifugo, a Go server built to hold them, and the API now makes one HTTP call per change.

This post covers what one SSE stream costs in Tomcat and why, and the move to Centrifugo in Lịch ngày (Spring Boot backend, local-first PWA frontend) with the code on both sides. It then goes through what the Centrifugo load test taught me about Go's memory limit and about proxies in front of WebSockets, and what the move made worse.

The stream only carried a hint

Devices never got data over the stream. The app is local-first: every device keeps its own copy in IndexedDB and syncs with one request in both directions, as I described in the post on the sync protocol. Each device also reconciles on a timer of its own: every few minutes, less often while the stream is live. The stream only shortened that wait: when a push from one device committed, the API sent {"table": "..."} to the user's other devices, and they pulled that table right away.

That matters for the rest of the post. A lost hint costs a device at most the next reconcile, never data. So the connection layer can be fire and forget, and it can fail for a while without anyone losing an edit.

What one SSE stream costs in Tomcat

On Spring MVC, a controller returns an SseEmitter and the request goes async: the servlet thread is released, but the connection, its Tomcat processor and its buffers stay allocated until the stream ends. That is normal and documented behavior, and it is cheap per request. It is not cheap when the "request" lasts an hour and every signed-in device holds one.

The load test (a small Node script, since k6 has no SSE client) opened streams in steps with test users' tokens. The first run, with the API at its 768 MB limit:

Step Result
1,000 streams fine
near 3,000 streams stopped by the script's guard at 752 MB of 768 MB

A heap histogram of 1,000 streams on a local copy put the cost at about 118 KB of live heap per open stream. Nothing leaked: the memory is freed when the stream closes. It is simply what a held-open servlet request costs.

The test also found two smaller problems that came with the streams:

  • An ERROR per disconnect. When a stream ends, Spring dispatches it again as ASYNC. My auth filters did not run on that dispatch, the request looked anonymous, and access was denied on a response that was already committed. That was 424 stack traces for about 3,000 streams. The fix, as Spring Security recommends, is to permit ASYNC and ERROR dispatches of a request that was authorized on its first dispatch.
  • No cap per user. Earlier, a security pass had already limited each account to 20 open streams, closing the oldest beyond that. Without it, one leaked token or one client stuck reconnecting could use up the connector's connections and cut everyone else off.

More memory only moves the ceiling

The first reaction was to double the API's memory limit, and I did, as a stopgap. But the arithmetic does not change: the number of devices online grows linearly with memory, and the JVM's heap is also what serves every sync request. A request/response API should not be the process that holds long-lived connections. Scaling it out would not help much either: each instance would need its share of the streams. It would also need a way to route a hint to whichever instance holds the device's stream, which the app had already built on Redis pub/sub.

The usual answer is a separate service whose only job is holding connections, written in a runtime where a connection is cheap. I chose Centrifugo: a single Go binary, WebSocket with SSE and HTTP-streaming fallbacks, JWT auth, per-channel history, and an HTTP API for publishing. Two more apps on the same server (a chat app and a bidding tool, both on Socket.IO) could use it too, so one service replaced three connection layers.

The shape after the move

After the move, a change travels from one device to the others in four steps, and only one service holds connections:

Sequence diagram with four participants: phone, API, Centrifugo and laptop. The phone pushes a change to the API over HTTP. The API publishes the table name to Centrifugo. Centrifugo sends the hint to the laptop, and the laptop pulls the data from the API over HTTP.PhoneAPIRealtime(Centrifugo)Laptoppush (HTTP)publish{table}hintpull(HTTP)Centrifugo holds every device connection.The API holds none.
Centrifugo holds every device connection. The API only publishes a small hint and keeps serving plain HTTP.
  • The API holds no connection. After a push commits, it publishes a small message to the user's channel and forgets about it.
  • Each user has a user-limited channel, plan:#<sub>. In Centrifugo, the # symbol is the user channel boundary: only a connection whose user ID is <sub> may subscribe, so no subscribe proxy or permission check is needed in the app.
  • Devices authenticate with the access token they already have. Centrifugo checks the Keycloak token's signature, issuer and audience itself, and the client library asks for a fresh token before the old one expires.
  • The publish API is internal only. Only the connection endpoint is reachable from outside.

Publishing from Spring: async, after commit, idempotent

The publisher is a few lines on top of java.net.http.HttpClient. This is the core of it (shortened from the app's CentrifugoRealtimePublisher):

public void publish(String userId, String table) {
    byte[] body = objectMapper.writeValueAsBytes(Map.of(
        "channel", "plan:#" + userId,
        "data", Map.of("table", table),
        "idempotency_key", UUID.randomUUID().toString()));
    HttpRequest request = HttpRequest.newBuilder(URI.create(publishUrl))
        .timeout(Duration.ofSeconds(3))
        .header("Content-Type", "application/json")
        .header("X-API-Key", apiKey)
        .header("X-Centrifugo-Error-Mode", "transport")
        .POST(HttpRequest.BodyPublishers.ofByteArray(body))
        .build();
    http.sendAsync(request, HttpResponse.BodyHandlers.discarding())
        .whenComplete((response, error) -> { /* warn at most once a minute */ });
}

Three details carry most of the weight:

  • sendAsync after the commit. The request thread that handled the push never waits on Centrifugo. If Centrifugo is down, pushes still succeed.
  • idempotency_key lets Centrifugo drop a duplicate publication when a request is retried. Centrifugo keeps those keys for 5 minutes, per channel. The docs also warn that a key it does not recognize is ignored without an error, so idempotencyKey in camelCase would silently do nothing.
  • X-Centrifugo-Error-Mode: transport. By default the HTTP API answers 200 with an error field in the body. With this header, errors come back as HTTP statuses, so checking statusCode() is enough.

Failures are logged at most once a minute. During a Centrifugo outage, every push would otherwise add a warning line.

On the device: recovery replaces most reconciles

The client is centrifuge-js. It reconnects with exponential backoff and jitter, refreshes its token through getToken, and, with channel history turned on, recovers the publications a device missed while it was away. That last part let me drop work. Before, every reconnect of the SSE stream triggered a reconcile: a check of all 8 tables, then a pull of the ones that changed, because the device could not know what it had missed. Now:

const subscription = client.newSubscription(`plan:#${sub}`);
subscription.on("publication", (ctx) => this.onHint(ctx.data));
subscription.on("subscribed", (ctx) => {
  this.live = true;
  // Recovered = every missed hint was replayed above: no reconcile needed.
  if (!ctx.recovered) this.onConnected?.();
});

The plan channel keeps 50 messages for 5 minutes (history and recovery). A device that was away longer, or is subscribing for the first time, gets recovered: false and reconciles as before.

For the rollout, the old SSE endpoint stayed for devices still running the previous build, then went away in a separate change. Old builds calling it now get a 404 instead of a 500.

Load testing Centrifugo: set GOMEMLIMIT, and read memory directly

The same kind of script, now with centrifuge-js clients subscribed to their own channels, measured Centrifugo in steps. It also timed a publish through the HTTP API until the device received it:

Memory grew linearly with the number of devices, at roughly 30–35 KB per device, against about 118 KB per SSE stream in the JVM. The signal took 8–11 ms at the median, with no errors, at every step. The first run also went wrong in two instructive ways.

Bar chart of memory per open connection: about 118 KB for an SSE stream in the JVM, about 34 KB for a Centrifugo connection.SSE streamin the JVM~118 KBCentrifugoconnection~34 KB
The same device costs roughly a quarter of the memory in a service built to hold connections.

Centrifugo was OOM-killed at its container limit on the way to the next step, and then every device reconnected at once, a reconnect storm that hit it again before it had settled. Go's garbage collector does not know about a container's memory limit unless you tell it. GOMEMLIMIT sets a soft limit, and the GC works harder as the heap approaches it instead of letting the kernel kill the process. I raised the container limit and set GOMEMLIMIT to about 90% of it. In the rerun, nothing was OOM-killed: the script's guard stopped the test itself as memory neared the limit.

The test's own guard was one scrape late. It read Centrifugo's memory from Prometheus, which scrapes every 15 seconds, and the process died between two reads. The script now reads process_resident_memory_bytes straight from Centrifugo's /metrics before each wave of 250 devices.

The proxy in front holds memory too

At that point the WebSocket connections still went through my reverse proxy (Caddy), which logs every request. After the test, Caddy kept 2.2 GB until it was restarted: every WebSocket it proxies holds buffers, and the memory did not come back right away when the connections closed. Removing the hop fixed it. The tunnel now sends the realtime hostname straight to Centrifugo, and the proxy got a memory limit and its own GOMEMLIMIT, since it is also a Go program.

The general lesson: when you count the cost of a connection, count every process it passes through. A connection that costs 34 KB in the service that holds it can cost more than that in a proxy you forgot was there.

What the move did not solve, and what it made worse

  • One shared point of failure. If Centrifugo is down, every app on it loses its instant signals at once. No data is lost: plan reconciles on its timer, and the chat and bidding apps reload when they reconnect. It has a healthcheck and a canary deploy like every app, and it can run several instances on its Redis engine.
  • Presence got slower for chat. The open-source Centrifugo has no hook for disconnects, so a phone that loses its signal shows as offline only after about 75 seconds, where Socket.IO showed it at once. Closing the page normally still reports right away.
  • History can be lost. If a channel's history is evicted or expires, devices fall back to a full reconcile.
  • Another moving part. For a single small app, SSE on the API with a per-user cap is simpler and good enough.

Summary

  • A held-open SseEmitter keeps a Tomcat processor and its buffers: about 118 KB of live heap per device in my measurement. At a 768 MB limit, the test had to stop near 3,000 devices.
  • Raising the API's memory only moves that limit linearly, and the heap is shared with request handling. Put long-lived connections in a service built for them.
  • With Centrifugo, the API publishes over HTTP (async, after commit, with an idempotency_key) and holds no connection. User-limited channels (#) remove the need for a permission check in the app.
  • centrifuge-js recovers missed publications from history. A device reconciles only when ctx.recovered is false.
  • Set GOMEMLIMIT below a Go service's container limit. A load-test guard should read memory directly, not from a scrape interval behind.
  • Count the proxy: Caddy held 2.2 GB of WebSocket buffers until restarted, so the realtime traffic no longer goes through it.

If you've moved long-lived connections out of a JVM service, or chosen a different server for them, I'd love to compare notes. My email is on the home page.