Skip to content

Redis ​

Introduction ​

Redis is what lets several DotBlaze servers work as one: a fast queue, a shared cache, shared encryption keys, and a backplane for broadcast notifications. All of it is in the DotBlaze.Redis package, built on StackExchange.Redis.

Installation ​

shell
dotnet add package DotBlaze.Redis

Nothing else: DotBlaze loads the package when a setting uses the redis driver. Queue connections and cache stores that name redis only need the package when they are used; app.keys_driver and broadcasting.driver set to redis without the package stop the app at startup with a message saying so.

Configuration ​

Connections are defined in config/Database.cs, next to the database connections:

csharp
redis = new
{
    @default = new { host = Env("REDIS_HOST"), port = 6379, password = Env("REDIS_PASSWORD"), database = 0 },
    cache = new { host = Env("REDIS_HOST"), port = 6379, password = Env("REDIS_PASSWORD"), database = 1 },
},
KeyDescription
host, portDefault 127.0.0.1 and 6379.
username, passwordFor Redis ACLs / requirepass.
databaseThe database number. Default 0.
tlstrue to connect with TLS.
urlA StackExchange.Redis configuration string instead ("redis.internal:6380,password=...,ssl=true").
prefixPrepended to every key and pub/sub channel of this connection, so several apps can share one Redis.

Each connection is one multiplexed TCP connection per process, shared by everything that uses it.

What Uses Redis ​

Queues ​

In config/Queue.cs:

csharp
connections = new
{
    redis = new { driver = "redis", connection = "default", queue = "default", retry_after = 90 },
},

Set @default = "redis" there (or dispatch with .OnConnection("redis")). The layout is Laravel's: a list queues:{name} of ready jobs and sorted sets queues:{name}:delayed and queues:{name}:reserved. Taking a job is a Lua script that moves it from the list to reserved and counts the attempt in one step, so any number of queue:work processes can share a queue without running a job twice. A job whose worker dies is handed out again after retry_after seconds. Failed jobs still go to the failed_jobs table of the default database, so queue:failed, queue:retry, and queue:flush work the same. See Queues.

Cache ​

In config/Cache.cs:

csharp
stores = new
{
    redis = new { driver = "redis", connection = "cache" },
},

Set @default = "redis" there. Counters use INCRBY and locks SET NX, so both are atomic across servers. The rate limiter uses the cache too, so login throttling then counts across servers. See Cache.

Data Protection Keys ​

Login cookies, CSRF tokens, Crypt, signed URLs, and live component snapshots are protected with the app's Data Protection keys. With an APP_KEY (the default for new apps), every server with the same key already shares them, and this setting is not needed. Without one, the servers must share the generated keys. In config/App.cs:

csharp
keys_driver = "redis",
keys_connection = "default",

The keys are stored under the key dotblaze:data-protection-keys (after the connection's prefix). Every server must also use the same app.name.

Broadcasting Backplane ​

Broadcast events and notifications go to browsers through SignalR connections held by the web process. With a backplane, an event sent by any process (another web server, or queue:work) reaches them. Presence channel members are kept in the default cache store, so set that to redis as well. In config/Broadcasting.cs:

csharp
public override object Values() => new
{
    driver = "redis",
    connection = "default",
    path = "/broadcasting",
};

Interacting With Redis ​

The Redis facade returns the StackExchange.Redis IDatabase of a connection, with its prefix applied:

csharp
await Redis.Connection().StringIncrementAsync("page-views");
var leaders = await Redis.Connection("default").SortedSetRangeByRankAsync("leaderboard", 0, 9, Order.Descending);

Running Redis Locally ​

shell
docker run -d --name redis -p 6379:6379 redis:7

The framework's Redis tests run when the environment variable DOTBLAZE_TEST_REDIS holds the host (CI starts a Redis service for them).

Complete Example: Redis Round-Trip ​

Install DotBlaze.Redis, start the local Redis container above, and set REDIS_HOST=127.0.0.1 in the Blog template's .env. Its DatabaseConfig already contains the named Redis connections.

csharp
// app/Commands/RedisDemo.cs
using DotBlaze;

namespace Blog.Commands;

public class RedisDemo : Command
{
    public override string Signature => "demo:redis";
    public override async Task<int> Handle()
    {
        var redis = Redis.Connection("default");
        var key = $"docs:round-trip:{Guid.NewGuid():N}";
        try
        {
            await redis.StringSetAsync(key, "hello", TimeSpan.FromMinutes(1));
            var value = await redis.StringGetAsync(key);
            if (value.ToString() != "hello")
                throw new InvalidOperationException("Redis round-trip failed.");
            Line(value.ToString());
            return 0;
        }
        finally
        {
            await redis.KeyDeleteAsync(key);
        }
    }
}

Run dotblaze demo:redis; expected output: hello. This is a real integration check, not a fake. It writes one uniquely named expiring key and removes it afterwards. Connection failures propagate; verify host, port, ACL credentials, TLS, and network access rather than interpreting an unavailable server as a cache miss. Queue reservations remain at-least-once, so jobs still need idempotent side effects.