Skip to content

Integration Redis Extension

aryehcitron@gmail.com edited this page Nov 7, 2026 · 23 revisions

The Kronikol.Extensions.Redis package adds Redis cache operation tracking to your test diagrams with cache hit/miss visualization. Instead of invisible Redis operations, your sequence diagrams show classified operations like Get (Hit): redis://db0/user:123 or Set: redis://db0/session:abc.

Can't change the service? Integration TcpTap Extension is the out-of-process alternative: a byte-for-byte TCP tee with a RESP2/RESP3 decoder that you point the service's Redis client at. It compiles the same classifier source as this page's extension, so Get (Hit): redis://db0/user:123 comes out identical — no code change, no client library, any language.

Using a shared library or abstraction layer? If your code doesn't use StackExchange.Redis IDatabase directly — e.g. it goes through a shared caching library, IDistributedCache, or custom abstraction — this extension won't be able to intercept the underlying calls. See Tracking Custom Dependencies for alternative approaches including RequestResponseLogger.LogPair(), TrackingProxy<T>, and MessageTracker.


How It Works

RedisTrackingDatabase is a DispatchProxy-based decorator around StackExchange.Redis's IDatabase that intercepts Redis operations, classifies each one (Get, Set, Delete, HashGet, ListPush, etc.), determines cache hit/miss for read operations, then logs it to RequestResponseLogger with a human-readable label.

Because it logs to the same RequestResponseLogger as the standard TestTrackingMessageHandler, Redis operations appear alongside your HTTP API calls, Cosmos DB operations, and SQL queries in the same sequence diagram — showing the complete flow from test → API → Redis.

Cache Hit/Miss Detection

The key differentiator of this extension is automatic cache hit/miss visualization:

  • Hit: A StringGet, HashGet, or similar read operation returned a non-null value
  • Miss: A read operation returned RedisValue.Null (key doesn't exist or field doesn't exist)
  • None: Write operations (Set, Delete, Expire, etc.) — hit/miss doesn't apply

This information is encoded directly in the diagram labels: Get (Hit), Get (Miss), HashGet (Hit), HashGet (Miss), etc.

Note: The request arrow (before the response is received) shows the operation without hit/miss (e.g. Get), since the result is not yet known. The response arrow shows the full label with hit/miss (e.g. Get (Hit) or Get (Miss)).


Install

dotnet add package Kronikol.Extensions.Redis

Client versions

The package asks for StackExchange.Redis 2.6.80 or later, so a suite can pin whichever 2.x from 2.6.80 its application ships with. The package's own suite runs on the newest 2.x, and in CI on 2.6.80 as well. A project that takes the client only through this package resolves 2.6.80; reference the client yourself for a newer one. The floor is 2.6.80 because it is the first release past GHSA-rxg9-xrhp-64gj, a critical advisory against the System.Drawing.Common 5.0.0 that earlier releases bring; the suite passes from 2.2.50.

Verbosity Levels

The extension supports three verbosity levels that control how much detail appears in the diagrams:

Level Method shown URI shown Request content Response content
Raw Redis command name (GET, SET, etc.) redis://host:port/db/key Full value Full value
Detailed Classified label (Get (Hit), Set) redis://db0/mykey Full value Full value
Summarised Classified label (Get (Hit), Set) redis://db0/ None None

The default is Detailed.

Diagram Label Examples

Operation Result Raw Detailed Summarised
StringGet("user:123") → "John" Hit GET Get (Hit) Get (Hit)
StringGet("user:999") → null Miss GET Get (Miss) Get (Miss)
StringSet("user:123", "John") — SET Set Set
KeyDelete("user:123") — DEL Delete Delete
HashGet("user:123", "name") → "John" Hit HGET HashGet (Hit) HashGet (Hit)
HashGet("user:123", "missing") → null Miss HGET HashGet (Miss) HashGet (Miss)
HashSet("user:123", entries) — HSET HashSet HashSet
ListLeftPush("queue", "msg") — LPUSH ListPush ListPush
SetAdd("tags", "redis") — SADD SetAdd SetAdd
StringIncrement("counter") → 42 — INCR Increment Increment
KeyExpire("key", 5min) — EXPIRE Expire Expire
Publish("channel", "msg") — PUBLISH Publish Publish

URI Examples by Verbosity

Verbosity Example URI
Raw redis://myredis.cache.windows.net:6380/0/user:123
Detailed redis://db0/user:123
Summarised redis://db0/

Classified Operations

The classifier recognises these Redis operations:

Operation Redis Commands Cache Hit/Miss
Get GET, GETDEL, GETSET, GETEX, MGET ✅ Yes
Set SET, SETEX, SETNX, PSETEX, MSET, MSETNX, APPEND, GETRANGE ❌ None
Delete DEL, UNLINK ❌ None
KeyExists EXISTS ❌ None
Expire EXPIRE, PEXPIRE, EXPIREAT, PEXPIREAT, PERSIST ❌ None
Increment INCR, INCRBY, INCRBYFLOAT ❌ None
Decrement DECR, DECRBY ❌ None
HashGet HGET, HMGET ✅ Yes
HashGetAll HGETALL ❌ None
HashSet HSET, HMSET, HSETNX ❌ None
HashDelete HDEL ❌ None
ListPush LPUSH, RPUSH, LPUSHX, RPUSHX ❌ None
ListRange LRANGE ❌ None
SetAdd SADD ❌ None
SetMembers SMEMBERS ❌ None
Publish PUBLISH ❌ None
Other Any unrecognised command ❌ None

In Summarised mode, Other operations are silently skipped.


Setup

Option A: DI Decoration (Recommended — Zero Prod Changes)

v2.27.14+ Use the built-in DI extension method. It automatically resolves IHttpContextAccessor from DI and handles the dual-resolution test identity pattern.

// In your test's ConfigureTestServices:
services.AddRedisTestTracking(options =>
{
    options.ServiceName = "Redis";
    options.CallerName = "My API";
    options.Verbosity = RedisTrackingVerbosity.Detailed;
    options.CurrentTestInfoFetcher = CurrentTestInfo.Fetcher;
});

This uses DecorateAll<IDatabase> internally — it finds all existing IDatabase registrations, replaces each with a RedisTrackingDatabase proxy wrapper, and preserves the original service lifetime. No-op if no IDatabase registrations exist. No changes to production code required.

Option B: IDatabase Decorator

The simplest approach — wrap your IDatabase with the tracking decorator using the WithRedisTestTracking() extension method:

using Kronikol.Extensions.Redis;

var options = new RedisTrackingDatabaseOptions
{
    ServiceName = "Redis",
    CallerName = "My API",
    Verbosity = RedisTrackingVerbosity.Detailed,
    CurrentTestInfoFetcher = CurrentTestInfo.Fetcher
};

// Wrap any IDatabase instance
IDatabase db = multiplexer.GetDatabase();
IDatabase trackedDb = db.WithRedisTestTracking(options);

// Use trackedDb everywhere — all operations are tracked
var value = trackedDb.StringGet("user:123"); // logs Get (Hit) or Get (Miss)
trackedDb.StringSet("user:123", "John");     // logs Set

Option C: Extension Method on IConnectionMultiplexer

Shorthand to get a tracked database directly from a multiplexer:

IDatabase db = multiplexer.GetTrackedDatabase(options);

This calls multiplexer.GetDatabase(db) internally and wraps the result.

Option D: Manual DI Registration

For ASP.NET Core integration tests using WebApplicationFactory, replace the IDatabase registration:

builder.ConfigureTestServices(services =>
{
    services.AddSingleton<IDatabase>(sp =>
    {
        var multiplexer = sp.GetRequiredService<IConnectionMultiplexer>();
        return multiplexer.GetTrackedDatabase(new RedisTrackingDatabaseOptions
        {
            ServiceName = "Redis",
            CallerName = "My API",
            Verbosity = RedisTrackingVerbosity.Detailed,
            CurrentTestInfoFetcher = CurrentTestInfo.Fetcher
        });
    });
});

Option E: With a Fake/In-Memory Redis

If you use a fake Redis implementation for unit tests, wrap the fake's IDatabase:

var fakeDb = GetFakeRedisDatabase(); // your in-memory fake
var trackedDb = fakeDb.WithRedisTestTracking(options);

The tracking decorator wraps any IDatabase — it doesn't care whether the underlying implementation is a real Redis connection, an emulator, or a fake.


CurrentTestInfoFetcher by Framework

Every framework package provides a CurrentTestInfo static class with a Fetcher property. The syntax is identical regardless of framework — just ensure you have the correct using directive:

CurrentTestInfoFetcher = CurrentTestInfo.Fetcher
Framework using directive
xUnit v3 using Kronikol.xUnit3;
xUnit v2 using Kronikol.xUnit2;
NUnit 4 using Kronikol.NUnit4;
MSTest using Kronikol.MSTest;
TUnit using Kronikol.TUnit;
LightBDD using Kronikol.LightBDD;
ReqNRoll using Kronikol.ReqNRoll;
BDDfy using Kronikol.BDDfy.xUnit3;

Tracked vs Untracked Methods

The following IDatabase method families are tracked (produce diagram entries):

  • String: StringGet, StringSet, StringIncrement, StringDecrement, StringGetDelete, StringGetSet, StringAppend, StringGetRange, StringGetWithExpiry, StringGetSetExpiry, StringGetLease, StringSetAndGet, StringSetRange, StringDelete
  • Key: KeyDelete, KeyExists, KeyExpire, KeyPersist
  • Hash: HashGet, HashGetAll, HashGetLease, HashSet, HashDelete
  • Increment / Decrement / KeyExists: HashIncrement (classified as Increment), HashDecrement (classified as Decrement), HashExists (classified as KeyExists) — these IDatabase.Hash* methods are mapped to internal classification codes (INCR, DECR, EXISTS) and appear in diagrams under those operation names, not as Hash operations
  • List: ListLeftPush, ListRightPush, ListLeftPop, ListRightPop, ListRange, ListRightPopLeftPush, ListMove
  • Set: SetAdd, SetMembers, SetRemove, SetPop, SetContains
  • Pub/Sub: Publish

All other IDatabase methods (Geo, HyperLogLog, Sorted Set, Stream, Script, Lock, Vector, metadata queries like KeyTimeToLive, StringLength, HashLength, etc.) pass through to the inner IDatabase without any tracking. This keeps diagrams focused on the cache interactions that matter for understanding application behaviour.

Both sync and async variants of all tracked methods are supported (StringGet/StringGetAsync, KeyDelete/KeyDeleteAsync, etc.).


Architecture

Test Code
    │
    ▼
IDatabase (RedisTrackingDatabase DispatchProxy)
    │
    ├── MapMethodToCommand() → classify operation
    ├── Log request to RequestResponseLogger (label without hit/miss)
    │
    ▼
IDatabase (real or fake inner implementation)
    │
    ├── Execute Redis command
    │
    ▼
RedisTrackingDatabase
    │
    ├── DetermineHasResult() → detect hit/miss from return value
    ├── Log response to RequestResponseLogger (label WITH hit/miss)
    │
    ▼
RequestResponseLogger → PlantUmlCreator → ReportGenerator

DispatchProxy Design

Unlike the CosmosDB extension (which uses a DelegatingHandler) or the EF Core extension (which uses a DbCommandInterceptor), the Redis extension uses .NET's DispatchProxy because StackExchange.Redis has no built-in interception infrastructure. DispatchProxy dynamically implements the IDatabase interface at runtime, routing all method calls through a single Invoke method. This means:

  1. Every IDatabase method is automatically forwarded — no missing methods, no compilation errors when StackExchange.Redis adds new methods
  2. Only mapped methods produce tracking logs — the command mapping table controls what gets tracked
  3. Zero boilerplate — no need to implement 192+ interface methods manually

Configuration Reference

RedisTrackingDatabaseOptions

Property Type Default Description
ServiceName string "Redis" The name shown as the target participant in sequence diagrams
CallerName string "Caller" The name shown as the source participant
Verbosity RedisTrackingVerbosity Detailed Controls diagram detail level (Raw / Detailed / Summarised)
CurrentTestInfoFetcher Func<(string Name, string Id)>? null Delegate that returns the current test's name and unique ID
CurrentStepTypeFetcher Func<string?>? null Has no effect: nothing in the Redis package reads it (only the HTTP handler's option of the same name does). Its removal is a v6 question
HttpContextAccessor IHttpContextAccessor? null Optional — enables dual-resolution of test identity from HTTP headers. Auto-resolved by DI extensions (v2.26.3+). See [[HTTP Tracking Setup › Dual-Resolution Test Identity (v2.23.0+)
SetupVerbosity RedisTrackingVerbosity? null Verbosity override for the Setup phase. See Phase-Aware Tracking
ActionVerbosity RedisTrackingVerbosity? null Verbosity override for the Action phase. See Phase-Aware Tracking
TrackDuringSetup bool true When false, tracking is suppressed during Setup. See Phase-Aware Tracking
TrackDuringAction bool true When false, tracking is suppressed during Action. See Phase-Aware Tracking

v2.23.0+ Dual-Resolution: RedisTracker accepts an optional IHttpContextAccessor? httpContextAccessor constructor parameter for resolving test identity from HTTP request headers when running inside the SUT's request pipeline. v2.26.3+: Set HttpContextAccessor on RedisTrackingDatabaseOptions instead — the tracker reads it automatically. See HTTP Tracking Setup › Dual-Resolution Test Identity (v2.23.0+) for details.

Extension Methods

Method On Type Description
WithRedisTestTracking(options) IDatabase Wraps the database with a tracking proxy
GetTrackedDatabase(options, db) IConnectionMultiplexer Gets a database from the multiplexer and wraps it
AddRedisConnectionMultiplexerTracking(options) IServiceCollection Decorates IConnectionMultiplexer registrations so all databases obtained from DI are automatically tracked

RedisTrackingConnectionMultiplexer

RedisTrackingConnectionMultiplexer is a DispatchProxy wrapping IConnectionMultiplexer so that GetDatabase() automatically returns RedisTrackingDatabase instances. This is useful when production code resolves IConnectionMultiplexer from DI and calls GetDatabase() itself, rather than resolving IDatabase directly.

AddRedisConnectionMultiplexerTracking() DI Extension

The AddRedisConnectionMultiplexerTracking() extension method decorates existing IConnectionMultiplexer registrations with RedisTrackingConnectionMultiplexer, so every IDatabase obtained via GetDatabase() is automatically tracked — no production code changes required.

services.AddRedisConnectionMultiplexerTracking(options =>
{
    options.ServiceName = "Redis";
    options.CurrentTestInfoFetcher = CurrentTestInfo.Fetcher;
});

This is an alternative to AddRedisTestTracking() (Option A) for codebases that resolve IConnectionMultiplexer rather than IDatabase from DI.


Invocation Validation

RedisTracker implements ITrackingComponent and auto-registers with TrackingComponentRegistry on construction. At report generation time, unused components are automatically detected and surfaced as console warnings and in the diagnostic report (when DiagnosticMode=true). This never throws or fails tests — if the tracker is unused, it usually means an untracked IDatabase instance is being used.

See Diagnostics and Debugging for full details on the TrackingComponentRegistry API.

A call that fails

A command that throws, on the synchronous and the asynchronous paths, is answered with the exception's type (!RedisConnectionException) and its message chain in error (5.34.3, #232), where it was left with no answer. The exception reaches the caller as the client threw it: before 5.34.3 a synchronous call threw it inside a TargetInvocationException, which a catch (RedisConnectionException) missed, and so did a command on a path the tracker does not record. History's older rules still read the call as the release before recorded it, so a suite that upgrades reads no change there (Cross-Run History).

Home · 🔍 Search this wiki Full-text search across every page. The “Pages” list above matches page and heading names, not page content.


Demo


Getting Started

Common Tasks

Integration Guides

Uninstrumentable / polyglot backends

Extensions

Configuration

Features

Reference

Clone this wiki locally