Real-time Updates in Liferay Without WebSockets: Building a Subscribe API on Server-Sent Events
Sooner or later, every portal project needs to push something to the browser: a background job finished, a record changed, a colleague sent a message. WebSockets are the usual answer, but they're an awkward fit for Liferay. A WebSocket endpoint sits outside the JAX-RS stack, so the portal's auth verifiers don't apply and you write your own authentication. Proxies and load balancers need upgrade handling. And on a cluster, you're still on your own for getting a message from the node that produced it to the node holding the socket.
There's a simpler option that Liferay 7.4 already supports: Server-Sent Events (SSE). This post walks through building a small publish/subscribe API on SSE. It's a JAX-RS module plus a React client extension: open the same channel in two browsers as two different users, send from one, and the other receives it.
Where the idea came from: AI Hub
Liferay's AI Hub delivers agent results to the browser this way. Its client code shows the contract clearly:
- The browser opens GET /o/ai-hub/v1.0/chats/subscribe with Accept: text/event-stream and keeps the response open.
- The first event on that stream carries an sseEventSinkKey.
- The browser starts the actual work with a separate POST, passing that key. The POST returns almost immediately.
- Results arrive later as events on the stream from step 1, interleaved with ": heartbeat" comment lines that keep the connection alive.
The name sseEventSinkKey is a strong hint about the server side: javax.ws.rs.sse.SseEventSink is the JAX-RS 2.1 type for an open SSE connection. The server keeps open sinks in a map, under a generated key.
So the question became: can an ordinary custom module on Liferay 7.4 do the same thing?
Does Liferay 7.4 support it?
Three things have to be true for SSE to work in a JAX-RS whiteboard module. All three hold on 7.4 GA132, and each one comes down to how a request travels through the portal:
- The SSE implementation is deployed. The portal ships org.apache.cxf.cxf-rt-rs-sse, and the Aries JAX-RS Whiteboard registers CXF's SSE context providers for every application. That means @Context Sse and @Context SseEventSink simply work. GA132 is still on javax.*; newer DXP quarterly releases have moved to jakarta.*.
- Requests under /o/* can go async. An SSE stream holds the response open, which needs Servlet 3 async support. The Module Framework Servlet that serves /o/*, and the portal's invoker filters, are all declared async-supported. CXF suspends the request with no timeout, so Tomcat's default 30-second async timeout doesn't cut the stream off.
- Nothing buffers the response. The portal's GZip filter isn't mapped to /o/* REST paths, so events reach the browser as they're written.
The design
The API has three calls:
| Call | Purpose |
|---|---|
| GET /o/subscribe/v1.0/channels/{uuid}/subscribe | Opens the stream. First event is subscribed, with the key. |
| POST /o/subscribe/v1.0/channels/{uuid}/messages | Sends {text} to every stream on the channel. |
| DELETE /o/subscribe/v1.0/subscriptions/{key} | Closes a stream early (optional). |
A channel is just a UUID. Nothing is stored; a channel exists for as long as something is subscribed to it.
The server
The application
@Component(
property = {
"osgi.jaxrs.application.base=/subscribe",
"osgi.jaxrs.name=Subscribe.API",
"auth.verifier.guest.allowed=false",
"liferay.access.control.disable=true", "liferay.oauth2=false"
},
service = Application.class
)
public class SubscribeApplication extends Application {
public Set<Object> getSingletons() {
return Collections.<Object>singleton(this);
}
...
}auth.verifier.guest.allowed=false keeps guests out, and every request runs through the same auth verifiers as any other /o/ endpoint. There's no separate authentication layer to write.
Don't skip getSingletons(). In the OSGi JAX-RS whiteboard, an Application is not a resource by default. Without it, the application registers fine, the component shows as active, and every path returns 404. That cost me a debugging session, so it gets its own line here.
The subscribe endpoint
@GET
@Path("/v1.0/channels/{channelId}/subscribe")
@Produces(MediaType.SERVER_SENT_EVENTS)
public void subscribe(
@PathParam("channelId") String channelId,
@Context HttpServletResponse httpServletResponse, @Context Sse sse,
@Context SseEventSink sseEventSink) {
// Ask proxies (nginx in particular) not to buffer the stream
httpServletResponse.setHeader("Cache-Control", "no-cache");
httpServletResponse.setHeader("X-Accel-Buffering", "no");
User user = _getUser();
Subscription subscription = _subscriptionRegistry.subscribe(
channelId, user.getUserId(), user.getFullName(), sse, sseEventSink);
_subscriptionRegistry.send(
subscription, "subscribed",
JSONUtil.put(
"channelId", channelId
).put(
"sseEventSinkKey", subscription.getKey()
).toString());
}The method returns void and the request doesn't end. CXF keeps the connection open, and anything written to the sink later goes straight to the browser.
One subtlety: by the time this method runs, the response is already committed as text/event-stream. You can't answer a bad request with a 400 anymore. In my implementation, validation failures go out as an error event with a JSON body, and the stream is closed straight after.
The registry
The registry is a plain OSGi component holding two concurrent maps: subscriptions by key, and keys by channel. Three things in it matter.
Sending, and noticing dead connections. SseEventSink.send() returns a CompletionStage. When the browser has gone away, the write fails, and the failure handler removes the subscription:
sseEventSink.send(
outboundSseEvent
).whenComplete(
(result, throwable) -> {
if (throwable != null) {
_remove(subscription);
}
}
);Heartbeats. A single scheduled thread writes a comment to every stream every 15 seconds:
_send(subscription, sse.newEventBuilder().comment("heartbeat").build());That does two jobs. It keeps proxies and load balancers from closing an idle connection, and it guarantees a dead connection is found within 15 seconds, because the heartbeat write fails. Wrap the heartbeat body in a try/catch: an exception that escapes a scheduleWithFixedDelay task silently cancels every future run.
Clustering. Each open stream lives in the memory of the node that accepted it - the stateful part of an otherwise stateless system. A publish therefore delivers to local streams first, then multicasts to the other nodes with Liferay's ClusterExecutor:
ClusterRequest clusterRequest = ClusterRequest.createMulticastRequest(
new MethodHandler(
_receiveClusterEventMethodKey, channelId, eventName, data),
true);
clusterRequest.setFireAndForget(true);
_clusterExecutor.execute(clusterRequest);The true passed to createMulticastRequest is skipLocal, so the publishing node doesn't deliver twice. On every other node, a static receiveClusterEvent method writes to that node's local streams. With clustering disabled, _clusterExecutor.isEnabled() is false and the multicast is skipped.
The client
The playground is a custom-element client extension (React 18, bundled with Vite). Its key design choice is to read the stream with fetch(), not EventSource.
EventSource can't set request headers. A session-authenticated call to /o/* needs the x-csrf-token header, so EventSource is out:
const response = await fetch(`/o/subscribe/v1.0/channels/${channelId}/subscribe`, {
credentials: 'include',
headers: {
'accept': 'text/event-stream',
'x-csrf-token': Liferay.authToken,
},
signal: controller.signal,
});
const reader = response.body.getReader();That also means doing by hand what EventSource would do for free:
- Parsing. Split on newlines; event: sets the name, data: lines accumulate, a blank line dispatches the event, and lines starting with a colon are comments (the heartbeats).
- Reconnecting. When the stream ends or errors, reconnect with exponential backoff (1s, 2s, 4s, … capped at 15s). Statuses a retry can't fix (400, 401, 403, 404) stop the loop instead.
- A watchdog. If nothing arrives for 45 seconds (three missed heartbeats), abort and reconnect. A connection can die without the socket noticing, especially behind NAT or a proxy.
When the page is closed, a DELETE with keepalive: true tells the server to close the stream right away rather than waiting for the next failed heartbeat.
Gotchas, collected
- 404 with an active component: add getSingletons() to the Application.
- 403 when you open the URL in the address bar: that request has no CSRF header, so the portal treats it as a guest. Test from the client extension, or with curl and Basic auth.
- Errors after the stream opens can't use HTTP status codes. Send them as an error event.
- Proxy buffering: send X-Accel-Buffering: no for nginx, check your other proxies, and make sure their idle timeouts are longer than the heartbeat interval.
- The browser connection limit: over HTTP/1.1, browsers allow about six open connections per host, shared across all tabs, and each subscribed tab uses one. Serve over HTTP/2 (where this stops being a practical limit), or carry several channels on a single stream per tab.
SSE or WebSockets?
SSE is one-way: server to browser. The browser-to-server direction is an ordinary POST. For notifications, progress updates, and chat-style traffic, that's no real loss, and you get a lot in return:
- It's plain HTTP, so auth verifiers, proxies, and load balancers treat it like any other request.
- An open stream holds a socket, not a Tomcat thread.
- Cluster fan-out is a few lines on top of ClusterExecutor.
If you need high-frequency, two-way, binary traffic (games, collaborative cursors), WebSockets are still the right tool. For "tell the browser when something happened", SSE is simpler and fits the portal better.
Before production
This is a proof of concept. Before relying on it, add:
- Channel authorization. Right now any signed-in user can subscribe to or publish on any UUID. Map channels to the entities they belong to and check permissions on both calls.
- Replay. Give events IDs and honour Last-Event-ID on reconnect, so messages sent during a reconnect aren't lost.
- Limits. Cap streams per user and rate-limit publishing.
None of that changes the core idea: a JAX-RS method that returns void, an SseEventSink kept in a map, and a heartbeat. That's enough for real-time updates in Liferay, without a WebSocket.