Java › Standard

Jakarta WebSocket endpoints and Spring STOMP routing

Trace the HTTP upgrade and compare Jakarta WebSocket with Spring STOMP, including proxy timeouts, multi-instance routing, and concurrent sends.

Jakarta WebSocket endpoints and Spring STOMP routing

A raw WebSocket connection carries frames. A STOMP application adds destinations and subscriptions. I use the same chat example to see where those responsibilities sit and what fails when clients connect through a proxy or to different replicas.

The examples use Java 21, Jakarta WebSocket 2.1, and Spring Boot 3.4.

How the HTTP connection upgrades

With HTTP/1.1, the client sends the WebSocket upgrade headers and a handshake key. The server accepts with HTTP 101 and a computed Sec-WebSocket-Accept value. The upgraded connection can then carry frames in either direction. Application routes and topics belong to a protocol above those frames.

sequenceDiagram
    participant Client as "Client (Browser/App)"
    participant Container as "Servlet Container (Tomcat)"
    participant Endpoint as "@ServerEndpoint Instance"

    Client->>Container: "GET /ws/chat/room-1 (Upgrade: websocket)"
    Container->>Container: "Sec-WebSocket-Key validation and upgrade"
    Container-->>Client: "HTTP/1.1 101 Switching Protocols"
    Container->>Endpoint: "@OnOpen(Session)"
    Client->>Endpoint: "WebSocket Text Frame (Send message)"
    Endpoint-->>Client: "WebSocket Text Frame (Broadcast)"
    Client->>Endpoint: "Close Frame (Close connection)"
    Container->>Endpoint: "@OnClose(Session, CloseReason)"

The handshake is also where an application can reject an unsupported origin or protocol. Once the connection is open, authorize sensitive messages or subscriptions as well as the connection itself.

Implementing a Jakarta WebSocket endpoint

JSR 356 originated the Java WebSocket API now maintained under Jakarta. @ServerEndpoint declares a route. The runtime fires @OnOpen, @OnMessage, @OnClose, and @OnError callbacks and supplies a Session to send or receive messages.

1
2
3
4
// build.gradle.kts
dependencies {
    implementation("org.springframework.boot:spring-boot-starter-websocket")
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// src/main/java/com/example/ws/ChatServerEndpoint.java
package com.example.ws;

import jakarta.websocket.CloseReason;
import jakarta.websocket.OnClose;
import jakarta.websocket.OnError;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
@ServerEndpoint("/ws/chat/{roomId}")
public class ChatServerEndpoint {

    private static final Logger log = LoggerFactory.getLogger(ChatServerEndpoint.class);
    private static final ConcurrentHashMap<String, Set<Session>> ROOMS = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("roomId") String roomId) {
        ROOMS.computeIfAbsent(roomId, key -> ConcurrentHashMap.newKeySet()).add(session);
        log.info("Connected: roomId={}, sessionId={}", roomId, session.getId());
    }

    @OnMessage
    public void onMessage(String message, Session sender, @PathParam("roomId") String roomId) {
        for (Session target : ROOMS.getOrDefault(roomId, Set.of())) {
            if (target.isOpen()) {
                target.getAsyncRemote().sendText(message);
            }
        }
    }

    @OnClose
    public void onClose(Session session, @PathParam("roomId") String roomId, CloseReason reason) {
        Set<Session> sessions = ROOMS.get(roomId);
        if (sessions != null) {
            sessions.remove(session);
        }
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        log.error("WebSocket error: sessionId={}", session.getId(), throwable);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// src/main/java/com/example/ws/StandardWebSocketConfig.java
package com.example.ws;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Configuration
public class StandardWebSocketConfig {

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

The Boot example registers the endpoint through ServerEndpointExporter for the embedded container. A standalone container can discover endpoint declarations itself. Confirm how the runtime instantiates the endpoint before assuming that regular Spring-managed injection and lifecycle rules apply.

Adding destinations with Spring STOMP

ConcernJakarta endpointSpring WebSocket handlerSpring STOMP
Programming modelSession and framesSpring-managed raw handlerMessage destinations and subscriptions
RoutingApplication codeApplication codeConfigured /app, /topic, and /queue prefixes
Typical useA binary or application-specific protocolLightweight push with Spring integrationChat, collaboration, and topic-based notifications
flowchart TD
    Client["WebSocket + STOMP Client"] -->|"SEND /app/chat"| Inbound["clientInboundChannel"]
    Inbound -->|"Match destination"| Controller["@MessageMapping Controller"]
    Controller -->|"SimpMessagingTemplate"| BrokerChannel["brokerChannel"]
    Inbound -->|"SUBSCRIBE /topic/room.1"| Broker["SimpleBroker / StompBrokerRelay"]
    BrokerChannel --> Broker
    Broker -->|"MESSAGE frame"| Outbound["clientOutboundChannel"]
    Outbound -->|"Push"| Client

Spring’s STOMP setup registers the connection endpoint and application and broker prefixes. The controller handles the application destination. The broker infrastructure publishes the result to subscribers.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// src/main/java/com/example/ws/StompWebSocketConfig.java
package com.example.ws;

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

@Configuration
@EnableWebSocketMessageBroker
public class StompWebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/ws-stomp")
                .setAllowedOriginPatterns("https://app.example.com");
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.setApplicationDestinationPrefixes("/app");
        registry.enableSimpleBroker("/topic", "/queue");
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// src/main/java/com/example/ws/ChatStompController.java
package com.example.ws;

import org.springframework.messaging.handler.annotation.DestinationVariable;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;

@Controller
public class ChatStompController {

    public record ChatMessage(String sender, String content) {}

    @MessageMapping("/chat/{roomId}")
    @SendTo("/topic/chat.{roomId}")
    public ChatMessage broadcast(@DestinationVariable String roomId, ChatMessage message) {
        return message;
    }
}

Shipping across proxies and replicas

An in-memory endpoint registry or Spring’s simple broker sees connections in its process. Sticky sessions can keep one client on its current instance, but a subscriber on another replica still needs a shared delivery mechanism. For cross-instance delivery, evaluate an external broker relay and test what happens during a reconnect.

The reverse proxy needs to forward the upgrade headers. Coordinate its read timeout with the heartbeat interval so idle connections live as long as expected. The Nginx example illustrates the headers and timeout together.

1
2
3
4
5
6
7
8
9
location /ws-stomp {
    proxy_pass http://backend_upstream;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_set_header Host $host;
    proxy_read_timeout 3600s;
    proxy_send_timeout 3600s;
}

Concurrent writes to one session may overlap while the first frame is still being sent.

1
java.lang.IllegalStateException: The remote endpoint was in state [TEXT_FULL_WRITING] which is an invalid state for called method

Serialize writes per session or use an appropriate asynchronous queue. For raw Spring sessions, ConcurrentWebSocketSessionDecorator can coordinate sends and limit buffering. Keep the overflow policy explicit so one slow consumer cannot accumulate messages indefinitely.

Checking the deployed path

Open a connection through the real proxy, leave it idle, and verify the heartbeat and timeout behavior. Connect two clients to different replicas and send a message to their shared destination. Then slow one consumer and confirm that the send path respects the configured limits. These checks distinguish a handshake error from a routing or buffering problem.

References

The WebSocket protocol defines two types of messages (text and binary), but their content is undefined. The protocol defines a mechanism for client and server to negotiate a sub-protocol (that is, a higher-level messaging protocol) to use on top of WebSocket to define what kind of messages each can send, what the format is, the content of each message, and so on. The use of a sub-protocol is optional but, either way, the client and the server need to agree on some protocol that defines message content.
This post is licensed under CC BY 4.0 by the author.