skip to content

In ASP.NET Core SignalR, what does AddStackExchangeRedis register, and why set ChannelPrefix when several apps share one Redis server?

level: middleimportance: should knowfreq 36%

answer

  1. Microsoft.AspNetCore.SignalR.StackExchangeRedis package
  2. RedisHubLifetimeManager<THub>
  3. channels named after the hub's full type name
  4. options.Configuration.ChannelPrefix
  5. RedisChannel.Literal("commentary-prod")

basics

~20 s

AddStackExchangeRedis registers RedisHubLifetimeManager<THub>, which turns sends into Redis publishes on channels named after the hub's full type name. Two deployments with the same hub on one Redis would hear each other's broadcasts; a distinct Configuration.ChannelPrefix per app keeps them apart.

solid answer

~40 s

The package is `Microsoft.AspNetCore.SignalR.StackExchangeRedis`. `AddSignalR().AddStackExchangeRedis(connectionString, o => ...)` parses the string into `RedisOptions.Configuration`, a StackExchange.Redis `ConfigurationOptions`, runs your callback, and registers `RedisHubLifetimeManager<THub>` as the hub lifetime manager. Channel names start with `typeof(THub).FullName`: `...:all`, `...:group:{name}`, `...:user:{id}`, `...:connection:{id}` and a few internal ones. Staging and production of the same app, or two tenants' copies, therefore use identical channel names on a shared Redis, and a `Clients.All` in staging reaches production fans. Setting `options.Configuration.ChannelPrefix = RedisChannel.Literal("commentary-prod")`, or `channelPrefix=` in the connection string, makes StackExchange.Redis prefix every channel and isolates the apps. In ASP.NET Core 10 the property is a `RedisChannel`; the implicit string conversion is obsolete.

code

csharp · 15 lines
csharp
using StackExchange.Redis;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddSignalR()
    .AddStackExchangeRedis(builder.Configuration.GetConnectionString("backplane")!, options =>
    {
        // One value per deployment that shares this Redis server.
        options.Configuration.ChannelPrefix =
            RedisChannel.Literal(builder.Configuration["Backplane:ChannelPrefix"] ?? "commentary-dev");
    });

var app = builder.Build();
app.MapHub<CommentaryHub>("/hubs/commentary");
app.Run();

go deeper

for a junior

Recall the package name, Microsoft.AspNetCore.SignalR.StackExchangeRedis, and that AddStackExchangeRedis is chained onto AddSignalR with a Redis connection string.

for a middle

Explain that the backplane names channels after the hub's full type name, so copies of one app on a shared Redis collide, and that Configuration.ChannelPrefix separates them.

for a senior

Mention the abortConnect difference between the string and callback overloads, same-data-center placement, and that a prefix isolates messages but not Redis capacity.

for a principal

Decide whether environments may share a Redis server at all, weighing the saving against cross-environment leaks and one noisy tenant slowing every backplane.

## What the call registers The Redis backplane ships as the NuGet package **`Microsoft.AspNetCore.SignalR.StackExchangeRedis`**. It adds four `AddStackExchangeRedis` overloads on `ISignalRServerBuilder`, the object `AddSignalR()` returns: - `AddStackExchangeRedis()` with defaults (it connects to localhost); - `AddStackExchangeRedis(string redisConnectionString)`; - `AddStackExchangeRedis(Action<RedisOptions> configure)`; - `AddStackExchangeRedis(string redisConnectionString, Action<RedisOptions> configure)`. Each registers **`RedisHubLifetimeManager<THub>`** as the singleton `HubLifetimeManager<>`, replacing the in-memory default. `RedisOptions` has two properties: `Configuration`, a StackExchange.Redis `ConfigurationOptions`, and `ConnectionFactory`, a delegate for building the `IConnectionMultiplexer` yourself. The string overloads parse the connection string into `Configuration` first and run your callback afterwards, so values set in code win. ## How the channels are named The manager uses Redis **publish/subscribe**. Channel names are built from the hub's full type name, for example `Live.Hubs.CommentaryHub`: | Channel | Carries | |---|---| | `{hub}:all` | `Clients.All`, `Others`, `AllExcept` | | `{hub}:group:{group}` | `Clients.Group(...)` | | `{hub}:user:{userId}` | `Clients.User(...)` | | `{hub}:connection:{connectionId}` | sends addressed by connection id, such as a single remote connection or `Clients.Clients(ids)` | | `{hub}:internal:...` | group commands, acknowledgements, client results | There is no application name in that scheme. Two processes that map the same hub type on the same Redis server are, to Redis, the same app. ## Why shared Redis servers collide The usual way to hit this: 1. Staging and production of the sports-commentary app share one Redis server to save cost. 2. Both run `Live.Hubs.CommentaryHub`. 3. A tester triggers a `Clients.All` broadcast in staging, and production fans receive it. Two apps whose hubs have different full type names do not cross, because their channel names differ. The risk is a copy of the same app: a staging slot, a second tenant, a load-test environment. ## Setting the prefix StackExchange.Redis adds `ConfigurationOptions.ChannelPrefix` to every channel name it publishes or subscribes to, without SignalR knowing: - in code: `options.Configuration.ChannelPrefix = RedisChannel.Literal("commentary-prod");` - in the connection string: `redis:6379,channelPrefix=commentary-prod`. Give each deployment its own value. The prefix is prepended to the channel name as it is, with no separator added, so ending it with one, such as `commentary-prod:`, keeps channel names readable when you list them on the Redis server. The prefix isolates **pub/sub traffic** only. The apps still share the Redis server's CPU and network, and a noisy neighbour can still slow the backplane. ## Other settings worth knowing - **Connection failures at start-up.** `RedisOptions` starts with `AbortOnConnectFail = false`, so the multiplexer keeps retrying in the background. The string overloads replace that object with `ConfigurationOptions.Parse(...)`, where StackExchange.Redis's own default applies, so add `abortConnect=false` to the string if you want the same behaviour. - **Placement.** The docs recommend a Redis backplane only in the same data center as the app, because every broadcast takes a round trip through it. - **Redis Cluster.** List all nodes in the connection string; messages reach every node, and more nodes trade throughput for availability. - **Sticky sessions.** Still required; the backplane carries messages, not connections. ## Checking the isolation On the Redis server, list the active channels for one deployment's prefix. With `commentary-prod:` set, every SignalR channel of that deployment starts with it, and a staging deployment with its own prefix shows up separately: ```bash redis-cli PUBSUB CHANNELS 'commentary-prod:*' ``` Channels that appear without any prefix belong to a deployment nobody configured, which is exactly the one that will leak. ## Version notes ASP.NET Core 10.0.12 builds this package against StackExchange.Redis 2.7.27; an app may resolve a newer 2.x or 3.x. In both, `ChannelPrefix` is a `RedisChannel`, and assigning a plain string relies on an implicit conversion marked `[Obsolete]`, so `RedisChannel.Literal` is the clean spelling.

  • If two different apps share one Redis server but their hubs have different full type names, do they still need prefixes?
    Their broadcasts already stay apart, because SignalR builds every channel name from `typeof(THub).FullName`. A prefix is still cheap insurance: it makes ownership obvious when you inspect Redis, and it protects you the day someone deploys a second copy of either app, such as a staging slot or another tenant, against the same server.
  • Does selecting a different Redis database number in each app's connection string isolate their SignalR traffic?
    No. Redis pub/sub channels are not scoped to a database number; a message published while one database is selected reaches subscribers that selected another. Use a distinct `ChannelPrefix`, or separate Redis servers, to isolate SignalR backplane traffic.

  • AddStackExchangeRedis keeps SignalR messages in Redis keys until clients read them.
  • Set RedisCacheOptions.InstanceName to isolate SignalR apps that share one Redis server.
  • A different defaultDatabase in each connection string isolates the apps' SignalR traffic.
  • Without ChannelPrefix, every SignalR app on one Redis server receives every other app's broadcasts, whatever its hub names.

Assumes ASP.NET Core SignalR 10, whose Redis package builds against StackExchange.Redis 2.7.27; ChannelPrefix is a RedisChannel and RedisChannel.Literal replaces the obsolete implicit string conversion.