Handling websocket connections connected to different replicas Handling websocket connections connected to different replicas kubernetes kubernetes

Handling websocket connections connected to different replicas


To keep track of who is connected and who closed all tabs, you need to have one DB-like instance. All you need to do is to publish an event to that instance when someone connects or disconnects.

A simple implementation would to have a dictionary with a user identifier as key and number of session as a value.

When a user connects to a websocket, you publish a connected event that increments the number of sessions.

When a user disconnects, you publish a disconnected event that decrements the number of sessions and return the remaining number of session or just a boolean if the number is equal to 0. Then you can do whatever you need to do to clean up his session.

Note: you need to make the write operation synchronous if you will have multiple threads receiving the events. A good solution is to use a SQL database which support ACID out of the box.

If you need to more control, you can extend the solution to have a publish subscribe architecture. Where the connection is bidirectional rather than the unidirectional method above. This way, if someone connects in another tab, you can interact with the first tab and show a message or disconnect based on your needs.