LESSON 13 OF 14

13. Multi-Server Scalability with a Redis Backplane

Configure a Redis backplane for SignalR, distribute Hub messages across multiple ASP.NET Core instances, and test Docker deployment, sticky sessions, routing, and failure behavior.

35 dk 54

Introduction

In a single ASP.NET Core instance, every SignalR connection is maintained in the memory of the server that accepted it. When the application is scaled to two or more server instances, each instance knows only about its own connections. If client A is connected to app-1 while client B is connected to app-2, a message sent through the first instance does not reach client B unless the application has a scale-out mechanism.

In this lesson, we will configure the SignalR Redis backplane, which uses Redis publish/subscribe to distribute messages between application instances. Each instance will connect to Redis, receive publications from the other instances, and forward those messages to its local clients. We will also run Redis, two application instances, and an Nginx load balancer with Docker Compose.

A Redis backplane is not a durable message queue. It is designed to distribute live SignalR messages between servers. If the application must reliably store and replay historical events, it should use a database or a durable messaging system in addition to SignalR.

1. Understanding the scale-out model

Without a backplane

Assume that two servers run the same Hub code. Client A is connected to the first server and client B is connected to the second. When client A invokes a Hub method, the first server knows only about its local connections. As a result, client B does not receive the message.

With a Redis backplane

When the backplane is enabled, the server sends a message to its local clients and publishes the message to a Redis pub/sub channel. The other SignalR instances receive that publication and send it to their own local connections. Connection state remains local to each server, while message distribution happens through the shared communication layer.

A Redis backplane does not remove the requirement that a connection remain on the same server. ASP.NET Core SignalR expects a connection to communicate with the same application instance throughout its lifetime. Therefore, a multi-server deployment using Redis normally requires sticky sessions or session affinity at the load balancer.

2. Installing and configuring the Redis package

Add the SignalR Redis package to the existing project:

dotnet add package Microsoft.AspNetCore.SignalR.StackExchangeRedis

The following example reads the Redis connection from configuration. The ChannelPrefix separates this application's channels from channels used by other applications sharing the same Redis server.

using StackExchange.Redis;

var builder = WebApplication.CreateBuilder(args);

var redisConnection = builder.Configuration.GetConnectionString("Redis")
    ?? "localhost:6379";

builder.Services.AddSignalR()
    .AddStackExchangeRedis(redisConnection, options =>
    {
        options.Configuration.ChannelPrefix =
            RedisChannel.Literal("realtime-course");
    });

builder.Services.AddControllers();

var app = builder.Build();

app.MapControllers();
app.MapHub<ClusterHub>("/hubs/cluster");

app.Run();

The AddStackExchangeRedis call must be made before builder.Build(). In production, use passwords, TLS, network access rules, and secret configuration rather than placing credentials in source code.

3. Making the application instance visible

To identify which application instance produced a message, add an instance name to the Hub response:

using Microsoft.AspNetCore.SignalR;

public sealed class ClusterHub : Hub
{
    private readonly IConfiguration _configuration;

    public ClusterHub(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    public async Task Publish(string text)
    {
        var instance = _configuration["INSTANCE_NAME"] ?? "unknown";

        await Clients.All.SendAsync("messageReceived", new
        {
            text,
            instance,
            sentAtUtc = DateTimeOffset.UtcNow
        });
    }
}

When two clients use the shared load-balancer address, the instance field lets you see which server handled the invocation. The receiving client should still get the message regardless of which application instance originally processed it.

4. Running Redis and two application instances with Docker

For a quick local test, run Redis using the official image:

docker run -d --name signalr-redis -p 6379:6379 redis:latest

When application containers share a Docker network, the Redis host is the service name rather than localhost. The following Compose file defines Redis and two application instances:

services:
  redis:
    image: redis:latest
    command: ["redis-server", "--appendonly", "yes"]
    volumes:
      - redis-data:/data

  app1:
    build: .
    environment:
      ASPNETCORE_URLS: http://+:8080
      ConnectionStrings__Redis: redis:6379
      INSTANCE_NAME: app-1

  app2:
    build: .
    environment:
      ASPNETCORE_URLS: http://+:8080
      ConnectionStrings__Redis: redis:6379
      INSTANCE_NAME: app-2

volumes:
  redis-data:

This starts two identical application containers, but clients still need a common entry point that decides which instance receives each request. Add a load balancer for a realistic multi-server test.

5. Routing connections with sticky sessions

A simple Nginx configuration can use ip_hash so that requests from the same client address are routed to the same backend:

upstream signalr_backend {
    ip_hash;
    server app1:8080;
    server app2:8080;
}

server {
    listen 80;

    location / {
        proxy_pass http://signalr_backend;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_read_timeout 100s;
    }
}

The WebSocket upgrade headers are required for a WebSocket connection to pass through the proxy. If WebSockets are unavailable, SignalR may fall back to Server-Sent Events or Long Polling. Those transports also benefit from keeping the connection's requests on the same application instance.

A client that uses WebSockets only and skips negotiation can reduce some affinity requirements. However, that approach limits transport choices and depends on every proxy and client supporting WebSockets correctly. For a general multi-server deployment, session affinity is the safer default.

6. Verifying the setup with a TypeScript client

Keep the resilient-client approach from the previous lesson and connect to the shared load-balancer address:

import { HubConnectionBuilder, LogLevel } from "@microsoft/signalr";

type ClusterMessage = {
  text: string;
  instance: string;
  sentAtUtc: string;
};

const connection = new HubConnectionBuilder()
  .withUrl("/hubs/cluster")
  .withAutomaticReconnect()
  .configureLogging(LogLevel.Information)
  .build();

connection.on("messageReceived", (message: ClusterMessage) => {
  console.log(
    `[${message.instance}] ${message.text} - ${message.sentAtUtc}`
  );
});

await connection.start();
await connection.invoke("Publish", "Hello from multiple servers");

Open two separate clients and make sure both use the same load-balancer address. Send a message from one client. The Redis publication should reach the other application instance, which then forwards the event to its local client.

7. Testing failure scenarios

Stopping Redis

Stop the Redis container:

docker stop signalr-redis

Messages that need to cross the backplane can no longer be delivered. SignalR does not buffer those messages and replay them after Redis becomes available. Events produced while Redis is unavailable may therefore be lost. Client automatic reconnect restores the SignalR connection; it does not recover the history of Redis publications.

Restart Redis and inspect the application logs:

docker start signalr-redis
docker compose logs -f app1 app2

The application can reconnect when Redis becomes available again. If a message is business-critical, add a durable record, an idempotency key, or a persistent queue instead of relying only on a transient SignalR broadcast.

Removing sticky sessions

Remove the ip_hash line and test round-robin routing. Negotiation, connection establishment, or Long Polling requests may be sent to different instances, causing connection failures or inconsistent behavior. This experiment demonstrates that a backplane and session affinity solve different problems.

8. Common mistakes

  • Using the wrong Redis host: A container should use redis:6379, the Compose service name, rather than localhost:6379.
  • Using inconsistent channel prefixes: Instances belonging to the same application must use the same prefix. Separate applications sharing one Redis server should use different prefixes.
  • Treating the backplane as durable storage: Redis pub/sub does not provide message history. Reconnecting clients do not automatically receive old SignalR events.
  • Forgetting sticky sessions: The backplane distributes messages between servers but does not transfer ownership of an active client connection.
  • Placing Redis far from the application: High network latency can delay real-time messages and reduce backplane performance.
  • Broadcasting excessive traffic: With high-frequency client-to-client traffic, forwarding every message to every node can make Redis or the network a bottleneck.

9. Short practice exercise

  1. Run Redis, two ASP.NET Core instances, and an Nginx load balancer.
  2. Assign a different INSTANCE_NAME value to each application instance.
  3. Configure the same ChannelPrefix for both instances.
  4. Connect two clients to the shared Nginx address and send a message from one of them.
  5. Remove sticky-session configuration and compare the behavior.
  6. Stop Redis, send a message, and verify from the logs that it is not delivered later automatically.
  7. Add a message identifier and design a small client-side deduplication mechanism to prevent processing the same event twice.

Conclusion

A Redis backplane is a practical scale-out approach for sharing ASP.NET Core SignalR Hub messages across multiple application instances. The integration consists of the Microsoft.AspNetCore.SignalR.StackExchangeRedis package, a shared Redis connection, and an application-specific channel prefix. Docker makes it easy to run Redis and several application instances in a repeatable local environment.

Before production deployment, test sticky sessions, WebSocket proxy settings, Redis availability, network latency, connection counts, message frequency, and behavior after failures. Redis backplane is useful when the team manages its own infrastructure, while Azure SignalR Service and other managed options may be more suitable when connection scale or operational simplicity is the primary concern.

Sources