Video in progress

The server computes and sends a price every second for every quote topic, even if nobody is subscribed to it. How do you do work only for topics that have subscribers?

You have to track subscriptions: either query SimpUserRegistry.findSubscriptions(), or listen to SessionSubscribeEvent/SessionUnsubscribeEvent and SessionDisconnectEvent and keep a counter per destination. When the counter drops to zero, the producer stops.

📖 Answer

convertAndSend doesn't tell you there are no subscribers; the message just goes to nobody. If there are 5000 instruments and users are watching 200, 96 percent of your CPU and external API quota goes to waste.

The first option is to ask the registry:

Set<SimpSubscription> subs = userRegistry.findSubscriptions(
        s -> s.getDestination().startsWith("/topic/quotes."));
Set<String> active = subs.stream()
        .map(s -> s.getDestination().substring("/topic/quotes.".length()))
        .collect(Collectors.toSet());

One catch: SimpUserRegistry only knows sessions that have a Principal. Subscriptions from anonymous clients aren't visible here, which is a time-consuming trap.

The second option is to count yourself with events:

@EventListener
void onSubscribe(SessionSubscribeEvent e) {
    var acc = SimpMessageHeaderAccessor.wrap(e.getMessage());
    subs.add(acc.getSessionId(), acc.getSubscriptionId(), acc.getDestination());
}

@EventListener
void onUnsubscribe(SessionUnsubscribeEvent e) {
    var acc = SimpMessageHeaderAccessor.wrap(e.getMessage());
    subs.remove(acc.getSessionId(), acc.getSubscriptionId());
}

@EventListener
void onDisconnect(SessionDisconnectEvent e) {
    subs.removeSession(e.getSessionId());  // connections that dropped without UNSUBSCRIBE
}

An UNSUBSCRIBE frame has no destination, only a subscription id, so you keep a sessionId + subscriptionId -> destination map. If you forget disconnect, the counter never reaches zero.

With many instances, each instance knows only its own local subscriptions. If the producer is central, the instances write a list of "these topics are active on me" to Redis with a TTL. One more small thing: after the last subscriber leaves I don't stop the work immediately but wait 30 seconds, so the expensive producer doesn't restart over and over when a user refreshes the page.