Video in progress

How is the STOMP heartbeat negotiated, and why is it set separately for each direction?

The CONNECT and CONNECTED frames carry a heart-beat: cx,cy header: the first number is how often I can send, the second is how often I want to hear from you. For each direction the larger of the two sides' values is used, and 0 means "off".

📖 Answer

For example, if the client says heart-beat:10000,10000 and the server says heart-beat:25000,25000: in the client → server direction a heartbeat goes once every 25 seconds, and server → client also once every 25 seconds. A heartbeat is a single newline (\n), very cheap.

The two directions are separate because the sides' needs differ. A mobile client may want to send rarely to save battery, while the server wants to hear from the client often to find dead connections fast.

With Spring's simple broker you need a scheduler to turn heartbeats on; it doesn't work without one:

@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
    ThreadPoolTaskScheduler ts = new ThreadPoolTaskScheduler();
    ts.setPoolSize(1);
    ts.setThreadNamePrefix("ws-heartbeat-");
    ts.initialize();

    registry.enableSimpleBroker("/topic", "/queue")
            .setHeartbeatValue(new long[]{20_000, 20_000})
            .setTaskScheduler(ts);
}

If nothing arrives within the expected interval (usually with a bit of slack), the side closes the connection as dead.

Pick a value smaller than the proxy idle timeout: if Nginx is 60s, 20 to 25s is good. There's no need to make the heartbeat 1 or 2 seconds: with 100k clients that is noticeable traffic and CPU.