| name | redis |
| description | Implements Redis caching, session management, and distributed coordination for the Sorcha platform.
Use when: Adding caching layers, token revocation, rate limiting, SignalR backplane, or distributed state.
|
| allowed-tools | Read, Edit, Write, Glob, Grep, Bash, mcp__context7__resolve-library-id, mcp__context7__query-docs |
Redis Skill
Sorcha uses Redis via StackExchange.Redis for caching, token revocation tracking, rate limiting, and distributed coordination. All services share a single Redis instance managed by .NET Aspire with circuit breaker resilience.
Quick Start
Aspire Configuration
var redis = builder.AddRedis("redis")
.WithRedisCommander();
var blueprintService = builder.AddProject<Projects.Sorcha_Blueprint_Service>()
.WithReference(redis);
Cache Store Usage
public class MyService(ICacheStore cache)
{
public async Task<User?> GetUserAsync(string id)
{
return await cache.GetAsync<User>($"user:{id}");
}
public async Task SetUserAsync(User user)
{
await cache.SetAsync($"user:{user.Id}", user, TimeSpan.FromMinutes(15));
}
}
Direct IConnectionMultiplexer
public class TokenService(IConnectionMultiplexer redis)
{
private readonly IDatabase _db = redis.GetDatabase();
public async Task TrackTokenAsync(string userId, string jti)
{
await _db.SetAddAsync($"auth:user_tokens:{userId}", jti);
}
}
Key Concepts
| Concept | Usage | Example |
|---|
| Key prefix | Namespace isolation | sorcha:, auth: |
| TTL | Automatic expiration | TimeSpan.FromMinutes(15) |
| Circuit breaker | Graceful degradation | Breaks after 5 failures |
| Sets | Token tracking | SetAddAsync, SetMembersAsync |
| Counters | Rate limiting | StringIncrementAsync |
Common Patterns
Rate Limiting
When: Protecting auth endpoints from brute force.
public async Task<bool> IsRateLimitedAsync(string identifier)
{
var key = $"auth:failed:{identifier}";
var count = await _db.StringIncrementAsync(key);
if (count == 1)
await _db.KeyExpireAsync(key, TimeSpan.FromSeconds(60));
return count >= MaxFailedAttempts;
}
Token Revocation
When: Invalidating JWTs before expiration.
public async Task RevokeTokenAsync(string jti, DateTimeOffset expiresAt)
{
var ttl = expiresAt - DateTimeOffset.UtcNow;
if (ttl > TimeSpan.Zero)
await _db.StringSetAsync($"auth:revoked:{jti}", "revoked", ttl);
}
IDistributedCache is a separate registration from IConnectionMultiplexer
builder.AddRedisClient("redis") wires up IConnectionMultiplexer and IDatabase — sufficient for direct StackExchange.Redis use. It does NOT register Microsoft.Extensions.Caching.Distributed.IDistributedCache. Code that depends on IDistributedCache will throw InvalidOperationException: Unable to resolve service for type 'IDistributedCache' at the first request — not at boot.
Add the distributed-cache overlay explicitly, sharing the same connection name:
builder.AddRedisClient("redis");
builder.AddRedisDistributedCache("redis");
Requires the Aspire.StackExchange.Redis.DistributedCaching package alongside the base Aspire.StackExchange.Redis.
Unit-test trap that masks this: tests that construct the SUT directly with new MemoryDistributedCache(Options.Create(new MemoryDistributedCacheOptions())) bypass the DI graph entirely. The test passes; the container fails at runtime. If a service under test depends on IDistributedCache, also add a thin DI-startup test (or an integration test against a TestHost) that asserts the registration exists — not just one that mocks past it. Feature 124 PR #697 was the cautionary tale: 6 unit tests with MemoryDistributedCache green, production 500'd on every endpoint call.
See Also
Related Skills
- aspire - Redis resource configuration and service discovery
- jwt - Token revocation integration
- signalr - Redis backplane for scale-out
- docker - Redis container configuration
Documentation Resources
Fetch latest Redis and StackExchange.Redis documentation with Context7.
How to use Context7:
- Use
mcp__context7__resolve-library-id to search for "StackExchange.Redis" or "redis"
- Prefer website documentation (
/websites/redis_io) for concepts
- Use
/stackexchange/stackexchange.redis for .NET-specific patterns
Library IDs:
/stackexchange/stackexchange.redis - .NET client (344 snippets)
/websites/redis_io - Redis concepts (29k+ snippets)
Recommended Queries:
- "Connection pooling multiplexer patterns best practices"
- "Caching patterns TTL expiration strategies"
- "Pub/Sub patterns distributed systems"