Building Microservices Using RabbitMQ :👈 👉:gRPC

ASP.NET Core SignalR: Real-Time Applications and Scalable Backplanes

ASP.NET Core SignalR: Real-Time Applications and Scalable Backplanes

ASP.NET Core SignalR is a framework used to build real-time web applications where the server can send data to connected clients instantly, without requiring clients to continuously refresh the page or repeatedly request updates.

It is useful for:

  • Chat applications.
  • Live notifications.
  • Real-time dashboards.
  • Stock market updates.
  • Online gaming.
  • Live tracking applications.
  • Collaborative applications.
  • Order and payment status updates.

1. What is ASP.NET Core SignalR?

Normally, HTTP communication follows a request-response model.

  1. The client sends a request to the server.
  2. The server processes the request.
  3. The server sends a response.
  4. The communication is completed.

If the server has new information later, the client must make another request to receive it.

SignalR makes communication more interactive by allowing the server to send messages to clients whenever new information becomes available.

Example: In a chat application, User A sends a message. The server receives the message and immediately sends it to User B using SignalR. User B sees the message without refreshing the page.

Key point: SignalR provides real-time, two-way communication between clients and servers.

2. Traditional HTTP vs SignalR

Traditional HTTP Communication

Client                 Server
  |                       |
  |------ Request ------->|
  |                       |
  |<------ Response ------|
  |                       |
  |    Request completed  |
  |                       |
  |------ New Request ---->|

SignalR Communication

Client                 Server
  |                       |
  |<=====================>|
  |                       |
  |   Persistent          |
  |   Connection          |
  |                       |
  |<------ Message -------|
  |                       |
  |------- Message ------>|
  |                       |
  |<------ Message -------|

SignalR allows both client and server to communicate over an established connection.

3. What is a SignalR Hub?

A Hub is the main communication component in ASP.NET Core SignalR.

It acts as a central communication point between clients and the server. The client calls methods on the Hub, and the Hub can call methods on connected clients.

SignalR Hub Architecture

SignalR Hub Architecture Three clients communicate with a central SignalR Hub. SignalR Hub ChatHub.cs Client A Client B Client C Browser / App Browser / App Browser / App One Hub manages communication with connected clients

Example: Creating a SignalR Hub

using Microsoft.AspNetCore.SignalR;
public class ChatHub : Hub
{
    public async Task SendMessage(string user, string message)
    {
        await Clients.All.SendAsync(
            "ReceiveMessage",
            user,
            message
        );
    }
}

Explanation

  • ChatHub inherits from Hub.
  • SendMessage() is a method clients can invoke.
  • Clients.All represents all clients connected to this Hub.
  • SendAsync() sends an event to the clients.
  • ReceiveMessage is the client-side event name.
  • user and message are the values sent to clients.

4. How SignalR Works Internally

The communication process generally follows these steps:

  1. A client establishes a connection with the SignalR server.
  2. SignalR negotiates the connection and available transport.
  3. A suitable transport is selected.
  4. The client and server exchange messages.
  5. The server can send messages whenever required.
  6. When the client disconnects, SignalR handles the disconnection.
1. Client connects 2. Negotiate connection 3. Select transport 4. Persistent communication Client <--> Server 5. Disconnect

5. SignalR Transports

A transport is the underlying communication mechanism used between the client and server.

ASP.NET Core SignalR supports three transports.

5.1 WebSockets

WebSockets provides full-duplex communication over a single connection.

Full-duplex means both client and server can send messages independently.

  • Low communication overhead.
  • Fast message delivery.
  • Two-way communication.
  • Suitable for high-frequency updates.

5.2 Server-Sent Events (SSE)

Server-Sent Events allows the server to send continuous updates to the client over an HTTP connection. Communication is primarily one-way, from server to client. The client uses HTTP requests to send information to the server.

5.3 Long Polling

Long Polling works by making an HTTP request and keeping it open until the server has information to return or a timeout occurs. After receiving a response, the client immediately makes another request.

Client                  Server
  |                        |
  |------ Request -------->|
  |                        |
  |       Wait...          |
  |                        |
  |<----- Response --------|
  |                        |
  |------ New Request ----->|
  |                        |
  |       Wait...          |

5.4 Transport Comparison

Feature WebSockets SSE Long Polling
CommunicationTwo-wayPrimarily server to clientRequest-response
Persistent connectionYesYesRepeated requests
PerformanceGenerally bestGood for server updatesHigher overhead
Client-to-server messagesYesSeparate HTTP requestsYes
Typical usageChat, live trackingLive feedsFallback compatibility

SignalR automatically negotiates and selects a supported transport. WebSockets is generally preferred.

6. SignalR Architecture in ASP.NET Core

A typical SignalR application contains the following components:

  1. Client application – browser, mobile application or desktop application.
  2. SignalR connection – communication channel between client and server.
  3. Hub – handles client-to-server and server-to-client communication.
  4. Business service – performs business operations.
  5. Database – stores permanent application information.
Client Applications Web / Mobile / Desktop SignalR Connection WebSockets / SSE / Long Polling SignalR Hub ChatHub / NotificationHub Business Services Orders / Payments / Notifications Database SQL Server / PostgreSQL Authentication JWT / Identity Authorization Monitoring Logging / Tracing Application data is stored in the database.

7. Creating a SignalR Application Step by Step

Step 1: Create an ASP.NET Core Web API Project

dotnet new webapi -n SignalRDemo
cd SignalRDemo

Step 2: Install SignalR Client Libraries

For the ASP.NET Core server, SignalR is included in the ASP.NET Core shared framework.

For a JavaScript client:

npm install @microsoft/signalr

For a .NET client:

dotnet add package Microsoft.AspNetCore.SignalR.Client

Step 3: Create a Hub

Create a folder named Hubs and create ChatHub.cs.

using Microsoft.AspNetCore.SignalR;
namespace SignalRDemo.Hubs
{
    public class ChatHub : Hub
    {
        public async Task SendMessage(
            string user,
            string message)
        {
            await Clients.All.SendAsync(
                "ReceiveMessage",
                user,
                message
            );
        }
    }
}

Step 4: Register SignalR in Program.cs

using SignalRDemo.Hubs;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddSignalR();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.MapHub<ChatHub>("/chatHub");
app.Run();

AddSignalR() registers SignalR services in dependency injection.

MapHub<ChatHub>("/chatHub") maps the Hub to an HTTP endpoint.

Step 5: Create the JavaScript Client

Create an HTML page named index.html.

<!DOCTYPE html>
<html>
<head>
    <title>SignalR Chat</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/8.0.7/signalr.min.js"></script>
</head>
<body>
    <h2>SignalR Chat Application</h2>
    <input type="text" id="user"
           placeholder="Enter username">
    <input type="text" id="message"
           placeholder="Enter message">
    <button onclick="sendMessage()">
        Send Message
    </button>
    <ul id="messagesList"></ul>
    <script>
        const connection = new signalR.HubConnectionBuilder()
            .withUrl("/chatHub")
            .withAutomaticReconnect()
            .build();
        connection.on("ReceiveMessage", (user, message) => {
            const li = document.createElement("li");
            li.textContent = `${user}: ${message}`;
            document.getElementById("messagesList")
                .appendChild(li);
        });
        async function startConnection() {
            try {
                await connection.start();
                console.log("SignalR Connected");
            }
            catch (err) {
                console.error(err);
            }
        }
        async function sendMessage() {
            const user = document.getElementById("user").value;
            const message = document.getElementById("message").value;
            await connection.invoke(
                "SendMessage",
                user,
                message
            );
        }
        startConnection();
    </script>
</body>
</html>

Important: Serve this page from the ASP.NET Core application or configure CORS and the correct Hub URL when hosted separately.

Step 6: Test the Application

  1. Run your ASP.NET Core application.
  2. Open the chat page in two browser windows.
  3. Enter different usernames.
  4. Send a message from the first window.
  5. Observe the message appearing in both windows.

8. Important SignalR Client Methods

8.1 Invoke()

Calls a Hub method and waits for its completion and any return value.

await connection.invoke(
    "SendMessage",
    "User1",
    "Hello"
);

8.2 Send()

Sends a Hub method invocation without waiting for a result from the method.

await connection.send(
    "SendMessage",
    "User1",
    "Hello"
);

8.3 On()

Registers a handler for a server-to-client event.

connection.on("ReceiveMessage", (user, message) => {
    console.log(user);
    console.log(message);
});
Method Direction Purpose
invoke()Client to ServerInvoke Hub method and await completion/result
send()Client to ServerSend invocation without awaiting its result
on()Server to ClientReceive server events

9. SignalR Clients API

9.1 Clients.All

Sends messages to all clients connected to the Hub.

await Clients.All.SendAsync(
    "ReceiveNotification",
    "New announcement"
);

Example: Company-wide announcements.

9.2 Clients.Caller

Sends a message only to the client that invoked the Hub method.

await Clients.Caller.SendAsync(
    "ReceiveMessage",
    "Your request was processed"
);

9.3 Clients.Others

Sends messages to every client except the caller.

await Clients.Others.SendAsync(
    "ReceiveMessage",
    "A new user joined"
);

9.4 Clients.Client()

Sends a message to a particular connection ID.

await Clients.Client(connectionId)
    .SendAsync("ReceiveMessage", "Hello");

9.5 Clients.User()

Sends a message to all connections associated with a particular authenticated user identifier.

await Clients.User(userId)
    .SendAsync(
        "ReceiveNotification",
        "Your order shipped"
    );

9.6 Clients.Group()

Sends a message to all connections in a specific group.

await Clients.Group("Developers")
    .SendAsync(
        "ReceiveMessage",
        "Hello Developers"
    );

10. SignalR Groups

A group is a logical collection of connections.

For example, an application may contain three chat rooms:

  • Developers
  • Testers
  • Managers

Instead of sending messages to everybody, you can send messages only to members of a particular group.

SignalR Groups Architecture

SignalR Hub Developers Testers Managers Group A Group B Group C Client A · Client B Client C · Client D Client E · Client F Messages can target one group at a time. A connection can belong to multiple groups.

Adding a Client to a Group

public class ChatHub : Hub
{
    public async Task JoinRoom(string roomName)
    {
        await Groups.AddToGroupAsync(
            Context.ConnectionId,
            roomName
        );
    }
}

Removing a Client from a Group

public async Task LeaveRoom(string roomName)
{
    await Groups.RemoveFromGroupAsync(
        Context.ConnectionId,
        roomName
    );
}

Sending a Message to a Group

public async Task SendToRoom(
    string roomName,
    string message)
{
    await Clients.Group(roomName)
        .SendAsync("ReceiveMessage", message);
}

Important: Groups are not an authorization mechanism. Always validate whether a user is permitted to join a room. Group membership must be restored after a new connection.

11. Connection Lifecycle Events

SignalR provides lifecycle methods to track when clients connect and disconnect.

OnConnectedAsync()

Called when a client successfully establishes a connection.

public override async Task OnConnectedAsync()
{
    Console.WriteLine(
        $"Connected: {Context.ConnectionId}"
    );
    await base.OnConnectedAsync();
}

OnDisconnectedAsync()

Called when a connection is disconnected.

public override async Task OnDisconnectedAsync(
    Exception? exception)
{
    Console.WriteLine(
        $"Disconnected: {Context.ConnectionId}"
    );
    await base.OnDisconnectedAsync(exception);
}
Client starts connection OnConnectedAsync() Active communication OnDisconnectedAsync()

These are connection lifecycle events, not user account lifecycle events. A user might connect from multiple browser tabs or devices.

12. What is a SignalR Backplane?

A backplane is a shared message-distribution mechanism that allows multiple SignalR servers to exchange messages.

First, understand the problem.

Imagine you have a SignalR application running on a single server.

  • Client A connects to Server 1.
  • Client B connects to Server 1.
  • Client C connects to Server 1.

When Client A sends a message, Server 1 can send it to all three clients.

But what happens when your application grows and you add multiple servers?

12.1 Problem Without a Backplane

Imagine the following architecture:

  • Server 1 has Client A and Client B.
  • Server 2 has Client C and Client D.
  • Server 3 has Client E and Client F.

Each server manages its own SignalR connections.

If Client A sends a message through Server 1, Server 1 knows about Client A and Client B. It doesn't automatically know about the connections on Server 2 and Server 3.

Server 1 Server 2 Server 3 Client A · Client B Client C · Client D Client E · Client F Local connections only Knows A and B Local connections only Knows C and D Local connections only Knows E and F No shared message distribution Server 1 cannot automatically broadcast to Server 2 and 3. Messages remain within the server that handles them.

12.2 How Does a Backplane Solve This Problem?

  1. Client A connects to Server 1.
  2. Client C connects to Server 2.
  3. Client E connects to Server 3.
  4. Client A sends a message.
  5. Server 1 publishes the message to Redis.
  6. Redis distributes the message to the other SignalR servers.
  7. Servers 2 and 3 deliver the message to their connected clients.

SignalR with Redis Backplane

SignalR Server 1 SignalR Server 2 SignalR Server 3 Client A · Client B Client C · Client D Client E · Client F Redis Backplane Publish / Subscribe Distributes messages between servers Messages delivered by each server A, B, C, D, E and F receive the broadcast

Important: Redis is not the database for your chat messages in this architecture. It distributes live messages between SignalR servers. Persist messages separately when they must survive disconnections or server restarts.

13. What is Redis Backplane?

Redis is an in-memory data store that also supports Pub/Sub (Publish/Subscribe) messaging.

SignalR uses Redis Pub/Sub to distribute messages between multiple application servers.

13.1 Publisher and Subscriber

Publisher: The application server that publishes a message to a Redis channel.

Subscriber: An application server that listens to the Redis channel and receives published messages.

SignalR Server 1
       |
       | Publish message
       v
     Redis
       |
       +--------> Server 2
       |
       +--------> Server 3
       |
       +--------> Server 4

13.2 Redis Backplane Configuration

Install the Redis integration package:

dotnet add package Microsoft.AspNetCore.SignalR.StackExchangeRedis

Register Redis in Program.cs:

using SignalRDemo.Hubs;
var builder = WebApplication.CreateBuilder(args);
builder.Services
    .AddSignalR()
    .AddStackExchangeRedis(
        builder.Configuration.GetConnectionString("Redis")
    );
var app = builder.Build();
app.MapHub<ChatHub>("/chatHub");
app.Run();

Add a Redis connection string in appsettings.json:

{
  "ConnectionStrings": {
    "Redis": "localhost:6379"
  }
}

For production, use a managed Redis deployment or a secured Redis instance. Do not expose Redis publicly or commit passwords and access keys to source control.

13.3 Without Redis vs With Redis

Without Redis:

Client A
   |
   v
Server 1
   |
   v
Client B

With Redis:

Client A
   |
   v
Server 1
   |
   v
 Redis
   |
   +------> Server 2 ------> Client B
   |
   +------> Server 3 ------> Client C

13.4 Redis Backplane Advantages

  • Supports multiple application servers.
  • Enables cross-server message distribution.
  • Uses Redis Pub/Sub.
  • Helps applications scale horizontally.
  • Works with virtual machines and containers.

13.5 Redis Backplane Disadvantages

  • Introduces an additional infrastructure dependency.
  • Redis availability affects cross-server message delivery.
  • Adds network communication overhead.
  • Requires monitoring and capacity planning.
  • Does not provide permanent message storage.

13.6 Redis Backplane and Sticky Sessions

In a multi-server ASP.NET Core SignalR deployment, clients generally need to remain connected to the same application server for the lifetime of their connection.

This is called:

  • Sticky sessions.
  • Session affinity.
  • Client affinity.

SignalR maintains connection-related information in the application server process. The Redis backplane distributes messages but does not make every application server interchangeable for an existing client connection.

Exceptions: Sticky sessions are not required when all clients use WebSockets only and negotiation is skipped, or when using Azure SignalR Service.

14. What is Azure SignalR Service?

Azure SignalR Service is a fully managed Azure service designed to handle SignalR connections and real-time message delivery.

It reduces the connection-management responsibilities of your application servers.

14.1 Architecture Without Azure SignalR Service

Client A --------> Server 1
Client B --------> Server 1
Client C --------> Server 2
Client D --------> Server 2
Servers communicate through Redis.

14.2 Architecture With Azure SignalR Service

Client A --------\
Client B ---------\
Client C ----------> Azure SignalR Service
Client D ---------/          |
                             |
                  ---------------------
                  |                   |
               Server 1            Server 2

Azure SignalR Service manages client connections and routes real-time messages between clients and application servers.

Azure SignalR Service Architecture

Client A Client B Client C Browser Mobile Desktop Azure SignalR Service Connection management Real-time message routing ASP.NET Core Server 1 ASP.NET Core Server 2 Business logic · SignalR Hub Business logic · SignalR Hub Managed service handles the client connection layer.

14.3 Azure SignalR Service Advantages

  • Managed connection infrastructure.
  • Supports large numbers of concurrent connections.
  • Reduces connection pressure on application servers.
  • Provides message routing across application instances.
  • Removes the need to configure Redis as a SignalR backplane.
  • Avoids application-level sticky-session requirements.

14.4 When Should You Use Azure SignalR Service?

  • Your application is hosted in Azure.
  • You need to handle many concurrent connections.
  • You want managed connection infrastructure.
  • You want to reduce the connection-management workload on your application servers.
  • You need a managed scale-out solution.

15. Redis Backplane vs Azure SignalR Service

Feature Redis Backplane Azure SignalR Service
InfrastructureRedis and application serversManaged Azure service and application servers
Connection managementApplication serversAzure SignalR Service
Message distributionRedis Pub/SubManaged service
Sticky sessionsGenerally requiredNot required at application level
Self-hostingYesNo
Azure integrationCan be hosted on AzureNative Azure service
Infrastructure managementYou manage RedisMicrosoft manages service infrastructure
Best suited forSelf-hosted deploymentsAzure-hosted deployments

Architectural recommendation:

  • On-premises or self-hosted infrastructure: Redis backplane is a strong option.
  • Azure-hosted application: Prefer Azure SignalR Service.
  • Single-server application: You may not need either initially.

16. Horizontal Scaling of SignalR

Horizontal scaling means adding more application server instances instead of increasing the resources of a single server.

Before Scaling

             Server 1
                |
           1,000 clients

After Horizontal Scaling

       Load Balancer
              |
       --------------
       |     |      |
    Server 1 Server 2 Server 3
       |     |      |
    Clients Clients Clients

However, SignalR requires a mechanism for cross-server message distribution. That is where Redis backplane or Azure SignalR Service comes into the picture.

Vertical Scaling vs Horizontal Scaling

Feature Vertical Scaling Horizontal Scaling
MeaningIncrease server resourcesAdd more servers
CPUIncrease CPU capacityDistribute CPU workload
MemoryIncrease RAMAdd memory across servers
InfrastructureOne larger machineMultiple machines
SignalR scale-outDoesn't inherently require a backplaneUsually requires shared message distribution

17. SignalR in Microservices Architecture

SignalR is particularly useful in microservices applications.

Imagine an e-commerce application with these services:

  • Order Service.
  • Payment Service.
  • Inventory Service.
  • Notification Service.
  • SignalR Hub.

Example Workflow

  1. Customer places an order.
  2. Order Service creates the order.
  3. Payment Service processes payment.
  4. Inventory Service updates stock.
  5. An event is published through RabbitMQ.
  6. Notification Service consumes the event.
  7. Notification Service sends an update using SignalR.
  8. Customer receives the notification immediately.

SignalR with RabbitMQ in Microservices

Customer Application Order Service Payment Service Inventory Service Other Services Payment events Stock events Business events RabbitMQ Business event distribution Notification Service SignalR to Customer

Important Architectural Distinction

RabbitMQ SignalR
Service-to-service communicationServer-to-client communication
Message brokerReal-time communication framework
Supports asynchronous messagingSupports live connected-client messaging
Can provide durable delivery with appropriate configurationNot a durable message store
Consumers process business eventsClients receive real-time updates

Best practice: Use RabbitMQ for backend business events and SignalR for notifying connected users.

Payment Service
       |
       v
    RabbitMQ
       |
       v
Notification Service
       |
       v
SignalR
       |
       v
Customer Browser

18. Sending SignalR Messages from Outside a Hub

A common real-world requirement is sending notifications from a background service, controller or another application service.

Examples:

  • Payment completed.
  • Order shipped.
  • User account updated.
  • Background job completed.
  • Report generated.

You cannot directly call Clients.All from an ordinary service because Clients belongs to the Hub instance.

Instead, use IHubContext.

What is IHubContext?

IHubContext allows application services outside a Hub to send messages to connected clients.

using Microsoft.AspNetCore.SignalR;
public class NotificationService
{
    private readonly IHubContext<ChatHub> _hubContext;
    public NotificationService(
        IHubContext<ChatHub> hubContext)
    {
        _hubContext = hubContext;
    }
    public async Task SendNotification(string message)
    {
        await _hubContext.Clients.All.SendAsync(
            "ReceiveNotification",
            message
        );
    }
}

Register the service:

builder.Services.AddScoped<NotificationService>();

Use it in a controller:

[ApiController]
[Route("api/orders")]
public class OrdersController : ControllerBase
{
    private readonly NotificationService _notification;
    public OrdersController(
        NotificationService notification)
    {
        _notification = notification;
    }
    [HttpPost]
    public async Task<IActionResult> CreateOrder()
    {
        // Save order to database.
        await _notification.SendNotification(
            "A new order has been created"
        );
        return Ok("Order created");
    }
}

Why is IHubContext important? It separates real-time communication from business logic. Controllers, services and background workers can send notifications without inheriting from Hub.

19. SignalR Authentication and Authorization

In production applications, you should not allow every connected client to access every Hub method.

SignalR supports ASP.NET Core authentication and authorization.

19.1 JWT Authentication

JWT (JSON Web Token) is commonly used when connecting web or mobile applications to SignalR.

builder.Services
    .AddAuthentication()
    .AddJwtBearer(options =>
    {
        // Configure token validation parameters.
        // Set issuer, audience and signing key.
    });

Configure SignalR to read the access token from the query string for the Hub endpoint when required by browser WebSocket or SSE connections:

options.Events = new JwtBearerEvents
{
    OnMessageReceived = context =>
    {
        var accessToken = context.Request.Query[
            "access_token"
        ];
        var path = context.HttpContext.Request.Path;
        if (!string.IsNullOrEmpty(accessToken) &&
            path.StartsWithSegments("/chatHub"))
        {
            context.Token = accessToken;
        }
        return Task.CompletedTask;
    }
};

Configure the JavaScript client:

const connection = new signalR.HubConnectionBuilder()
    .withUrl("/chatHub", {
        accessTokenFactory: () => getAccessToken()
    })
    .build();

Important security considerations:

  • Use HTTPS.
  • Validate JWT issuer, audience and signature.
  • Configure token expiration correctly.
  • Restrict query-string token handling to the required Hub endpoint.
  • Avoid logging access tokens.
  • Use a suitable token renewal strategy.

19.2 Authorize a Hub

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
[Authorize]
public class ChatHub : Hub
{
    public async Task SendMessage(string message)
    {
        await Clients.All.SendAsync(
            "ReceiveMessage",
            message
        );
    }
}

Now only authenticated users can connect to the Hub.

19.3 Role-Based Authorization

[Authorize(Roles = "Admin")]
public class AdminHub : Hub
{
    public async Task SendAnnouncement(string message)
    {
        await Clients.All.SendAsync(
            "ReceiveAnnouncement",
            message
        );
    }
}

Only users with the Admin role can access this Hub.

19.4 Method-Level Authorization

public class ChatHub : Hub
{
    [Authorize(Roles = "Admin")]
    public async Task DeleteMessage(int messageId)
    {
        // Validate and delete message.
    }
}

For more complex scenarios, use authorization policies and explicit resource-level checks.

Important: Protect both Hub connections and sensitive Hub methods. Never trust a client-supplied user ID, group name or role.

20. Automatic Reconnection and Connection Recovery

Network interruptions can happen in real applications.

  • Internet connection lost.
  • Mobile network changes.
  • Server restart.
  • Browser temporarily goes offline.
  • Load balancer closes an idle connection.

SignalR provides automatic reconnection support on supported clients.

const connection = new signalR.HubConnectionBuilder()
    .withUrl("/chatHub")
    .withAutomaticReconnect()
    .build();

The default automatic reconnect policy attempts reconnection after approximately:

AttemptDelay
First0 seconds
Second2 seconds
Third10 seconds
Fourth30 seconds
Further attemptsStop

Note that withAutomaticReconnect() does not automatically retry the initial connection.start() failure.

Handling Initial Connection Failures

async function start() {
    try {
        await connection.start();
        console.log("Connected");
    }
    catch (error) {
        console.error("Connection failed", error);
        setTimeout(start, 5000);
    }
}

Handling Reconnection Events

connection.onreconnecting(error => {
    console.log("Reconnecting...", error);
});
connection.onreconnected(connectionId => {
    console.log("Reconnected", connectionId);
});
connection.onclose(error => {
    console.log("Connection closed", error);
});

Important: A successful reconnection establishes a new connection. Rejoin required groups and restore application-specific subscriptions. SignalR reconnection alone does not guarantee delivery of messages missed during disconnection.

21. SignalR Performance Optimization

Real-time applications can consume considerable resources because every active connection requires server and network resources.

21.1 Use WebSockets

Prefer WebSockets where supported. It generally provides better performance and lower communication overhead than fallback transports.

21.2 Use MessagePack

SignalR supports JSON and MessagePack Hub protocols.

JSON example:

{
  "user": "John",
  "message": "Hello"
}

MessagePack is a binary serialization format that can reduce message size compared with JSON for many payloads.

Install the package:

dotnet add package Microsoft.AspNetCore.SignalR.Protocols.MessagePack

Register it:

builder.Services
    .AddSignalR()
    .AddMessagePackProtocol();

21.3 Avoid Large Messages

Do not send unnecessarily large objects through SignalR. Instead of sending an entire order object, send only the information required by the client.

await Clients.User(userId).SendAsync(
    "OrderUpdated",
    new
    {
        OrderId = 1001,
        Status = "Shipped"
    }
);

21.4 Use Groups Instead of Broadcasting to Everyone

Avoid broadcasting every message to every user when only a particular group needs the information.

await Clients.Group("Developers").SendAsync(
    "ReceiveMessage",
    message
);

21.5 Avoid Blocking Operations

Prefer asynchronous operations:

await _orderService.ProcessOrderAsync(orderId);

Avoid synchronous blocking calls:

_orderService.ProcessOrderAsync(orderId).Wait();

21.6 Monitor Active Connections

  • Active connections.
  • Connection failures.
  • Reconnection rates.
  • Messages per second.
  • Message processing latency.
  • CPU utilization.
  • Memory consumption.
  • Network throughput.

22. SignalR Production Best Practices

AreaRecommended Practice
ArchitectureKeep Hub methods thin
Business logicMove into application services
AuthenticationUse JWT or another supported authentication scheme
AuthorizationApply roles and policies
TransportPrefer WebSockets where supported
ScalingUse Redis or Azure SignalR Service
SerializationConsider MessagePack
MessagesKeep payloads small
GroupsValidate membership permissions
ConnectionHandle disconnect and reconnect
DatabasePersist important messages separately
MonitoringMonitor connections and latency
SecurityUse HTTPS and validate inputs
LoggingAvoid sensitive information
ReliabilityDesign for duplicate events and missed notifications

23. Common Mistakes to Avoid

Mistake 1: Keeping Business Logic Inside Hub Methods

Bad approach:

public async Task ProcessPayment()
{
    // Entire payment processing implementation.
}

Better approach:

public async Task ProcessPayment(int orderId)
{
    await _paymentService.ProcessAsync(orderId);
    await Clients.Caller.SendAsync(
        "PaymentCompleted"
    );
}

Mistake 2: Using Clients.All Unnecessarily

Broadcasting every message to every user wastes network resources. Use groups or user-specific delivery where appropriate.

Mistake 3: Assuming Redis Stores Messages Permanently

Redis Pub/Sub is a message-distribution mechanism, not a persistent chat-history database. Store important messages in SQL Server, PostgreSQL or another appropriate database.

Mistake 4: Not Handling Reconnection

Network interruptions are normal. Implement reconnection and subscription recovery.

Mistake 5: Trusting Client-Supplied User IDs

Identify authenticated users through the server-side identity and claims rather than trusting values supplied by clients.

Mistake 6: Forgetting Sticky Sessions

When self-hosting SignalR on multiple servers with Redis, configure session affinity unless an applicable exception exists.

Mistake 7: Assuming Groups Provide Security

Groups are useful for message distribution, but group membership must be authorized.

Mistake 8: Using SignalR for Every Type of Communication

SignalR is designed for real-time communication. It is not a replacement for REST APIs, RabbitMQ, databases or durable event processing.

24. SignalR vs REST API vs RabbitMQ

Feature REST API SignalR RabbitMQ
Primary purposeRequest-responseReal-time communicationAsynchronous messaging
CommunicationHTTPPersistent connectionBroker messaging
Main directionClient-serverTwo-wayProducer-consumer
Server pushNot inherentlyYesNot directly to browser clients
Real-time updatesRequires polling or another mechanismYesRequires a consumer and delivery mechanism
Message persistenceApplication-dependentNot inherentlyConfigurable durable messaging
Typical usageCRUD operationsChat and notificationsBackground jobs and integration events

Which One Should You Use?

  • REST API: Fetch customer details, create orders and update products.
  • SignalR: Notify customers about order status changes.
  • RabbitMQ: Communicate order events between microservices.

They complement each other.

25. Real-World Architecture: E-Commerce Application

Consider an e-commerce application built using ASP.NET Core microservices.

The customer wants to see order status changes immediately.

Architecture

Customer Application ASP.NET Core API Microservices Order · Payment · Inventory RabbitMQ Order status events Notification Service SignalR Hub Real-time update to customer Database persists order information independently of SignalR.

Example Order Notifications

Order Created
     |
     v
Payment Completed
     |
     v
Order Confirmed
     |
     v
Order Shipped
     |
     v
Out for Delivery
     |
     v
Delivered

The customer receives each status update through SignalR.

For reliability, the notification service should consume durable business events, persist relevant notification information where necessary, and handle duplicate events safely.

26. SignalR Troubleshooting

Problem Possible Reason What to Check
Connection failsIncorrect Hub URLEndpoint configuration
404 errorHub not mappedMapHub()
401 errorAuthentication failureJWT validation
403 errorAuthorization failureRoles and policies
WebSocket connection failsProxy or server configurationWebSocket support
Messages not receivedIncorrect event nameClient on() handler
Messages work on one server onlyMissing backplaneRedis or Azure SignalR
Intermittent disconnectsNetwork or infrastructure timeoutsLogs and proxy configuration
Reconnects but no group messagesGroup membership not restoredRejoin groups
High CPU consumptionExcessive messages or processingProfiling and message volume

27. Important Interview Questions and Answers

Q1. What is ASP.NET Core SignalR?

ASP.NET Core SignalR is a real-time communication library that enables servers to push messages to connected clients instantly.

Q2. What is a Hub?

A Hub is a high-level communication component that manages client-server method invocations and message delivery.

Q3. What is WebSocket?

WebSocket is a communication protocol that provides full-duplex communication over a persistent connection.

Q4. What transports are supported by SignalR?

WebSockets, Server-Sent Events and Long Polling.

Q5. What is a backplane?

A backplane distributes messages between multiple SignalR application servers so clients connected to different servers can receive the same messages.

Q6. Why is Redis used with SignalR?

Redis provides Pub/Sub messaging, allowing SignalR servers to distribute messages between different application instances.

Q7. What is Azure SignalR Service?

It is a managed Azure service that handles SignalR client connections and message routing, reducing connection-management responsibilities on application servers.

Q8. What is the difference between Redis Backplane and Azure SignalR Service?

Redis distributes messages between application servers while the application servers manage client connections. Azure SignalR Service manages client connections and message routing.

Q9. What is IHubContext?

IHubContext allows controllers, services and background workers to send messages to SignalR clients without inheriting from Hub.

Q10. What is the difference between Clients.All and Clients.Caller?

Clients.All sends a message to all connected clients, whereas Clients.Caller sends a message only to the client that invoked the Hub method.

Q11. What are SignalR groups?

Groups are logical collections of connections used to send messages to selected clients.

Q12. Does SignalR store messages permanently?

No. SignalR provides real-time message delivery. Permanent message storage must be implemented separately.

Q13. What are sticky sessions?

Sticky sessions ensure that requests associated with a SignalR connection are routed to the same application server.

Q14. Can SignalR work with microservices?

Yes. Microservices can publish business events through RabbitMQ, and a notification service can use SignalR to deliver updates to connected users.

Q15. How does SignalR handle disconnections?

SignalR provides connection lifecycle callbacks and optional automatic reconnection support in its clients.

Q16. Can SignalR communicate with mobile applications?

Yes. Supported .NET and JavaScript clients and other supported client SDKs can communicate with ASP.NET Core SignalR servers.

Q17. What is the difference between SendAsync and InvokeAsync?

SendAsync sends a message without waiting for a result from the invoked method. InvokeAsync invokes a remote operation and awaits its completion and result.

Q18. Why should Hub methods be lightweight?

Lightweight Hub methods improve responsiveness and maintain separation between communication handling and business processing.

Q19. Can a user have multiple SignalR connections?

Yes. For example, a user can connect from multiple browser tabs, devices or applications.

Q20. What happens if Redis becomes unavailable?

Cross-server message distribution can fail or be disrupted. The application should monitor Redis availability and define appropriate operational recovery procedures.

28. Final Architecture Decision Guide

Requirement Recommended Solution
Simple real-time chatSignalR
Live dashboardSignalR
Personal notificationsSignalR + Clients.User
Department notificationsSignalR Groups
Multiple self-hosted serversSignalR + Redis
Azure-hosted real-time applicationAzure SignalR Service
Microservice communicationRabbitMQ
Permanent chat historySQL Server / PostgreSQL
Background processingHosted Service / Worker Service
Real-time order trackingREST API + SignalR + Backend Events

29. Official Microsoft Documentation

  1. ASP.NET Core SignalR Overview
  2. Working with SignalR Hubs
  3. SignalR JavaScript Client
  4. SignalR .NET Client
  5. SignalR Hosting and Scaling
  6. SignalR Authentication and Authorization
  7. Azure SignalR Service
  8. Redis Backplane Configuration

30. Quick Revision

  • SignalR: Real-time communication.
  • Hub: Communication between clients and server.
  • WebSockets: Full-duplex communication.
  • Groups: Send messages to selected connections.
  • IHubContext: Send messages outside Hub classes.
  • Redis Backplane: Distribute messages between self-hosted servers.
  • Azure SignalR Service: Managed connection and message-routing infrastructure.
  • RabbitMQ: Backend asynchronous communication.
  • JWT: Authenticate SignalR connections.
  • Sticky Sessions: Keep a connection associated with the same application server when required.
  • Horizontal Scaling: Run multiple application instances.

Final architectural concept: SignalR handles real-time communication, Redis or Azure SignalR Service helps distribute messages across multiple servers, and RabbitMQ handles backend service-to-service messaging. They solve different problems and can work together in a scalable ASP.NET Core microservices architecture.

🔙
Building Microservices Using RabbitMQ :👈 👉:gRPC