Design and Implementation of a Unified WebSocket Communication Service for Backend Systems
This article presents a comprehensive design of a unified WebSocket communication service that abstracts messaging, improves reliability with RabbitMQ, replaces polling with push, and provides standardized APIs and message formats for backend developers to quickly integrate real‑time features.
Background
The company’s existing backend services were tightly coupled with frontend web code, relying on polling and ad‑hoc WebSocket usage, which caused high latency and maintenance overhead. A unified WebSocket communication layer (ws) is needed to address several scenarios:
Polling for asynchronous results such as payment callbacks and order status.
Real‑time push features like QR‑code refresh and charging port status.
Transforming synchronous calls into asynchronous ones, pushing results via WebSocket to reduce interface latency.
Future business requirements that demand real‑time communication.
Goals
Standardize the project structure and coding style for WebSocket communication.
Separate business logic from communication code to improve integration efficiency.
Replace unreasonable polling with push notifications.
Enable asynchronous call patterns, delivering results through WebSocket to improve overall system responsiveness.
Use MQ instead of Redis pub/sub for inter‑service communication.
Core Design
Project Structure
Business Process
3.1 Application Relationship Diagram
Message Push (Fanout)
Message Receiving (Topic)
3.2 Business Sequence Diagram
From top to bottom:
WebSocket client registration and connection flow.
Push message to server flow.
Push message to client flow.
Ensuring Reliable Message Transmission
The design must prevent message loss, which can occur in three RabbitMQ scenarios:
Producer fails to deliver the message to the RabbitMQ server.
Server crashes before persisting the message.
Consumer crashes after receiving the message but before processing it, causing RabbitMQ to consider it acknowledged.
✔ Ensure producer‑side reliability (two methods)
Method 1: Enable transaction mode. If the message is not successfully received, the producer receives an exception and can roll back with channel.txRollback() and retry.
Method 2: Enable publisher confirms. RabbitMQ sends an ack when the message is persisted, otherwise a nack is returned, allowing the producer to retry.
Analysis: Transactions are synchronous and block the thread, while confirms are asynchronous and provide higher throughput; therefore confirms are generally preferred for reliable delivery.
✔ How the MQ server guarantees no loss
Enable message persistence so that messages are written to disk; after a server restart, persisted messages are recovered.
✔ Ensure consumer‑side reliability
Disable automatic acknowledgments and use manual consumer ack . The consumer acknowledges only after business logic succeeds; if it crashes before ack, RabbitMQ will re‑queue the message for another consumer.
Message Classification
5.1 Client → Server
Client actively pushes a message to the server, triggering a business process (e.g., QR‑code refresh request).
5.2 Server → Client
Server initiates an event and pushes the result to a client (e.g., payment completion callback).
5.3 Client → Client
One client pushes a message to another client (e.g., user‑initiated request that updates an H5 page).
WebSocket API Design
6.1 Request WebSocket Connection Token
Method: GET
Unified endpoint: domain/xxx/websocket/token
{
"result": 0,
"description": "无",
"data": "wss://dws.test.com:8086/socket/asrwqgvsd" // connection URL
}6.2 Connect to WebSocket Using Returned URL
Protocol: wss
Connection URL: wss://dws.test.com:8086/socket/{token}
Unified Message Body
{
"sendType":"",
"messageType":"消息类型",
"businessType":"",
"fromUniqueId":"发送端唯一id",
"toUniqueId":"接收端唯一id",
"fromClientType":"发送端类型",
"toClientType":"接收端类型",
"timestamp":0,
"content":"业务数据",
"tags":["标签集"],
"businesses":["业务集"]
}Unified Invocation Method
8.1 WebSocket API Aggregation Wrapper
8.2 Business Unified Call
Conclusion
The article documents a DDD‑inspired, unified WebSocket abstraction that decouples business code from communication logic, enabling “plug‑and‑play” real‑time messaging across services without worrying about low‑level WebSocket configuration.
Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.