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

SignalR within Microservice Architectures

Use an event bus to bridge backend microservice events to SignalR frontend broadcasts.

In this lesson, you will learn how to decouple your SignalR hub from internal microservice business logic by utilizing an event bus to bridge backend domain events to frontend clients.

Decoupling Hubs from Business Logic

In a robust microservice architecture, your SignalR hub should be a "dumb" delivery pipe. It should not contain the logic for processing orders or updating inventory. Instead, you should keep your Hubs thin and let your microservices communicate asynchronously via an event bus (such as RabbitMQ, Azure Service Bus, or MassTransit).

When a backend service completes a task, it publishes an event to the bus. A dedicated "Notification Service" then consumes this event and triggers the appropriate SignalR IHubContext.

Implementing the Bridge

Instead of a service calling a Hub directly (which causes tight coupling), the Notification Service listens for integration events. Here is how you bridge that gap:

public class OrderProcessedConsumer : IConsumer<OrderProcessedEvent>
{
    private readonly IHubContext<NotificationHub> _hubContext;

    public OrderProcessedConsumer(IHubContext<NotificationHub> hubContext)
    {
        _hubContext = hubContext;
    }

    public async Task Consume(ConsumeContext<OrderProcessedEvent> context)
    {
        // Broadcast the event to the user's specific group
        await _hubContext.Clients.Group(context.Message.UserId)
            .SendAsync("ReceiveOrderUpdate", context.Message.Status);
    }
}

Why this architecture matters

  1. Isolation: If your SignalR instance fails or needs to be scaled out, your core business microservices remain unaffected.
  2. Scalability: By using an event bus, you can have multiple instances of the Notification Service handling the load, and they will work seamlessly with your SignalR backplane (like Redis) to ensure messages reach the correct connected client regardless of which server holds the connection.
  3. Resilience: If the SignalR service is temporarily down, the event bus ensures the message is queued and processed once the service recovers, preventing the loss of real-time updates.

By treating the SignalR hub as an event consumer rather than a direct service dependency, you ensure your architecture remains modular and maintainable as your system grows.

Key Takeaway: Never trigger SignalR Hub methods directly from your business logic services; instead, emit domain events to a bus and let a specialized consumer invoke the Hub context.