Implementing WebSocket in Projects - Cluster Scenarios
Recently, WebSocket was implemented in our site, and immediately we faced communication issues in Web service clusters. In a multi-instance Web service environment, if user A subscribes to a WS channel on server A, but server B initiates a broadcast in the background, user A won’t receive the message. So the question is: how to handle broadcasts and send accurate messages to individual users in a cluster scenario?
Tech Stack
First, let me introduce our current project’s tech stack:
- React
v16.4.2
- SpringBoot
v2.1.6.RELEASE
Solution
Use Redis to share user information and implement message subscription broadcasts.
How to write the specific code? Without further ado, click here
General Process
- When a user connects to WS, Redis stores the user information. All cluster instances are connected to Redis, so theoretically they can all access all user information.
- If you want to send a point-to-point message, initiate a Redis broadcast. All instance Redis services will receive the message, find the target UID, and send the message if matched.
- If you want to broadcast, initiate a Redis broadcast. All instance Redis services will receive the message and subsequently send it, so all users will receive it.
Is it necessary to add Kafka or MQ?
Many WebSocket cluster solutions found online mention adding a message queue. Currently, I don’t use it in the project. I personally think Redis is sufficient if the message volume is not large.
Conclusion
If you think about it, without a cluster, this problem wouldn’t exist.
So why do we need a cluster? Clustering physically increases the service instances to provide services to more clients. The service content is the same, but it also brings problems, like the one mentioned at the beginning of the article. To face such problems, Redis, as a NoSQL storage service, can be exposed to multiple clients to solve the issue.
This is the general idea, and I hope it can inspire some thoughts.