In this lesson, you will learn how to architect a central notification hub that aggregates disparate event streams and intelligently routes them to users based on their specific interests.
The Aggregator Pattern
Rather than having every microservice maintain its own WebSocket connections, we build a dedicated Push Notification Hub. This hub acts as a mediator: it subscribes to various internal message buses (like Redis Streams) and broadcasts messages to the correct clients.
The challenge is preventing the hub from becoming a bottleneck. To solve this, we categorize incoming events into topics. When a client connects via a WebSocket, they don't just "connect"; they perform a handshake that registers their interest_profile (e.g., user:123, stock:AAPL, system:alerts).
Implementing the Hub
The hub maintains a Map where keys are topics and values are sets of WebSocket connections. When an event arrives from an internal service, the hub looks up the topic and pushes the payload only to the interested subscribers.
const subscribers = new Map(); // Map<Topic, Set<WebSocket>>
function subscribe(topic, socket) {
if (!subscribers.has(topic)) subscribers.set(topic, new Set());
subscribers.get(topic).add(socket);
}
// Routing an incoming event
function handleIncomingEvent(event) {
const { topic, payload } = event;
if (subscribers.has(topic)) {
subscribers.get(topic).forEach(socket => {
if (socket.readyState === WebSocket.OPEN) {
socket.send(JSON.stringify(payload));
}
});
}
}
Routing Efficiency
By decoupling the event producer from the WebSocket transport, you gain the flexibility to scale the hub independently. As you learned in our previous sessions on "Building a Protocol Agnostic Message Bus," this architecture allows your backend services to emit events without knowing anything about WebSockets. They simply dump data onto the bus, and the Hub translates those messages into real-time pushes.
To maintain high availability, ensure that your Hub instance listens to the same message stream across your Kubernetes cluster, ensuring that even if one Hub node fails, the event is still processed by the surviving members of your WebSocket cluster.
Key Takeaway: A Push Notification Hub acts as a decoupled router that maps incoming data topics to a specific set of active WebSocket connections, enabling efficient, interest-based message delivery.