Redis

suggest change

Redis is an in-memory data store. It keeps keys mapped to strings, hashes, lists, sets and sorted sets, executes each command atomically, and answers in well under a millisecond. Typical uses are caching, sessions, counters, rate limiting, leaderboards, queues, distributed locks and pub/sub messaging between services. Valkey is an open-source fork with the same protocol, and everything below works with it too.

The standard .NET client is StackExchange.Redis. It's fully async, thread-safe, and pipelines commands from many threads over one connection.

Examples use C# 14 / .NET 10 as file-based programs (dotnet run app.cs) and expect a Redis server on localhost:6379. The quickest way to get one is Docker:

docker run -d --name redis -p 6379:6379 redis:8

In a project, add the package with dotnet add package StackExchange.Redis.

Connecting

The central type is ConnectionMultiplexer. Create it once when your program starts and share it everywhere. It's expensive to create, thread-safe, and reconnects by itself when the connection drops. Creating one per request is the most common performance bug with this library.

#:package StackExchange.Redis@3.4.5
using StackExchange.Redis;

// one multiplexer per application, shared by all threads
await using ConnectionMultiplexer redis =
    await ConnectionMultiplexer.ConnectAsync("localhost:6379");

IDatabase db = redis.GetDatabase();   // cheap, don't cache it

TimeSpan latency = await db.PingAsync();
Console.WriteLine($"connected: {redis.IsConnected}, ping < 1s: {latency < TimeSpan.FromSeconds(1)}");

await db.StringSetAsync("greeting", "Hello, Redis");
string? greeting = await db.StringGetAsync("greeting");
Console.WriteLine(greeting);
connected: True, ping < 1s: True
Hello, Redis

GetDatabase() returns a lightweight IDatabase wrapper. Call it whenever you need it, there's no reason to store it. Every command has a synchronous and an Async version. Prefer the async ones in servers so threads aren't blocked waiting for the network.

Connection options

A connection string is a list of endpoints followed by name=value options. The same settings are available as properties of ConfigurationOptions:

#:package StackExchange.Redis@3.4.5
using StackExchange.Redis;

// connection string form: endpoints first, then comma-separated options
var fromString = ConfigurationOptions.Parse(
    "localhost:6379,abortConnect=false,connectTimeout=5000,syncTimeout=2000");

// the same thing in code
var options = new ConfigurationOptions
{
    EndPoints = { { "localhost", 6379 } },
    AbortOnConnectFail = false,   // keep retrying in the background
    ConnectTimeout = 5000,        // ms
    SyncTimeout = 2000,           // ms, for synchronous calls
    AsyncTimeout = 2000,          // ms, for async calls
    ClientName = "inventory-api", // shows up in CLIENT LIST
    // Password = "secret", User = "app", Ssl = true,
};
Console.WriteLine(fromString.ToString());

await using var redis = await ConnectionMultiplexer.ConnectAsync(options);
redis.ConnectionFailed += (_, e) => Console.WriteLine($"lost {e.EndPoint}: {e.FailureType}");
redis.ConnectionRestored += (_, e) => Console.WriteLine($"restored {e.EndPoint}");

IDatabase db = redis.GetDatabase();
string? name = (string?)await db.ExecuteAsync("CLIENT", "GETNAME");
Console.WriteLine(name);
localhost:6379,syncTimeout=2000,connectTimeout=5000,abortConnect=False
inventory-api

The settings worth knowing:

Keep the connection string out of the source code. Read it from configuration or environment variables, see Configuration files.

ExecuteAsync sends any command, including ones the library doesn't have a method for. The result is a RedisResult you cast to the expected type.

Strings, counters and expiration

The simplest Redis value is a string, which can hold text, a number or binary data up to 512 MB. In the API, keys are RedisKey and values are RedisValue. Both convert implicitly from string, numbers and byte[], and RedisValue converts back with a cast:

#:package StackExchange.Redis@3.4.5
using StackExchange.Redis;

await using var redis = await ConnectionMultiplexer.ConnectAsync("localhost:6379");
IDatabase db = redis.GetDatabase();
await db.KeyDeleteAsync(["user:1:name", "page:views", "session:abc", "price"]);

// SET / GET
await db.StringSetAsync("user:1:name", "Alice");
RedisValue name = await db.StringGetAsync("user:1:name");
Console.WriteLine($"{name} hasValue={name.HasValue}");

RedisValue missing = await db.StringGetAsync("user:999:name");
Console.WriteLine($"missing: IsNull={missing.IsNull} as string={(string?)missing ?? "(null)"}");

// RedisValue converts to and from numbers, strings, byte[]
await db.StringSetAsync("price", 19.99);
double price = (double)await db.StringGetAsync("price");
Console.WriteLine(price * 2);

// atomic counters
await db.StringIncrementAsync("page:views");
await db.StringIncrementAsync("page:views", 10);
long views = await db.StringDecrementAsync("page:views");
Console.WriteLine($"views={views}");

// expiration
await db.StringSetAsync("session:abc", "user-1", expiry: TimeSpan.FromMinutes(30));
TimeSpan? ttl = await db.KeyTimeToLiveAsync("session:abc");
Console.WriteLine($"ttl ~ {Math.Round(ttl!.Value.TotalMinutes)} min");
await db.KeyExpireAsync("session:abc", TimeSpan.FromSeconds(1));
await Task.Delay(1100);
Console.WriteLine($"exists after expiry: {await db.KeyExistsAsync("session:abc")}");
Console.WriteLine($"no ttl: {await db.KeyTimeToLiveAsync("user:1:name") is null}");

// SET only if the key doesn't exist (NX) / only if it exists (XX)
bool first = await db.StringSetAsync("user:1:name", "Bob", when: When.NotExists);
bool update = await db.StringSetAsync("user:1:name", "Alicia", when: When.Exists);
Console.WriteLine($"NX={first} XX={update} now={await db.StringGetAsync("user:1:name")}");

// several keys in one round trip
await db.StringSetAsync([new("k1", "a"), new("k2", "b")]);
RedisValue[] values = await db.StringGetAsync(["k1", "k2", "k3"]);
Console.WriteLine(string.Join(", ", values.Select(v => v.IsNull ? "(nil)" : v.ToString())));
Alice hasValue=True
missing: IsNull=True as string=(null)
39.98
views=10
ttl ~ 30 min
exists after expiry: False
no ttl: True
NX=False XX=True now=Alicia
a, b, (nil)

Things to know:

Use : in key names to create namespaces like user:1:name. It's only a convention, but tools like RedisInsight group keys by it.

Hashes

A hash stores field/value pairs under one key. It's a natural fit for objects, and you can read or update a single field without touching the rest:

#:package StackExchange.Redis@3.4.5
using StackExchange.Redis;

await using var redis = await ConnectionMultiplexer.ConnectAsync("localhost:6379");
IDatabase db = redis.GetDatabase();
await db.KeyDeleteAsync("product:42");

await db.HashSetAsync("product:42",
[
    new HashEntry("name", "Keyboard"),
    new HashEntry("price", 49.5),
    new HashEntry("stock", 12),
]);

string? productName = await db.HashGetAsync("product:42", "name");
long stock = await db.HashDecrementAsync("product:42", "stock", 3);
Console.WriteLine($"{productName}: stock={stock}");

RedisValue[] some = await db.HashGetAsync("product:42", ["name", "price", "color"]);
Console.WriteLine(string.Join(" | ", some.Select(v => v.IsNull ? "(nil)" : (string)v!)));

Console.WriteLine($"has color: {await db.HashExistsAsync("product:42", "color")}");
await db.HashSetAsync("product:42", "color", "black");
await db.HashDeleteAsync("product:42", "price");

HashEntry[] all = await db.HashGetAllAsync("product:42");
foreach (HashEntry e in all)
    Console.WriteLine($"  {e.Name} = {e.Value}");

// map to a class
Product p = FromHash(all);
Console.WriteLine(p);

static Product FromHash(HashEntry[] entries)
{
    var d = entries.ToDictionary(e => e.Name.ToString(), e => e.Value);
    return new Product(
        (string)d["name"]!,
        d.TryGetValue("price", out var price) ? (decimal)price : 0m,
        (int)d["stock"]);
}

record Product(string Name, decimal Price, int Stock);
Keyboard: stock=9
Keyboard | 49.5 | (nil)
has color: False
  name = Keyboard
  stock = 9
  color = black
Product { Name = Keyboard, Price = 0, Stock = 9 }

HashIncrementAsync and HashDecrementAsync are atomic, just like string counters. Use a hash when you update individual fields. When you always read and write the whole object, storing it as a JSON string (shown below) is simpler.

Lists, sets and sorted sets

#:package StackExchange.Redis@3.4.5
using StackExchange.Redis;

await using var redis = await ConnectionMultiplexer.ConnectAsync("localhost:6379");
IDatabase db = redis.GetDatabase();
await db.KeyDeleteAsync(["jobs", "recent", "tags:a", "tags:b", "leaderboard"]);

// list as a queue: push on the left, pop from the right
await db.ListLeftPushAsync("jobs", ["resize", "email", "report"]);
Console.WriteLine($"queued: {await db.ListLengthAsync("jobs")}");
RedisValue job = await db.ListRightPopAsync("jobs");
Console.WriteLine($"next job: {job}");

// list as a capped "recent items" log
foreach (var page in new[] { "/", "/about", "/blog", "/contact", "/blog/1" })
{
    await db.ListLeftPushAsync("recent", page);
    await db.ListTrimAsync("recent", 0, 2);     // keep newest 3
}
RedisValue[] recent = await db.ListRangeAsync("recent", 0, -1);
Console.WriteLine($"recent: {string.Join(", ", recent)}");

// sets: unique members, set algebra
await db.SetAddAsync("tags:a", ["csharp", "redis", "dotnet"]);
await db.SetAddAsync("tags:b", ["redis", "go"]);
bool added = await db.SetAddAsync("tags:a", "redis");
Console.WriteLine($"added duplicate: {added}");
Console.WriteLine($"contains go: {await db.SetContainsAsync("tags:a", "go")}");
RedisValue[] both = await db.SetCombineAsync(SetOperation.Intersect, "tags:a", "tags:b");
RedisValue[] any = await db.SetCombineAsync(SetOperation.Union, "tags:a", "tags:b");
Console.WriteLine($"intersect: {string.Join(", ", both)}; union count: {any.Length}");

// sorted sets: members ordered by score
await db.SortedSetAddAsync("leaderboard",
[
    new SortedSetEntry("alice", 120),
    new SortedSetEntry("bob", 95),
    new SortedSetEntry("carol", 150),
    new SortedSetEntry("dave", 80),
]);
await db.SortedSetIncrementAsync("leaderboard", "bob", 40);

SortedSetEntry[] top = await db.SortedSetRangeByRankWithScoresAsync(
    "leaderboard", 0, 2, Order.Descending);
foreach (var (e, i) in top.Select((e, i) => (e, i)))
    Console.WriteLine($"  #{i + 1} {e.Element} {e.Score}");

long? rank = await db.SortedSetRankAsync("leaderboard", "alice", Order.Descending);
double? score = await db.SortedSetScoreAsync("leaderboard", "alice");
Console.WriteLine($"alice: rank {rank + 1}, score {score}");

RedisValue[] mid = await db.SortedSetRangeByScoreAsync("leaderboard", 90, 130);
Console.WriteLine($"score 90..130: {string.Join(", ", mid)}");
queued: 3
next job: resize
recent: /blog/1, /contact, /blog
added duplicate: False
contains go: False
intersect: redis; union count: 4
  #1 carol 150
  #2 bob 135
  #3 alice 120
alice: rank 3, score 120
score 90..130: alice

ListLeftPushAsync with several values pushes them one by one, so the last one ends up at the head. Ranks are 0-based, and negative indexes count from the end: ListRangeAsync(key, 0, -1) returns the whole list.

Pipelining and batches

Most of the time spent on a Redis command is the network round trip, not the work on the server. StackExchange.Redis pipelines automatically: if you start several commands without awaiting each one, they're all written to the socket immediately and the replies come back in order.

#:package StackExchange.Redis@3.4.5
using System.Diagnostics;
using StackExchange.Redis;

await using var redis = await ConnectionMultiplexer.ConnectAsync("localhost:6379");
IDatabase db = redis.GetDatabase();

// 1. awaiting one command at a time: 1000 round trips
var sw = Stopwatch.StartNew();
for (int i = 0; i < 1000; i++)
    await db.StringSetAsync($"item:{i}", i);
Console.WriteLine($"sequential: {sw.ElapsedMilliseconds} ms");

// 2. start all commands, then await them: pipelined automatically
sw.Restart();
var tasks = new List<Task>();
for (int i = 0; i < 1000; i++)
    tasks.Add(db.StringSetAsync($"item:{i}", i));
await Task.WhenAll(tasks);
Console.WriteLine($"pipelined: {sw.ElapsedMilliseconds} ms");

// 3. fire-and-forget: don't wait for a reply at all
db.StringIncrement("stats:hits", flags: CommandFlags.FireAndForget);

// 4. IBatch: commands are sent together, but not atomically
IBatch batch = db.CreateBatch();
Task<RedisValue> a = batch.StringGetAsync("item:1");
Task<RedisValue> b = batch.StringGetAsync("item:2");
batch.Execute();
Console.WriteLine($"batch: {await a} {await b}");
sequential: 73 ms
pipelined: 3 ms
batch: 1 2

That's on localhost, where a round trip is tiny. Over a real network with 0.5 ms latency the sequential loop takes over half a second, while the pipelined version is barely slower than here.

Transactions

CreateTransaction() wraps commands in MULTI / EXEC. They're queued and then run as one unit: no other client's command runs in the middle.

You can't read a value inside the transaction and act on it, because the results only exist after ExecuteAsync. Instead, add conditions. The transaction checks them on the server and aborts (ExecuteAsync returns false) if any of them is false. That's optimistic concurrency: read, decide, commit only if nothing changed, otherwise retry.

#:package StackExchange.Redis@3.4.5
using StackExchange.Redis;

await using var redis = await ConnectionMultiplexer.ConnectAsync("localhost:6379");
IDatabase db = redis.GetDatabase();
await db.StringSetAsync("balance:alice", 100);
await db.StringSetAsync("balance:bob", 20);

// MULTI/EXEC: both commands run together, nothing runs in between
ITransaction tx = db.CreateTransaction();
_ = tx.StringIncrementAsync("balance:alice", -30);
_ = tx.StringIncrementAsync("balance:bob", 30);
bool committed = await tx.ExecuteAsync();
Console.WriteLine($"committed={committed} alice={await db.StringGetAsync("balance:alice")} bob={await db.StringGetAsync("balance:bob")}");

Console.WriteLine(await Transfer(db, "balance:alice", "balance:bob", 50));
Console.WriteLine(await Transfer(db, "balance:alice", "balance:bob", 50));
Console.WriteLine($"alice={await db.StringGetAsync("balance:alice")} bob={await db.StringGetAsync("balance:bob")}");

// optimistic concurrency: the transaction only commits if the
// balance is still what we read; otherwise read again and retry
static async Task<string> Transfer(IDatabase db, string from, string to, long amount)
{
    for (int attempt = 1; attempt <= 5; attempt++)
    {
        RedisValue current = await db.StringGetAsync(from);
        long balance = (long)current;
        if (balance < amount)
            return $"insufficient funds ({balance} < {amount})";

        ITransaction tx = db.CreateTransaction();
        tx.AddCondition(Condition.StringEqual(from, current));
        _ = tx.StringDecrementAsync(from, amount);
        _ = tx.StringIncrementAsync(to, amount);
        if (await tx.ExecuteAsync())
            return $"moved {amount} on attempt {attempt}";
    }
    return "gave up: too much contention";
}
committed=True alice=70 bob=50
moved 50 on attempt 1
insufficient funds (20 < 50)
alice=20 bob=100

Don't await the individual tasks of a transaction before calling ExecuteAsync. They only complete after the transaction executes, so awaiting them first would hang. Other conditions include Condition.KeyNotExists, Condition.HashEqual, Condition.ListLengthLessThan and Condition.SortedSetLengthEqual.

Lua scripts

When the logic is more complex, send a Lua script. Redis runs the whole script atomically, and it's often simpler and faster than a transaction with retries. Keys are passed in KEYS, other arguments in ARGV:

#:package StackExchange.Redis@3.4.5
using StackExchange.Redis;

await using var redis = await ConnectionMultiplexer.ConnectAsync("localhost:6379");
IDatabase db = redis.GetDatabase();
await db.KeyDeleteAsync("rate:user:7");

// fixed-window rate limiter: INCR + EXPIRE must happen atomically
const string Script = """
    local count = redis.call('INCR', KEYS[1])
    if count == 1 then
        redis.call('EXPIRE', KEYS[1], ARGV[1])
    end
    return count
    """;

for (int i = 1; i <= 5; i++)
{
    long count = (long)await db.ScriptEvaluateAsync(Script,
        keys: ["rate:user:7"], values: [60]);
    Console.WriteLine($"request {i}: {(count <= 3 ? "allowed" : "rejected")} ({count})");
}

// LuaScript lets you use named @parameters bound from an object
LuaScript setIfHigher = LuaScript.Prepare("""
    local cur = tonumber(redis.call('GET', @key) or '-1')
    if tonumber(@value) > cur then
        redis.call('SET', @key, @value)
        return 1
    end
    return 0
    """);

await db.KeyDeleteAsync("highscore");
foreach (int v in new[] { 10, 5, 42 })
{
    var r = (int)await db.ScriptEvaluateAsync(setIfHigher,
        new { key = (RedisKey)"highscore", value = v });
    Console.WriteLine($"offer {v}: {(r == 1 ? "stored" : "ignored")}");
}
Console.WriteLine($"highscore = {await db.StringGetAsync("highscore")}");
request 1: allowed (1)
request 2: allowed (2)
request 3: allowed (3)
request 4: rejected (4)
request 5: rejected (5)
offer 10: stored
offer 5: ignored
offer 42: stored
highscore = 42

The library caches scripts by their SHA1 and sends EVALSHA, so the script text doesn't go over the wire every time. With LuaScript.Prepare, @name placeholders are filled from the properties of the object you pass. Pass keys as RedisKey so the library knows which arguments are keys, which matters for Redis Cluster.

Keep scripts short: while one runs, the server doesn't execute anything else.

Caching objects as JSON

The most common use of Redis is a cache in front of a slow database or API. With the cache-aside pattern, you look in Redis first, and on a miss you load the data, store it with an expiration, and return it. Here's a small helper that stores objects as JSON with System.Text.Json (see JSON handling):

#:package StackExchange.Redis@3.4.5
#:property PublishAot=false
using System.Text.Json;
using StackExchange.Redis;

await using var redis = await ConnectionMultiplexer.ConnectAsync("localhost:6379");
var cache = new RedisCache(redis.GetDatabase());
await redis.GetDatabase().KeyDeleteAsync("user:7");

for (int i = 0; i < 2; i++)
{
    User u = await cache.GetOrSetAsync("user:7", TimeSpan.FromMinutes(5),
        () => LoadUserFromDatabase(7));
    Console.WriteLine($"{u.Name} roles={string.Join(",", u.Roles)}");
}
Console.WriteLine(await redis.GetDatabase().StringGetAsync("user:7"));

await cache.RemoveAsync("user:7");   // invalidate after an update
Console.WriteLine($"after remove: {await redis.GetDatabase().KeyExistsAsync("user:7")}");

static async Task<User> LoadUserFromDatabase(int id)
{
    Console.WriteLine($"  (loading user {id} from database)");
    await Task.Delay(50);   // pretend this is slow
    return new User(id, "Alice", ["admin", "dev"]);
}

record User(int Id, string Name, string[] Roles);

class RedisCache(IDatabase db)
{
    static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);

    public async Task<T> GetOrSetAsync<T>(string key, TimeSpan ttl, Func<Task<T>> factory)
    {
        RedisValue cached = await db.StringGetAsync(key);
        if (cached.HasValue)
            return JsonSerializer.Deserialize<T>((byte[])cached!, Json)!;

        T value = await factory();
        byte[] bytes = JsonSerializer.SerializeToUtf8Bytes(value, Json);
        await db.StringSetAsync(key, bytes, ttl);
        return value;
    }

    public Task RemoveAsync(string key) => db.KeyDeleteAsync(key);
}
  (loading user 7 from database)
Alice roles=admin,dev
Alice roles=admin,dev
{"id":7,"name":"Alice","roles":["admin","dev"]}
after remove: False

The #:property PublishAot=false line is needed because file-based programs default to Native AOT, where reflection-based JsonSerializer is disabled. In a normal project you don't need it.

Always set an expiration on cache entries. Then stale data fixes itself eventually and the cache can't grow forever. Also configure the server with maxmemory and an eviction policy such as allkeys-lru when Redis is used only as a cache.

IDistributedCache and HybridCache

ASP.NET Core has standard caching abstractions with a Redis implementation in Microsoft.Extensions.Caching.StackExchangeRedis:

#:package Microsoft.Extensions.Caching.StackExchangeRedis@10.0.13
#:package Microsoft.Extensions.Caching.Hybrid@10.11.0
#:package Microsoft.Extensions.DependencyInjection@10.0.13
#:property PublishAot=false
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Hybrid;
using Microsoft.Extensions.DependencyInjection;

var services = new ServiceCollection();
services.AddStackExchangeRedisCache(o =>
{
    o.Configuration = "localhost:6379";
    o.InstanceName = "myapp:";            // prefix for every key
});
services.AddHybridCache(o =>
{
    o.DefaultEntryOptions = new HybridCacheEntryOptions
    {
        Expiration = TimeSpan.FromMinutes(5),          // Redis (L2)
        LocalCacheExpiration = TimeSpan.FromMinutes(1) // in-process (L1)
    };
});
using ServiceProvider sp = services.BuildServiceProvider();

// IDistributedCache: plain strings or byte[]
IDistributedCache dist = sp.GetRequiredService<IDistributedCache>();
await dist.SetStringAsync("motd", "Deploy at 5pm",
    new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(1) });
Console.WriteLine(await dist.GetStringAsync("motd"));

// HybridCache: typed values, serialization and stampede protection built in
HybridCache cache = sp.GetRequiredService<HybridCache>();
await cache.RemoveAsync("weather:krakow");
for (int i = 0; i < 2; i++)
{
    Forecast f = await cache.GetOrCreateAsync("weather:krakow", async ct =>
    {
        Console.WriteLine("  (calling weather service)");
        await Task.Delay(100, ct);
        return new Forecast("Krakow", 14.5);
    });
    Console.WriteLine(f);
}

record Forecast(string City, double TempC);
Deploy at 5pm
  (calling weather service)
Forecast { City = Krakow, TempC = 14.5 }
Forecast { City = Krakow, TempC = 14.5 }

In Redis the keys are myapp:motd and myapp:weather:krakow. IDistributedCache stores each value in a hash together with its expiration settings, so read entries through the same API instead of with StringGetAsync. For a pure in-process cache, see MemoryCache.

Pub/Sub

Publish/subscribe sends messages to everyone currently subscribed to a channel. Delivery is fire-and-forget: subscribers that are offline miss the message, and nothing is stored. That's good for notifications such as "invalidate your local cache" or "config changed". For durable queues use lists or Redis Streams.

#:package StackExchange.Redis@3.4.5
using StackExchange.Redis;

await using var redis = await ConnectionMultiplexer.ConnectAsync("localhost:6379");
ISubscriber sub = redis.GetSubscriber();

// handler style: called on a thread-pool thread for each message
var orders = RedisChannel.Literal("orders");
await sub.SubscribeAsync(orders, (channel, message) =>
    Console.WriteLine($"[handler] {channel}: {message}"));

// queue style: messages are processed in order, one at a time
ChannelMessageQueue queue = await sub.SubscribeAsync(RedisChannel.Pattern("events:*"));
var consumer = Task.Run(async () =>
{
    await foreach (ChannelMessage m in queue)
        Console.WriteLine($"[queue]   {m.Channel}: {m.Message}");
});

long receivers = await sub.PublishAsync(orders, "order 1001 created");
Console.WriteLine($"delivered to {receivers} subscriber(s)");
await sub.PublishAsync(RedisChannel.Literal("events:login"), "alice");
await sub.PublishAsync(RedisChannel.Literal("events:logout"), "bob");

await Task.Delay(200);
await queue.UnsubscribeAsync();   // ends the await foreach loop
await sub.UnsubscribeAsync(orders);
await consumer;
Console.WriteLine("done");
delivered to 1 subscriber(s)
[handler] orders: order 1001 created
[queue]   events:login: alice
[queue]   events:logout: bob
done

Messages are handled on other threads, so the order of lines can vary. Notes:

Distributed locks

When several instances of a service must not do the same work at once, take a lock in Redis. LockTakeAsync runs SET key value NX PX ttl, and LockReleaseAsync deletes the key only if it still contains your value, so you can't release a lock someone else took after yours expired:

#:package StackExchange.Redis@3.4.5
using StackExchange.Redis;

await using var redis = await ConnectionMultiplexer.ConnectAsync("localhost:6379");
IDatabase db = redis.GetDatabase();

// simulate 3 workers that all want to run the same nightly job
var workers = Enumerable.Range(1, 3).Select(id => RunJob(db, $"worker-{id}"));
await Task.WhenAll(workers);

static async Task RunJob(IDatabase db, string workerId)
{
    const string lockKey = "lock:nightly-report";
    // SET lock:nightly-report <workerId> NX PX 30000
    if (!await db.LockTakeAsync(lockKey, workerId, TimeSpan.FromSeconds(30)))
    {
        Console.WriteLine($"{workerId}: busy, held by {await db.LockQueryAsync(lockKey)}");
        return;
    }
    try
    {
        Console.WriteLine($"{workerId}: got the lock, working...");
        await Task.Delay(300);
    }
    finally
    {
        // deletes the key only if it still holds our value
        bool released = await db.LockReleaseAsync(lockKey, workerId);
        Console.WriteLine($"{workerId}: released={released}");
    }
}
worker-1: got the lock, working...
worker-3: busy, held by worker-1
worker-2: busy, held by worker-1
worker-1: released=True

Use a unique value per owner (a machine name plus a GUID in real code), and pick an expiration longer than the work takes, or extend it with LockExtendAsync. The expiration makes sure a crashed process doesn't hold the lock forever. A lock on a single Redis server is fine for avoiding duplicate work. It's not a strong guarantee when correctness depends on it, because failover to a replica can lose the lock.

Finding keys with SCAN

The KEYS pattern command blocks the server while it walks the whole keyspace, so never use it in production. IServer.KeysAsync uses SCAN, which walks the keys in small pages:

#:package StackExchange.Redis@3.4.5
using StackExchange.Redis;

await using var redis = await ConnectionMultiplexer.ConnectAsync("localhost:6379");
IDatabase db = redis.GetDatabase();
for (int i = 0; i < 250; i++)
    _ = db.StringSetAsync($"temp:{i}", i, flags: CommandFlags.FireAndForget);

// KEYS-like enumeration needs a specific server; it uses SCAN under the hood
IServer server = redis.GetServer(redis.GetEndPoints()[0]);

int count = 0;
var batch = new List<RedisKey>();
await foreach (RedisKey key in server.KeysAsync(pattern: "temp:*", pageSize: 100))
{
    count++;
    batch.Add(key);
    if (batch.Count == 100)
    {
        await db.KeyDeleteAsync(batch.ToArray());
        batch.Clear();
    }
}
if (batch.Count > 0)
    await db.KeyDeleteAsync(batch.ToArray());

Console.WriteLine($"found and deleted {count} keys");
Console.WriteLine($"left: {server.Keys(pattern: "temp:*").Count()}");

// type of a key, and memory-friendly scanning inside a big hash
await db.HashSetAsync("big", [new("a", 1), new("b", 2), new("c", 3)]);
Console.WriteLine(await db.KeyTypeAsync("big"));
await foreach (HashEntry e in db.HashScanAsync("big", pattern: "*", pageSize: 2))
    Console.Write($"{e.Name}={e.Value} ");
Console.WriteLine();
found and deleted 250 keys
left: 0
Hash
a=1 b=2 c=3

Key enumeration runs against a specific server, so you get an IServer from an endpoint. In a cluster, repeat it for every primary. HashScanAsync, SetScanAsync and SortedSetScanAsync iterate over large collections the same way, without loading everything at once.

Errors

Connection problems and command errors throw different exceptions:

#:package StackExchange.Redis@3.4.5
using StackExchange.Redis;

// nothing listens on port 6390
try
{
    await ConnectionMultiplexer.ConnectAsync("localhost:6390,connectTimeout=1000");
}
catch (RedisConnectionException ex)
{
    Console.WriteLine($"{ex.GetType().Name}: {ex.FailureType}");
}

await using var redis = await ConnectionMultiplexer.ConnectAsync("localhost:6379");
IDatabase db = redis.GetDatabase();
await db.StringSetAsync("counter-name", "not a number");
try
{
    await db.StringIncrementAsync("counter-name");
}
catch (RedisServerException ex)
{
    Console.WriteLine($"{ex.GetType().Name}: {ex.Message}");
}
try
{
    await db.ListLeftPushAsync("counter-name", "x");
}
catch (RedisServerException ex)
{
    Console.WriteLine($"{ex.GetType().Name}: {ex.Message}");
}
RedisConnectionException: UnableToConnect
RedisServerException: ERR value is not an integer or out of range
RedisServerException: WRONGTYPE Operation against a key holding the wrong kind of value

Using Redis in ASP.NET Core

Register the multiplexer as a singleton and inject it, or inject IDistributedCache / HybridCache as shown above:

#:sdk Microsoft.NET.Sdk.Web
#:package StackExchange.Redis@3.4.5
using StackExchange.Redis;

var builder = WebApplication.CreateBuilder(args);
string redisConn = builder.Configuration.GetConnectionString("Redis") ?? "localhost:6379";
builder.Services.AddSingleton<IConnectionMultiplexer>(
    _ => ConnectionMultiplexer.Connect(redisConn));

var app = builder.Build();

app.MapGet("/visits", async (IConnectionMultiplexer redis) =>
{
    long n = await redis.GetDatabase().StringIncrementAsync("visits");
    return $"visit #{n}";
});

app.Run();
$ curl http://localhost:5000/visits
visit #1
$ curl http://localhost:5000/visits
visit #2

The connection string goes in appsettings.json under ConnectionStrings:Redis. See dependency injection for more about service lifetimes.

Tips

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents