Video in progress
A user was removed from a group chat, but messages from that group keep arriving in their open tab. How do you cancel an active subscription?
Subscription permission is checked only at SUBSCRIBE time; after that the broker delivers messages without asking. Reliable solutions: when membership changes, close the user's sessions and force a resubscribe, or build the room not as a shared topic but with per-user delivery where membership is checked at publish time.
📖 Answer
This is a security bug, and it exists in many projects. The room is /topic/room.42, isMember was checked at subscribe time, and everything is correct. Then an admin removes the user. The broker knows nothing about membership; all it has is a record "session X is subscribed to /topic/room.42".
I go through the options from simple to complex.
1. Close the sessions. When membership changes, a MembershipRevoked(userId, roomId) event is emitted (with many instances, to all of them through pub/sub). Each instance finds that user's local sessions and closes them with a custom code:
@EventListener
void onRevoked(MembershipRevoked e) {
SimpUser user = userRegistry.getUser(e.userId());
if (user == null) return;
user.getSessions().forEach(s ->
sessions.close(s.getId(), new CloseStatus(4403, "membership changed")));
}
Here sessions is the list of raw sessions collected through a WebSocketHandlerDecoratorFactory. The client reconnects, resubscribes to everything, and now room.42 is denied. Simple and reliable, but the user's other rooms are briefly disconnected too.
2. Per-user delivery. The room message goes not through /topic but, based on the member list, to each one through /user/queue/rooms. Membership is checked at publish time, so the removed person doesn't get the next message. The cost is that fan-out happens on the server, which is expensive for large groups.
- Outbound filter. An interceptor on
clientOutboundChannelchecks membership (from a cache) for eachMESSAGEand drops it by returningnullif it doesn't match. It works, but it's a check on every outgoing message, so cache invalidation has to be right.
I usually pick option 2 for small groups and option 1 for large channels. Whichever you choose, write down the acceptable delay: "a removed user stops receiving messages within 2 seconds at most", and verify it with an automated test.
Don't forget: you can't take back messages the client has already received. The real-time layer only stops the future stream.
Sign up to mark studied questions and save your progress.