Course contentsShow
← C#
Lesson 1479 of 1,90813. Real-time Communication with SignalRFree lesson

Implementing Pub-Sub over SignalR

Create a decoupled pub-sub message broker that leverages Hubs as the distribution layer.

In this lesson, you will learn how to transform a SignalR Hub into a decoupled message broker that enables reactive, event-driven communication across your distributed system.

The Concept: The Hub as a Broker

In a traditional client-server request/response model, the server waits for instructions. When implementing a Pub-Sub (Publisher-Subscriber) pattern over SignalR, we invert this: the Hub acts as a neutral "backplane" that simply routes messages. Producers (publishers) send messages to the Hub, and the Hub broadcasts them to any clients (subscribers) currently interested in that specific topic.

To keep this decoupled, we avoid embedding business logic inside the Hub methods. Instead, we use Groups as the logical "topics."

Implementation Sketch

When a client wants to subscribe to a specific event stream, they call a Join method. When a publisher sends an event, the Hub forwards it to the associated group members.

public class MessageBrokerHub : Hub
{
    // Subscriber: Listen to a specific topic
    public async Task Subscribe(string topic)
    {
        await Groups.AddToGroupAsync(Context.ConnectionId, topic);
    }

    // Publisher: Broadcast data to all subscribers of a topic
    public async Task Publish(string topic, object message)
    {
        // Broadcast to all clients subscribed to this group
        await Clients.Group(topic).SendAsync("ReceiveMessage", topic, message);
    }
}

Why Decoupling Matters

By utilizing Groups, you decouple the sender from the receiver. The publisher does not need to know which clients are active, how many there are, or their internal state. It only needs to know the "topic" name.

Because we are using Groups, SignalR handles the complexity of connection management and message routing for you. If a client disconnects, SignalR automatically removes them from the group, ensuring that we aren't wasting resources trying to push updates to stale connections. This pattern effectively creates a lightweight, real-time message bus that integrates seamlessly with your existing infrastructure.

Key Takeaway: By leveraging Hub Groups as logical message channels, you can transform SignalR into a decoupled Pub-Sub engine where producers only need to know the topic, not the specific subscribers.