StackExchange.Redis.Extensions
StackExchange.Redis.Extensions is a library that extends StackExchange.Redis, making it easier to work with Redis in .NET applications. It wraps the base library with serialization, connection pooling, and higher-level APIs so you can store and retrieve complex objects without writing boilerplate code.
AI-Ready: This library provides an llms.txt file for AI coding assistants and a Claude Code plugin for configuration, scaffolding, and troubleshooting.
claude plugin add imperugo/StackExchange.Redis.Extensions
Then use /redis-configure, /redis-scaffold, or /redis-diagnose in Claude Code.
Features
- Store and retrieve complex .NET objects with automatic serialization
- Multiple serialization providers (System.Text.Json, Newtonsoft, Protobuf, MsgPack, MemoryPack, and more)
- Connection pooling with LeastLoaded and RoundRobin strategies
- Pub/Sub messaging with typed handlers
- Hash operations with per-field expiry (Redis 7.4+)
- GeoSpatial indexes (GEOADD, GEOSEARCH, GEODIST, etc.)
- Redis Streams with consumer group support
- Set, List, and Sorted Set operations with Set Combine (union, intersect, diff)
- HyperLogLog for probabilistic cardinality estimation
- Distributed locking with IAsyncDisposable auto-release
- Bitmap operations for analytics and feature flags
- Lua scripting for atomic server-side operations
- Key tagging and search
- Key management (rename, type, dump/restore)
- Atomic counters (StringIncrement/StringDecrement)
- Transparent compression (GZip, Brotli, LZ4, Snappy, Zstandard)
IDistributedCache adapter (Microsoft-compatible Hash schema)
- ASP.NET Core Health Check for connection pool monitoring
- Azure Managed Identity support
- ASP.NET Core integration with DI and .NET 8+ Keyed Services
- Multiple named Redis instances with
[FromKeyedServices] support
- OpenTelemetry integration
- .NET Standard 2.1, .NET 8, .NET 9, .NET 10
Architecture
graph TB
App[Your Application] --> DI[ASP.NET Core DI]
DI --> Factory[IRedisClientFactory]
Factory --> Client1[IRedisClient - Default]
Factory --> Client2[IRedisClient - Named]
Client1 --> DB[IRedisDatabase]
DB --> Pool[Connection Pool Manager]
Pool --> C1[Connection 1]
Pool --> C2[Connection 2]
Pool --> C3[Connection N...]
DB --> Ser[ISerializer]
Ser --> Comp[CompressedSerializer?]
Comp --> Inner[System.Text.Json / Newtonsoft / ...]
C1 --> Redis[(Redis Server)]
C2 --> Redis
C3 --> Redis
Loading
Quick Start
1. Install packages
dotnet add package StackExchange.Redis.Extensions.Core
dotnet add package StackExchange.Redis.Extensions.System.Text.Json
dotnet add package StackExchange.Redis.Extensions.AspNetCore
2. Configure in appsettings.json
{
"Redis": {
"Password": "",
"AllowAdmin": true,
"Ssl": false,
"ConnectTimeout": 5000,
"SyncTimeout": 5000,
"Database": 0,
"Hosts": [
{ "Host": "localhost", "Port": 6379 }
],
"PoolSize": 5,
"IsDefault": true
}
}
3. Register in DI
var redisConfig = builder.Configuration.GetSection("Redis").Get<RedisConfiguration>();
builder.Services.AddStackExchangeRedisExtensions<SystemTextJsonSerializer>(redisConfig);
4. Use it
public class MyService(IRedisDatabase redis)
{
public async Task Example()
{
// Store an object
await redis.AddAsync("user:1", new User { Name = "Ugo", Age = 38 });
// Retrieve it
var user = await redis.GetAsync<User>("user:1");
// Store with expiry
await redis.AddAsync("session:abc", sessionData, TimeSpan.FromMinutes(30));
// Bulk operations
var items = new[]
{
Tuple.Create("key1", "value1"),
Tuple.Create("key2", "value2"),
};
await redis.AddAllAsync(items, TimeSpan.FromHours(1));
// Search keys
var keys = await redis.SearchKeysAsync("user:*");
}
}
NuGet Packages
Core
| Package |
Description |
NuGet |
| Core |
Core library with abstractions and implementations |
|
| AspNetCore |
ASP.NET Core DI integration and middleware |
|
Serializers (pick one)
| Package |
Description |
NuGet |
| System.Text.Json |
Recommended for most scenarios |
|
| Newtonsoft |
JSON.NET for legacy compatibility |
|
| MemoryPack |
High-performance binary (net7.0+) |
|
| MsgPack |
MessagePack binary format |
|
| Protobuf |
Protocol Buffers |
|
| Utf8Json |
UTF-8 native JSON |
|
Compressors (optional)
| Package |
Algorithm |
Best for |
NuGet |
| Compression.LZ4 |
LZ4 |
Lowest latency |
|
| Compression.Snappier |
Snappy |
Low latency |
|
| Compression.ZstdSharp |
Zstandard |
Best ratio/speed |
|
| Compression.GZip |
GZip |
Wide compatibility |
|
| Compression.Brotli |
Brotli |
Best ratio for text |
|
Usage Examples
Hash Operations
// Set a hash field
await redis.HashSetAsync("user:1", "name", "Ugo");
await redis.HashSetAsync("user:1", "email", "ugo@example.com");
// Get a hash field
var name = await redis.HashGetAsync<string>("user:1", "name");
// Set with per-field expiry (Redis 7.4+)
await redis.HashSetWithExpiryAsync("user:1", "session", sessionData, TimeSpan.FromMinutes(30));
// Query field TTL
var ttl = await redis.HashFieldGetTimeToLiveAsync("user:1", new[] { "session" });
GeoSpatial
// Add locations
await redis.GeoAddAsync("restaurants", new[]
{
new GeoEntry(13.361389, 38.115556, "Pizzeria Da Michele"),
new GeoEntry(15.087269, 37.502669, "Trattoria del Corso"),
new GeoEntry(12.496366, 41.902782, "Da Enzo al 29"),
});
// Distance between two places
var km = await redis.GeoDistanceAsync("restaurants",
"Pizzeria Da Michele", "Trattoria del Corso", GeoUnit.Kilometers);
// Search within 200km of a point
var nearby = await redis.GeoSearchAsync("restaurants", 13.361389, 38.115556,
new GeoSearchCircle(200, GeoUnit.Kilometers),
count: 10, order: Order.Ascending);
Redis Streams
// Publish typed events
await redis.StreamAddAsync("orders", "payload", new Order { Id = 1, Total = 99.99m });
// Consumer group workflow
await redis.StreamCreateConsumerGroupAsync("orders", "processors");
var entries = await redis.StreamReadGroupAsync("orders", "processors", "worker-1");
foreach (var entry in entries)
{
// Process the message
await redis.StreamAcknowledgeAsync("orders", "processors", entry.Id!);
}
Pub/Sub
// Subscribe to typed messages
await redis.SubscribeAsync<OrderEvent>("orders:new", async order =>
{
Console.WriteLine($"New order: {order.Id}");
});
// Publish
await redis.PublishAsync("orders:new", new OrderEvent { Id = 42 });
Atomic Counters
// Increment/decrement with long (default step = 1)
var views = await redis.StringIncrementAsync("page:views");
var stock = await redis.StringDecrementAsync("product:123:stock");
// Custom step
await redis.StringIncrementAsync("stats:bytes", 1024);
// Double precision
await redis.StringIncrementAsync("account:balance", 49.99);
Set Operations