Bundle: redb-route / redb.Route.Redis (redb.Route.Redis.txt), 15 files
Snapshot: development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Index: https://redbase.app/src/dev-2026-12-06/redb-route/_index.txt
====
Path: redb-route/redb.Route.Redis/AssemblyInfo.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Redis/AssemblyInfo.cs
----
// redb_Route_Redis - placeholder for build
Path: redb-route/redb.Route.Redis/Extensions/ServiceCollectionExtensions.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Redis/Extensions/ServiceCollectionExtensions.cs
----
using Microsoft.Extensions.DependencyInjection;
using redb.Route.Extensions;
namespace redb.Route.Redis;
///
/// Extension methods for registering the Redis transport in a DI container.
///
public static class ServiceCollectionExtensions
{
///
/// Registers the in the route context so that
/// redis: URIs are resolved.
///
///
/// services.AddRedbRoute(route =>
/// {
/// route.Services.AddRedbRouteRedis();
/// route.AddRouteBuilder<MyRoutes>();
/// });
///
///
///
public static IServiceCollection AddRedbRouteRedis(this IServiceCollection services)
{
// IRouteContextConfigurator is applied by RouteHostedService at startup --
// the correct registration hook (a lazy marker singleton never fires).
services.AddRouteComponent();
return services;
}
}
Path: redb-route/redb.Route.Redis/Fluent/RedisDsl.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Redis/Fluent/RedisDsl.cs
----
using System.Text;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Expressions;
namespace redb.Route.Redis;
///
/// Fluent API for Redis endpoints.
///
/// // Key-value
/// .To(Redis.Set("user:123").Connection("redis-server:6379").Ttl(300))
/// .From(Redis.Subscribe("events.*").UsePattern())
///
/// // Streams
/// .From(Redis.XRead("order-stream").ConsumerGroup("workers").ConsumerName("w1"))
/// .To(Redis.XAdd("audit-stream").StreamMaxLength(10000))
///
/// // Generic operation
/// .To(Redis.Command("LPUSH", "task-queue"))
///
///
public static class Redis
{
// ── Key-Value ─────────────────────────────────────────────────────
/// SET key to a value.
public static RedisBuilder Set(string key) => new("SET", key);
/// GET value by key.
public static RedisBuilder Get(string key) => new("GET", key);
/// DEL — delete a key.
public static RedisBuilder Del(string key) => new("DEL", key);
/// EXISTS — check if key exists.
public static RedisBuilder Exists(string key) => new("EXISTS", key);
/// EXPIRE — set TTL on a key.
public static RedisBuilder Expire(string key) => new("EXPIRE", key);
/// INCR — increment a key.
public static RedisBuilder Incr(string key) => new("INCR", key);
/// DECR — decrement a key.
public static RedisBuilder Decr(string key) => new("DECR", key);
/// SETNX — set value only if key does not exist.
public static RedisBuilder SetNx(string key) => new("SETNX", key);
// ── Pub/Sub ───────────────────────────────────────────────────────
/// PUBLISH messages to a channel.
public static RedisBuilder Publish(string channel) => new("PUBLISH", channel);
/// SUBSCRIBE to a channel (consumer).
public static RedisBuilder Subscribe(string channel) => new("SUBSCRIBE", channel);
/// PSUBSCRIBE to a pattern (consumer).
public static RedisBuilder PSubscribe(string pattern) => new("PSUBSCRIBE", pattern);
// ── Streams ───────────────────────────────────────────────────────
/// XADD — write to a stream.
public static RedisBuilder XAdd(string stream) => new("XADD", stream);
/// XREAD — read from a stream (consumer).
public static RedisBuilder XRead(string stream) => new("XREAD", stream);
/// XGROUP — manage consumer groups.
public static RedisBuilder XGroup(string stream) => new("XGROUP", stream);
// ── Lists ─────────────────────────────────────────────────────────
/// LPUSH — push to head of list.
public static RedisBuilder LPush(string key) => new("LPUSH", key);
/// RPUSH — push to tail of list.
public static RedisBuilder RPush(string key) => new("RPUSH", key);
/// LPOP — pop from head of list.
public static RedisBuilder LPop(string key) => new("LPOP", key);
/// RPOP — pop from tail of list.
public static RedisBuilder RPop(string key) => new("RPOP", key);
/// LLEN — get list length.
public static RedisBuilder LLen(string key) => new("LLEN", key);
/// LRANGE — get range from list.
public static RedisBuilder LRange(string key) => new("LRANGE", key);
// ── Generic ───────────────────────────────────────────────────────
/// Any Redis operation by name.
public static RedisBuilder Command(string operation, string key) => new(operation, key);
}
///
/// Fluent builder for Redis endpoint URIs.
///
public sealed class RedisBuilder
{
private readonly string _operation;
private readonly string _resource;
// Connection
private string? _connectionString;
private string? _database;
private string? _password;
private string? _connectionFactory;
// Common
private string? _ttl;
private bool _usePattern;
private bool? _transacted;
private string? _pollDelayMs;
private string? _command;
// Sorted set
private string? _score;
private string? _minScore;
private string? _maxScore;
// Hash
private string? _field;
// Range
private string? _start;
private string? _stop;
// Geo
private string? _longitude;
private string? _latitude;
private string? _member1;
private string? _member2;
private string? _geoUnit;
// Bit
private string? _offset;
private bool? _bit;
// Stream
private string? _consumerGroup;
private string? _consumerName;
private string? _streamMaxLength;
private bool? _streamApproximate;
private string? _streamReadCount;
private bool _batching;
private int? _maxBatchMessages;
private int? _pollTimeoutMs;
private int? _batchingIntervalMs;
private string? _streamBlockTimeMs;
private AckMode? _ackMode;
private string? _streamClaimMinIdleMs;
private string? _processingList;
private string? _streamStartPosition;
internal RedisBuilder(string operation, string resource)
{
_operation = operation;
_resource = resource;
}
// ── Connection ────────────────────────────────────────────────────
/// Redis connection string. Default "localhost:6379".
public RedisBuilder Connection(IExpression connectionString) { _connectionString = connectionString.ToTemplateString(); return this; }
/// Redis connection string (template string, supports ${...}). Default "localhost:6379".
public RedisBuilder Connection(string connectionString) { _connectionString = connectionString; return this; }
/// Database number. Default 0.
public RedisBuilder Database(int db) { _database = db.ToString(); return this; }
/// Database number from an expression.
public RedisBuilder Database(IExpression db) { _database = db.ToTemplateString(); return this; }
/// Redis password.
public RedisBuilder Password(IExpression password) { _password = password.ToTemplateString(); return this; }
/// Redis password (template string, supports ${...}).
public RedisBuilder Password(string password) { _password = password; return this; }
/// Use a named connection factory registered in DI.
public RedisBuilder ConnectionFactory(IExpression name) { _connectionFactory = name.ToTemplateString(); return this; }
/// Use a named connection factory registered in DI (template string, supports ${...}).
public RedisBuilder ConnectionFactory(string name) { _connectionFactory = name; return this; }
// ── Common ────────────────────────────────────────────────────────
/// TTL for SET operations in seconds. Default 0 (no expiry).
public RedisBuilder Ttl(int seconds) { _ttl = seconds.ToString(); return this; }
/// TTL from an expression.
public RedisBuilder Ttl(IExpression seconds) { _ttl = seconds.ToTemplateString(); return this; }
/// Use pattern matching for SUBSCRIBE/key operations.
public RedisBuilder UsePattern() { _usePattern = true; return this; }
/// Defers the operation to the commit of the enclosing .Transacted() block (transacted=true).
public RedisBuilder Transacted() { _transacted = true; return this; }
///
/// Sets transacted explicitly. false makes PUBLISH and XADD go out at once even inside a
/// .Transacted() block; left unset, they follow the block and every other write runs at once.
///
public RedisBuilder Transacted(bool value) { _transacted = value; return this; }
/// Poll delay for consumer operations in milliseconds. Default 1000.
public RedisBuilder PollDelay(int ms) { _pollDelayMs = ms.ToString(); return this; }
/// Poll delay from an expression.
public RedisBuilder PollDelay(IExpression ms) { _pollDelayMs = ms.ToTemplateString(); return this; }
/// Custom Redis command string.
public RedisBuilder CustomCommand(string cmd) { _command = cmd; return this; }
// ── Sorted Set ────────────────────────────────────────────────────
/// Score for sorted set operations.
public RedisBuilder Score(double score) { _score = score.ToString(System.Globalization.CultureInfo.InvariantCulture); return this; }
/// Score from an expression.
public RedisBuilder Score(IExpression score) { _score = score.ToTemplateString(); return this; }
/// Min score for range queries.
public RedisBuilder MinScore(double min) { _minScore = min.ToString(System.Globalization.CultureInfo.InvariantCulture); return this; }
/// Min score from an expression.
public RedisBuilder MinScore(IExpression min) { _minScore = min.ToTemplateString(); return this; }
/// Max score for range queries.
public RedisBuilder MaxScore(double max) { _maxScore = max.ToString(System.Globalization.CultureInfo.InvariantCulture); return this; }
/// Max score from an expression.
public RedisBuilder MaxScore(IExpression max) { _maxScore = max.ToTemplateString(); return this; }
// ── Hash ──────────────────────────────────────────────────────────
/// Hash field name.
public RedisBuilder Field(IExpression field) { _field = field.ToTemplateString(); return this; }
/// Hash field name (template string, supports ${...}).
public RedisBuilder Field(string field) { _field = field; return this; }
// ── Range ─────────────────────────────────────────────────────────
/// Start index for list/range operations.
public RedisBuilder Start(long start) { _start = start.ToString(); return this; }
/// Start index from an expression.
public RedisBuilder Start(IExpression start) { _start = start.ToTemplateString(); return this; }
/// Stop index for list/range operations.
public RedisBuilder Stop(long stop) { _stop = stop.ToString(); return this; }
/// Stop index from an expression.
public RedisBuilder Stop(IExpression stop) { _stop = stop.ToTemplateString(); return this; }
// ── Geo ───────────────────────────────────────────────────────────
/// Longitude for geo operations.
public RedisBuilder Longitude(double lon) { _longitude = lon.ToString(System.Globalization.CultureInfo.InvariantCulture); return this; }
/// Longitude from an expression.
public RedisBuilder Longitude(IExpression lon) { _longitude = lon.ToTemplateString(); return this; }
/// Latitude for geo operations.
public RedisBuilder Latitude(double lat) { _latitude = lat.ToString(System.Globalization.CultureInfo.InvariantCulture); return this; }
/// Latitude from an expression.
public RedisBuilder Latitude(IExpression lat) { _latitude = lat.ToTemplateString(); return this; }
/// First member for geo distance.
public RedisBuilder Member1(IExpression member) { _member1 = member.ToTemplateString(); return this; }
/// First member for geo distance (template string, supports ${...}).
public RedisBuilder Member1(string member) { _member1 = member; return this; }
/// Second member for geo distance.
public RedisBuilder Member2(IExpression member) { _member2 = member.ToTemplateString(); return this; }
/// Second member for geo distance (template string, supports ${...}).
public RedisBuilder Member2(string member) { _member2 = member; return this; }
/// Geo distance unit: m, km, mi, ft. Default "m".
public RedisBuilder GeoUnit(string unit) { _geoUnit = unit; return this; }
// ── Bit ───────────────────────────────────────────────────────────
/// Bit offset for GETBIT/SETBIT.
public RedisBuilder Offset(long offset) { _offset = offset.ToString(); return this; }
/// Bit offset from an expression.
public RedisBuilder Offset(IExpression offset) { _offset = offset.ToTemplateString(); return this; }
/// Bit value for SETBIT.
public RedisBuilder Bit(bool value) { _bit = value; return this; }
// ── Stream ────────────────────────────────────────────────────────
/// Consumer group name for stream operations.
public RedisBuilder ConsumerGroup(IExpression group) { _consumerGroup = group.ToTemplateString(); return this; }
/// Consumer group name for stream operations (template string, supports ${...}).
public RedisBuilder ConsumerGroup(string group) { _consumerGroup = group; return this; }
/// Consumer name within the group.
public RedisBuilder ConsumerName(IExpression name) { _consumerName = name.ToTemplateString(); return this; }
/// Consumer name within the group (template string, supports ${...}).
public RedisBuilder ConsumerName(string name) { _consumerName = name; return this; }
/// Max stream length (XADD with MAXLEN). Default 0 (unlimited).
public RedisBuilder StreamMaxLength(int max) { _streamMaxLength = max.ToString(); return this; }
/// Max stream length from an expression.
public RedisBuilder StreamMaxLength(IExpression max) { _streamMaxLength = max.ToTemplateString(); return this; }
/// Approximate MAXLEN trimming. Default true.
public RedisBuilder StreamApproximate(bool approx = true) { _streamApproximate = approx; return this; }
/// Number of entries to read per XREAD. Default 10.
public RedisBuilder StreamReadCount(int count) { _streamReadCount = count.ToString(); return this; }
/// Stream read count from an expression.
public RedisBuilder StreamReadCount(IExpression count) { _streamReadCount = count.ToTemplateString(); return this; }
/// Stream batch mode (batching=true): the route gets the entries as a List<IMessage>.
public RedisBuilder Batching() { _batching = true; return this; }
/// Largest number of entries in a batch (maxBatchMessages, default streamReadCount).
public RedisBuilder MaxBatchMessages(int max) { _maxBatchMessages = max; return this; }
/// Batch mode: the idle timeout in milliseconds, restarted by every entry (pollTimeoutMs, default 1000).
public RedisBuilder PollTimeoutMs(int ms) { _pollTimeoutMs = ms; return this; }
/// Batch mode: the hard limit in milliseconds since a batch's first entry (batchingIntervalMs).
public RedisBuilder BatchingIntervalMs(int ms) { _batchingIntervalMs = ms; return this; }
/// Block time in milliseconds for XREAD. Default 1000.
public RedisBuilder StreamBlockTime(int ms) { _streamBlockTimeMs = ms.ToString(); return this; }
/// Stream block time from an expression.
public RedisBuilder StreamBlockTime(IExpression ms) { _streamBlockTimeMs = ms.ToTemplateString(); return this; }
///
/// When a group consumer settles a stream entry: after the route succeeded (,
/// default, at-least-once) or on read with NOACK (, at-most-once).
///
public RedisBuilder AckMode(AckMode mode) { _ackMode = mode; return this; }
///
/// A group consumer claims entries of its group pending for at least milliseconds (a failed
/// one, or one a dead consumer left) and processes them again. Must exceed the longest time a route takes.
///
public RedisBuilder StreamClaimMinIdle(int ms) { _streamClaimMinIdleMs = ms.ToString(); return this; }
///
/// Where a stream consumer starts: unset, at the entries added from now on; "0" from the beginning; an entry id after
/// it. ">" only with a consumer group.
///
public RedisBuilder StreamStartPosition(string position) { _streamStartPosition = position; return this; }
///
/// A BLPOP/BRPOP consumer moves each item into while its route runs and removes it after
/// success; a failed item goes back to the queue, and a previous run's leftovers are returned at start
/// (at-least-once). One consumer per processing list.
///
public RedisBuilder ProcessingList(string key) { _processingList = key; return this; }
// ── Build ─────────────────────────────────────────────────────────
/// Builds the Redis endpoint URI string.
public string Build()
{
var sb = new StringBuilder();
sb.Append("redis:");
sb.Append(_operation);
sb.Append(':');
sb.Append(_resource);
var sep = '?';
void Append(string key, string value)
{
sb.Append(sep); sb.Append(key); sb.Append('=');
sb.Append(Uri.EscapeDataString(value)); sep = '&';
}
void AppendIf(string key, string? value) { if (value != null) Append(key, value); }
void AppendBool(string key, bool value) { if (value) Append(key, "true"); }
void AppendBoolExplicit(string key, bool? value)
{
if (value.HasValue) Append(key, value.Value.ToString().ToLowerInvariant());
}
// Connection
AppendIf("connectionString", _connectionString);
AppendIf("database", _database);
AppendIf("password", _password);
AppendIf("connectionFactory", _connectionFactory);
// Common
AppendIf("ttl", _ttl);
AppendBool("usePattern", _usePattern);
AppendBoolExplicit("transacted", _transacted);
AppendIf("pollDelayMs", _pollDelayMs);
AppendIf("command", _command);
// Sorted set
AppendIf("score", _score);
AppendIf("minScore", _minScore);
AppendIf("maxScore", _maxScore);
// Hash
AppendIf("field", _field);
// Range
AppendIf("start", _start);
AppendIf("stop", _stop);
// Geo
AppendIf("longitude", _longitude);
AppendIf("latitude", _latitude);
AppendIf("member1", _member1);
AppendIf("member2", _member2);
AppendIf("geoUnit", _geoUnit);
// Bit
AppendIf("offset", _offset);
AppendBoolExplicit("bit", _bit);
// Stream
AppendIf("consumerGroup", _consumerGroup);
AppendIf("consumerName", _consumerName);
AppendIf("streamMaxLength", _streamMaxLength);
AppendBoolExplicit("streamApproximate", _streamApproximate);
AppendIf("streamReadCount", _streamReadCount);
if (_batching) AppendIf("batching", "true");
AppendIf("maxBatchMessages", _maxBatchMessages?.ToString());
AppendIf("pollTimeoutMs", _pollTimeoutMs?.ToString());
AppendIf("batchingIntervalMs", _batchingIntervalMs?.ToString());
AppendIf("streamBlockTimeMs", _streamBlockTimeMs);
AppendIf("ackMode", _ackMode?.ToString().ToLowerInvariant());
AppendIf("streamClaimMinIdleMs", _streamClaimMinIdleMs);
AppendIf("processingList", _processingList);
AppendIf("streamStartPosition", _streamStartPosition);
return sb.ToString();
}
/// Implicit conversion to URI string.
public static implicit operator string(RedisBuilder b) => b.Build();
///
public override string ToString() => Build();
}
Path: redb-route/redb.Route.Redis/README.md
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Redis/README.md
----
# redb.Route.Redis
> Documentation and articles:
Redis transport for redb.Route. Pub/Sub, Streams, key-value, lists, sorted sets — every Redis data structure is reachable as an endpoint URI via StackExchange.Redis; the builder has factories for keys, Pub/Sub, streams and lists, and `Redis.Command(operation, key)` for the rest.
[](https://www.nuget.org/packages/redb.Route.Redis)
[](../../LICENSE)
## Installation
```bash
dotnet add package redb.Route.Redis
```
## Usage
### URI Format
```
redis:OPERATION:resource?connectionString=localhost:6379&...
```
The operation is the first path segment (`SET`, `GET`, `PUBLISH`, `SUBSCRIBE`, `XADD`, `XREAD`, `BLPOP`, …), the
resource — key, channel or stream — follows it: `redis:SET:session:42?ttl=300`, `redis:SUBSCRIBE:notifications`.
`redis:SET/session/42` works too. A parameter the endpoint cannot read (a misspelt option, a value of the wrong type) is
refused by name when the endpoint is created.
### Fluent DSL
```csharp
using redb.Route.Redis;
// Pub/Sub — subscribe
From(Redis.Subscribe("notifications").Connection("localhost:6379"))
.Log("Received: ${body}")
.To("direct://process");
// Pub/Sub — publish
From("direct://outbound")
.To(Redis.Publish("events").Connection("localhost:6379"));
// Streams — consumer group
From(Redis.XRead("order-stream")
.Connection("localhost:6379")
.ConsumerGroup("processors")
.ConsumerName("node-1")
.StreamReadCount(100))
.To("direct://handle");
// Key-Value
From("direct://cache")
.To(Redis.Set("session:user-123")
.Connection("localhost:6379")
.Ttl(3600));
// Lists
From("direct://enqueue")
.To(Redis.LPush("task-queue").Connection("localhost:6379"));
```
## Fluent Builder API
| Category | Methods |
|----------|---------|
| **Connection** | `.Connection()`, `.Database()`, `.Password()`, `.ConnectionFactory()` |
| **Key-Value** | `Redis.Set()`, `Redis.Get()`, `Redis.Del()`, `Redis.Exists()`, `Redis.Expire()`, `Redis.Incr()`, `Redis.Decr()`, `Redis.SetNx()` |
| **Pub/Sub** | `Redis.Publish()`, `Redis.Subscribe()`, `Redis.PSubscribe()` |
| **Streams** | `Redis.XAdd()`, `Redis.XRead()`, `Redis.XGroup()`, `.ConsumerGroup()`, `.ConsumerName()`, `.StreamMaxLength()`, `.StreamReadCount()`, `.StreamBlockTime()`, `.StreamStartPosition()`, `.AckMode()`, `.StreamClaimMinIdle()`, `.Batching()`, `.MaxBatchMessages()`, `.PollTimeoutMs()`, `.BatchingIntervalMs()` |
| **Lists** | `Redis.LPush()`, `Redis.RPush()`, `Redis.LPop()`, `Redis.RPop()`, `Redis.LLen()`, `Redis.LRange()`, `.ProcessingList()` |
| **Any operation** | `Redis.Command(operation, key)` — the factories above cover keys, Pub/Sub, streams and lists; every other operation (`HSET`, `ZADD`, `GEOADD`, `BLPOP`, …) is built with it |
| **Options** | `.Ttl()`, `.Transacted()`, `.PollDelay()`, `.UsePattern()`, `.CustomCommand()` |
> Most builder methods accept both constant values and `IExpression` for runtime resolution via the expression engine.
`Redis.Command(operation, key)` names an **operation** of this connector. The `COMMAND` operation is something else:
a raw Redis command, named with `.CustomCommand("PING")` (or the `redbRedis.Command` header) and run through
`ExecuteAsync`.
## Consumers and delivery
| Consumer | How it reads | A failed route |
|---|---|---|
| `SUBSCRIBE` / `PSUBSCRIBE` | Pub/Sub; `PSUBSCRIBE` subscribes to a pattern (`events.*`), `usePattern` makes `SUBSCRIBE` do so too | lost: Pub/Sub keeps nothing |
| `XREAD` / `XGROUP` with `consumerGroup` | `XREADGROUP`, acknowledged (`XACK`) after the route succeeded | stays pending; `streamClaimMinIdleMs` claims it again (`XAUTOCLAIM`) once it idled that long — a dead consumer's entries too |
| the same with `ackMode=auto` | `XREADGROUP NOACK`: delivered when read | not read again (at-most-once) |
| `XREAD` without a group | a position of its own, moved past every entry read; starts at the entries added from now on, or at `streamStartPosition` (`0` = from the beginning) | moved past, like a Kafka consumer without `breakOnFirstError` |
| `BLPOP` / `BRPOP` | polls `LPOP` / `RPOP` every `pollDelayMs` (a blocking pop would hold the connection the whole process shares) | lost (at-most-once) |
| the same with `processingList` | `LMOVE` into that list, removed after the route succeeded | back to the head of the queue and processed again; what a previous run left there is returned at start. One consumer per processing list |
`streamClaimMinIdleMs` must exceed the longest time a route takes: a slower route would have its entry claimed by another
consumer while it still works on it.
A consumer is ready when its route has started: the subscription, the consumer group and the XREAD position are set up
before `Start()` returns, so a message published right after the start is received. A Redis that does not answer at
start fails the route start with an error naming the consumer (`redis:SUBSCRIBE:orders cannot start ...`); an outage
after the start is ridden out by the client, which reconnects and subscribes again.
### Stream batch mode
`batching=true` on an `XREAD` or `XGROUP` consumer hands the route one exchange per batch of entries, by the batch
contract every broker of redb.Route follows. Apache Camel's Redis component has no batch consumer; the contract is
redb.Route's own, the same as for Kafka, RabbitMQ, IBM MQ, SQS, AMQP 1.0 and Service Bus.
- `maxBatchMessages` caps the batch (default `streamReadCount`); `pollTimeoutMs` (default 1000) sends a batch on once no
entry came for that long, restarted by every entry; `batchingIntervalMs` sends it on once that long has passed since
its first entry. Each read asks for at most `streamReadCount` entries. A batch option without `batching=true`, a value
out of range, and `batching=true` on Pub/Sub or a list consumer (nothing there acknowledges a batch) fail the start.
- The body is a `List`, one message per entry with the same body (its fields) and headers a single entry gets,
even for a batch of one; `redbRedis.Stream` is set on the batch message. The exchange is InOnly.
- With a group, every entry is acknowledged in one `XACK` after the route. A failed batch follows the rule of a failed
entry for every entry in it: it stays pending, and `streamClaimMinIdleMs` claims it again; the claimed entries are
taken into a batch before new ones. `streamClaimMinIdleMs` must exceed the time a batch takes from its first entry to
the end of its route. With `ackMode=auto` the entries are read with `NOACK`.
- Without a group the consumer's position moves past every entry it reads, a failed batch included, as in single mode.
- A batch half collected when the consumer stops is not run; with a group its entries stay pending.
## Transactions
Redis is a store first, so inside a route's `.Transacted()` block only the operations that announce work wait for the
commit:
- **`PUBLISH` and `XADD`** follow the block like a broker send: they run once the database has committed and are
dropped if the block rolls back. The entry id (`redbRedis.Stream.MessageId`) and the recipient count reach the exchange
headers after the commit. `.Transacted(false)` runs them at once.
- **Other writes** (`SET`, `INCR`, `SETNX`, lists, hashes, sets) run at once: they exist for their effect and their
result right now. `.Transacted()` holds one back until the commit; the route then does not get its result.
- **Reads and pops** (`GET`, `LPOP` and the like) exist for what they return and refuse `.Transacted()` when the route
starts.
A deferred operation is the same operation, run after the commit on a snapshot of the exchange taken at the step: the
same key, body, fields, headers and TTL. Outside a block, `.Transacted()` fails the step instead of losing the write.
## Part of
[redb.Route](../README.md) — ESB & EIP Framework for .NET
## Named connection factory
Keep credentials out of the route URI: register a factory in the context registry and
reference it by name. A set-but-unknown name fails loud at startup — a typo can never
silently fall back to inline URI parameters.
```csharp
context.AddToRegistry("prod", new RedisConnectionFactory
{
ConnectionString = "redis.internal:6379",
Password = secrets.RedisPassword,
});
// redis:GET:cache?connectionFactory=prod
```
## Tracing
On the `redb.Route` activity source (`AddSource("redb.Route")`), with `redb.route.endpoint`:
- **Consumer.** One `Consumer` span, `redis {operation} receive`, per routed pub/sub message, stream entry or list item,
with `messaging.system` = `redis` and the channel, stream or list as `messaging.destination.name`.
A Redis value carries no trace context (a stream entry's fields are its body), so the span is a root, never a child of
the activity the consumer loop inherited from whoever started the routes; nothing arriving opens none. A failed route
marks it an error; our own stop does not.
- **Producer.** One `Client` span per command, `redis {operation}`, with `db.system` = `redis`; an error when the
command fails, unless our own token cancelled it.
- `RouteEngineOptions.EnableTelemetry = false` opens neither span.
Path: redb-route/redb.Route.Redis/RedisComponent.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Redis/RedisComponent.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
namespace redb.Route.Redis;
///
/// Redis transport component for redb.Route.
/// Scheme: redis.
///
/// URI format (colon-path): redis:SET:mykey?ttl=300&connectionString=localhost:6379
/// URI format (standard): redis://SET/mykey?ttl=300
///
///
/// The first path segment is the .
/// The remaining segments form the resource key / channel / stream name.
///
///
public sealed partial class RedisComponent : ComponentBase
{
///
public override string Scheme => "redis";
///
public override IEndpoint CreateEndpoint(EndpointUri uri)
{
ArgumentNullException.ThrowIfNull(uri);
var options = new RedisEndpointOptions();
options.BindFromUri(uri.RawParameters);
options.Validate();
return new RedisEndpoint(uri, this, options);
}
}
Path: redb-route/redb.Route.Redis/RedisConnectionFactory.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Redis/RedisConnectionFactory.cs
----
using StackExchange.Redis;
using redb.Route.Core;
namespace redb.Route.Redis;
///
/// Connection factory for Redis. Register via DI or in the route registry
/// and reference by name in endpoint URIs (connectionFactory=myFactory).
///
public sealed class RedisConnectionFactory
{
/// Redis connection string (e.g., "localhost:6379" or "host1:6379,host2:6379").
[Sensitive]
public string ConnectionString { get; set; } = "localhost:6379";
/// Default database index (default: 0).
public int Database { get; set; }
/// Redis password (optional).
[Sensitive]
public string? Password { get; set; }
/// Redis ACL username (Redis 6+). Use together with Password for ACL authentication.
public string? User { get; set; }
/// Client name for identification in Redis INFO.
public string ClientName { get; set; } = "redb.Route";
// ── Timeouts ──
/// Connection timeout in milliseconds (default: 5000).
public int ConnectTimeout { get; set; } = 5000;
/// Synchronous operation timeout in milliseconds (default: 5000).
public int SyncTimeout { get; set; } = 5000;
/// Async operation timeout in milliseconds (default: 5000).
public int AsyncTimeout { get; set; } = 5000;
/// Number of connection retries (default: 3).
public int ConnectRetry { get; set; } = 3;
/// Keep-alive interval in seconds (default: 60).
public int KeepAlive { get; set; } = 60;
/// Abort on connection fail (default: false — allows reconnect).
public bool AbortOnConnectFail { get; set; }
/// Allow admin commands (default: false).
public bool AllowAdmin { get; set; }
// ── SSL ──
/// Enable SSL encryption.
public bool Ssl { get; set; }
/// SSL host for certificate validation.
public string? SslHost { get; set; }
/// SSL/TLS protocol versions (e.g. "Tls12", "Tls13"). Default = system default.
public string? SslProtocols { get; set; }
/// Enable certificate revocation checking (default: true).
public bool CheckCertificateRevocation { get; set; } = true;
// ── Advanced ──
/// Include detailed diagnostics in exceptions.
public bool IncludeDetailInExceptions { get; set; } = true;
/// Include performance counters in exceptions.
public bool IncludePerformanceCountersInExceptions { get; set; }
// ── Sentinel / Cluster / HA ──
/// Redis Sentinel service name. Required for Sentinel-based HA setups.
public string? ServiceName { get; set; }
/// Tie-breaker key for master detection in multi-master scenarios.
public string? TieBreaker { get; set; }
///
/// Reconnect retry policy: "exponential" or "linear" (default: exponential).
/// Controls backoff during reconnection attempts.
///
public string ReconnectRetryPolicy { get; set; } = "exponential";
/// Channel prefix for Pub/Sub (optional).
public string? ChannelPrefix { get; set; }
/// Creates from this factory's settings.
public ConfigurationOptions Build()
{
var config = ConfigurationOptions.Parse(ConnectionString);
config.DefaultDatabase = Database;
config.ClientName = ClientName;
config.ConnectTimeout = ConnectTimeout;
config.SyncTimeout = SyncTimeout;
config.AsyncTimeout = AsyncTimeout;
config.ConnectRetry = ConnectRetry;
config.KeepAlive = KeepAlive;
config.AbortOnConnectFail = AbortOnConnectFail;
config.AllowAdmin = AllowAdmin;
config.Ssl = Ssl;
config.IncludeDetailInExceptions = IncludeDetailInExceptions;
config.IncludePerformanceCountersInExceptions = IncludePerformanceCountersInExceptions;
config.CheckCertificateRevocation = CheckCertificateRevocation;
if (!string.IsNullOrEmpty(Password))
config.Password = Password;
if (!string.IsNullOrEmpty(User))
config.User = User;
if (!string.IsNullOrEmpty(SslHost))
config.SslHost = SslHost;
// A typo must not silently drop the protocol policy the admin pinned.
// Flags-enum: "Tls12, Tls13" is a valid value.
if (!string.IsNullOrEmpty(SslProtocols))
{
if (!Enum.TryParse(SslProtocols, true, out var protocols))
throw new ArgumentException(
$"Unknown value '{SslProtocols}' for 'sslProtocols'. Valid values: " +
"Tls12, Tls13 (comma-separated for several).");
config.SslProtocols = protocols;
}
if (!string.IsNullOrEmpty(ServiceName))
config.ServiceName = ServiceName;
if (!string.IsNullOrEmpty(TieBreaker))
config.TieBreaker = TieBreaker;
config.ReconnectRetryPolicy = ReconnectRetryPolicy?.Trim().ToLowerInvariant() switch
{
"linear" => new LinearRetry(ConnectTimeout),
_ => new ExponentialRetry(Math.Min(ConnectTimeout, 5000)),
};
if (!string.IsNullOrEmpty(ChannelPrefix))
config.ChannelPrefix = new RedisChannel(ChannelPrefix, RedisChannel.PatternMode.Literal);
return config;
}
}
Path: redb-route/redb.Route.Redis/RedisConsumer.Batch.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Redis/RedisConsumer.Batch.cs
----
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Batching;
using redb.Route.Core;
using StackExchange.Redis;
namespace redb.Route.Redis;
///
/// Batch mode of the Redis stream consumer (batching=true, XREAD/XGROUP), on the core batch contract: the
/// consumer collects up to maxBatchMessages entries, runs them through the route once and settles them once.
/// With a consumer group and ackMode=manual, success acknowledges every entry in one XACK; a failure applies the
/// rule of a failed single entry to each: it stays pending, and streamClaimMinIdleMs claims it again. Entries
/// pending for that long are taken into a batch first, as single mode processes them first. A batch the consumer stops
/// on stays pending too. Without a group the consumer's own position moves past every entry it reads, a failed batch
/// included, as single mode does.
///
public sealed partial class RedisConsumer
{
private async Task RunStreamBatchAsync(BatchOptions batch, CancellationToken pollCt, CancellationToken processingCt)
{
var db = _db!;
var streamName = _options.StreamName ?? _endpoint.Resource;
var reader = new StreamBatchReader(this, db, streamName);
var settlement = new StreamBatchSettlement(this, db, streamName);
var dispatcher = new BatchDispatcher(Processor, settlement, (entry, _) => StreamMessage(entry, streamName),
_endpoint.ScopeFactory, [RedisHeaders.Stream]);
var collector = new BatchCollector(batch, reader.ReceiveAsync);
Logger?.LogInformation(
"Redis stream batch consumer started: stream={Stream}, group={Group}, consumer={Consumer}, batch={Batch}",
streamName, _options.ConsumerGroup, reader.ConsumerName, batch.MaxMessages);
while (!pollCt.IsCancellationRequested)
{
CollectedBatch collected;
try
{
collected = await collector.CollectAsync(pollCt).ConfigureAwait(false);
}
catch (Exception ex) when (!pollCt.IsCancellationRequested)
{
Logger?.LogError(ex, "Error reading from Redis stream {Stream}", streamName);
try { await Task.Delay(_options.PollDelayMs * 5, pollCt).ConfigureAwait(false); }
catch (OperationCanceledException) { return; }
continue;
}
if (collected.Items.Count == 0)
continue;
if (collected.Interrupted)
{
await settlement.ReturnAsync(collected.Items, CancellationToken.None).ConfigureAwait(false);
return;
}
var items = collected.Items;
using var span = BatchDispatcher.StartSpan(
(_endpoint.Component as ComponentBase)?.Context, $"redis {_endpoint.OperationType} receive", "redis",
_endpoint.Uri.NormalizedKey, _endpoint.Resource, [], items.Count);
IncrementInflight();
try
{
if (await dispatcher.DispatchAsync(items, span, processingCt).ConfigureAwait(false) == BatchOutcome.Accepted)
ProcessedCount += items.Count;
}
catch (OperationCanceledException) when (processingCt.IsCancellationRequested)
{
return;
}
catch (Exception ex)
{
Logger?.LogError(ex, "Redis stream batch failed to settle on {Stream}", streamName);
}
finally
{
DecrementInflight();
}
}
}
///
/// One stream entry as a message, the same for a single entry and an element of a batch: the body the entry's fields
/// (raw strings), the stream, the id and each field as headers.
///
private static Message StreamMessage(StreamEntry entry, string streamName)
{
var fields = entry.Values.ToDictionary(nv => nv.Name.ToString(), nv => (object?)nv.Value.ToString());
var message = new Message(fields);
message.Headers[RedisHeaders.Stream] = streamName;
message.Headers[RedisHeaders.MessageId] = entry.Id.ToString();
message.Headers[RedisHeaders.MessageType] = "Stream";
message.Headers[RedisHeaders.Timestamp] = DateTimeOffset.UtcNow;
foreach (var nv in entry.Values)
message.Headers[$"{RedisHeaders.StreamFieldPrefix}{nv.Name}"] = nv.Value.ToString();
return message;
}
///
/// The transport's part of collection. With a group: first the entries pending for streamClaimMinIdleMs
/// (XAUTOCLAIM), then new ones (XREADGROUP >); without one, XREAD after the consumer's position, which moves past
/// every entry read. Redis is not asked to block (the connection is shared): an empty read waits
/// streamBlockTimeMs, at most the wait the collector allows.
///
private sealed class StreamBatchReader(RedisConsumer owner, IDatabase db, string streamName)
{
private RedisValue _position = owner._streamPosition;
private RedisValue _claimCursor = "0-0";
public string ConsumerName { get; } = owner._options.ConsumerName ?? Environment.MachineName;
public async ValueTask ReceiveAsync(List into, int max, TimeSpan wait, CancellationToken ct)
{
ct.ThrowIfCancellationRequested();
var options = owner._options;
var group = options.ConsumerGroup;
var count = Math.Min(max, options.StreamReadCount);
StreamEntry[] entries;
if (!string.IsNullOrEmpty(group))
{
if (options.StreamClaimMinIdleMs is { } minIdle)
{
var claimed = await db.StreamAutoClaimAsync(streamName, group, ConsumerName, minIdle, _claimCursor, count)
.ConfigureAwait(false);
_claimCursor = claimed.NextStartId;
var pending = claimed.ClaimedEntries.Where(e => !e.IsNull).ToArray();
if (pending.Length > 0)
{
into.AddRange(pending);
return pending.Length;
}
}
entries = await db.StreamReadGroupAsync(streamName, group, ConsumerName, StreamPosition.NewMessages, count,
noAck: options.AckMode == AckMode.Auto).ConfigureAwait(false);
}
else
{
entries = await db.StreamReadAsync(streamName, _position, count).ConfigureAwait(false);
if (entries.Length > 0)
_position = entries[^1].Id;
}
if (entries.Length > 0)
{
into.AddRange(entries);
return entries.Length;
}
var idle = TimeSpan.FromMilliseconds(options.StreamBlockTimeMs);
await Task.Delay(idle < wait ? idle : wait, ct).ConfigureAwait(false);
return 0;
}
}
///
/// The settlement of a stream batch: with a group and ackMode=manual, one XACK of every entry on success; a
/// failed or interrupted batch stays pending. Without a group, or with ackMode=auto, nothing is settled.
///
private sealed class StreamBatchSettlement(RedisConsumer owner, IDatabase db, string streamName) : IBatchSettlement
{
private bool Acknowledges => !string.IsNullOrEmpty(owner._options.ConsumerGroup) && owner._options.AckMode == AckMode.Manual;
public ValueTask BeforeRouteAsync(IExchange batch, IReadOnlyList items, CancellationToken ct)
=> ValueTask.FromResult(null);
public async ValueTask AcceptAsync(IExchange batch, IReadOnlyList items, CancellationToken ct)
{
if (Acknowledges)
await db.StreamAcknowledgeAsync(streamName, owner._options.ConsumerGroup, items.Select(e => e.Id).ToArray())
.ConfigureAwait(false);
}
public ValueTask RejectAsync(IExchange batch, IReadOnlyList items, Exception failure, CancellationToken ct)
{
owner.Logger?.LogError(failure,
"Redis stream batch of {Count} failed on {Stream}; {Outcome}", items.Count, streamName,
Acknowledges ? "its entries stay pending" : "the consumer moves on");
return ValueTask.CompletedTask;
}
public ValueTask ReturnAsync(IReadOnlyList items, CancellationToken ct) => ValueTask.CompletedTask;
}
}
Path: redb-route/redb.Route.Redis/RedisConsumer.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Redis/RedisConsumer.cs
----
using System.Collections.Concurrent;
using System.Diagnostics;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Telemetry;
using StackExchange.Redis;
namespace redb.Route.Redis;
///
/// Redis consumer. Supports three modes based on the operation type:
///
/// / —
/// Pub/Sub with event-driven callback.
/// / —
/// Redis Streams polling loop: with a consumer group, acknowledged after the route (or NOACK) and pending entries
/// claimed again after an idle time; without one, a position of its own that moves past every entry read.
/// / —
/// list pop via polling (a blocking pop would hold the shared connection); at-least-once with a processing list.
///
///
public sealed partial class RedisConsumer : DrainableConsumer
{
private readonly RedisEndpoint _endpoint;
private readonly RedisEndpointOptions _options;
///
protected override IEndpoint ConsumerEndpoint => _endpoint;
///
protected override string ConsumerName => $"redis:{_endpoint.OperationType}:{_endpoint.Resource}";
/// Number of messages successfully processed.
public long ProcessedCount { get; private set; }
/// Creates a Redis consumer.
public RedisConsumer(RedisEndpoint endpoint, IProcessor processor, RedisEndpointOptions options)
: base(processor)
{
_endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint));
_options = options ?? throw new ArgumentNullException(nameof(options));
}
// Set up by OnStarting, read by the loop RunAsync starts.
private ISubscriber? _subscriber;
private ChannelMessageQueue? _queue;
private RedisChannel _channel;
private IDatabase? _db;
private RedisValue _streamPosition;
///
/// Everything a message depends on is in place before returns: the pub/sub
/// subscription, the consumer group, the XREAD position. Done in the loop, after Start, it lost whatever was
/// published or added in between. A Redis that does not answer fails Start, naming this consumer; it used to leave a
/// started consumer that never received anything.
///
protected override async Task OnStarting(CancellationToken ct)
{
try
{
switch (_endpoint.OperationType)
{
case RedisOperationType.SUBSCRIBE or RedisOperationType.PSUBSCRIBE:
await SubscribeAsync(ct).ConfigureAwait(false);
break;
case RedisOperationType.XREAD or RedisOperationType.XGROUP:
await PrepareStreamAsync(ct).ConfigureAwait(false);
break;
case RedisOperationType.BLPOP or RedisOperationType.BRPOP:
// A list keeps its items, nothing to set up; the round trip only proves Redis answers.
_db = await _endpoint.GetDatabaseAsync(ct).ConfigureAwait(false);
await _db.PingAsync().ConfigureAwait(false);
break;
default:
throw new NotSupportedException(
$"Consumer not supported for operation {_endpoint.OperationType}. " +
"Only SUBSCRIBE/PSUBSCRIBE, XREAD/XGROUP, BLPOP/BRPOP are supported.");
}
}
catch (Exception ex) when (ex is RedisException or TimeoutException)
{
throw new InvalidOperationException(
$"Redis consumer {ConsumerName} cannot start, Redis did not answer: {ex.Message}", ex);
}
}
///
protected override Task RunAsync(CancellationToken pollCt, CancellationToken processingCt)
{
return _endpoint.OperationType switch
{
RedisOperationType.SUBSCRIBE or RedisOperationType.PSUBSCRIBE
=> RunPubSubConsumerAsync(pollCt, processingCt),
RedisOperationType.XREAD or RedisOperationType.XGROUP when _options.Batch is { } batch
=> RunStreamBatchAsync(batch, pollCt, processingCt),
RedisOperationType.XREAD or RedisOperationType.XGROUP
=> RunStreamConsumerAsync(pollCt, processingCt),
RedisOperationType.BLPOP or RedisOperationType.BRPOP
=> RunListConsumerAsync(pollCt, processingCt),
_ => throw new NotSupportedException(
$"Consumer not supported for operation {_endpoint.OperationType}. " +
"Only SUBSCRIBE/PSUBSCRIBE, XREAD/XGROUP, BLPOP/BRPOP are supported.")
};
}
// ═══════════════════════════════════════════════════════════
// Pub/Sub
// ═══════════════════════════════════════════════════════════
private async Task SubscribeAsync(CancellationToken ct)
{
_subscriber = await _endpoint.GetSubscriberAsync(ct).ConfigureAwait(false);
var channel = _options.Channel ?? _endpoint.Resource;
// PSUBSCRIBE is a pattern subscription by itself; usePattern makes SUBSCRIBE one too.
var pattern = _endpoint.OperationType == RedisOperationType.PSUBSCRIBE || _options.UsePattern;
_channel = pattern
? new RedisChannel(channel, RedisChannel.PatternMode.Pattern)
: new RedisChannel(channel, RedisChannel.PatternMode.Literal);
_queue = await _subscriber.SubscribeAsync(_channel).ConfigureAwait(false);
Logger?.LogInformation("Redis subscribed to channel: {Channel} (pattern={Pattern})", channel, pattern);
}
private async Task RunPubSubConsumerAsync(CancellationToken pollCt, CancellationToken processingCt)
{
var subscriber = _subscriber!;
var queue = _queue!;
var redisChannel = _channel;
try
{
while (!pollCt.IsCancellationRequested)
{
var msg = await queue.ReadAsync(pollCt).ConfigureAwait(false);
await ProcessPubSubMessageAsync(msg.Channel!, msg.Message, processingCt).ConfigureAwait(false);
}
}
catch (OperationCanceledException) { /* normal shutdown */ }
catch (Exception ex)
{
Logger?.LogError(ex, "Error in Redis Pub/Sub consumer for channel {Channel}", redisChannel.ToString());
}
finally
{
try { await subscriber.UnsubscribeAsync(redisChannel).ConfigureAwait(false); }
catch (Exception ex) { Logger?.LogWarning(ex, "Error unsubscribing from Redis channel"); }
_queue = null;
}
}
private async Task ProcessPubSubMessageAsync(RedisChannel channel, RedisValue message, CancellationToken ct)
{
var exchange = Exchange.Create(new Message(message.ToString()), _endpoint.ScopeFactory);
exchange.Pattern = ExchangePattern.InOnly;
using var span = StartReceiveSpan();
IncrementInflight();
try
{
exchange.In.Headers[RedisHeaders.Channel] = channel.ToString();
exchange.In.Headers[RedisHeaders.MessageType] = "PubSub";
exchange.In.Headers[RedisHeaders.Timestamp] = DateTimeOffset.UtcNow;
await Processor.Process(exchange, ct).ConfigureAwait(false);
exchange.ThrowIfUnhandledFailure();
ProcessedCount++;
}
catch (Exception ex)
{
RecordFailure(span, ex, ct);
Logger?.LogError(ex, "Error processing Pub/Sub message from channel {Channel}", channel);
}
finally
{
DecrementInflight();
await exchange.DisposeAsync().ConfigureAwait(false);
}
}
// ═══════════════════════════════════════════════════════════
// Streams (XREAD / XGROUP)
// ═══════════════════════════════════════════════════════════
private async Task PrepareStreamAsync(CancellationToken ct)
{
var db = _db = await _endpoint.GetDatabaseAsync(ct).ConfigureAwait(false);
var streamName = _options.StreamName ?? _endpoint.Resource;
var consumerGroup = _options.ConsumerGroup;
// Create consumer group if needed
if (!string.IsNullOrEmpty(consumerGroup))
{
try
{
// Unset position: the group starts at the stream's end ($), as StackExchange.Redis does by default.
await db.StreamCreateConsumerGroupAsync(
streamName,
consumerGroup,
// RedisValue? explicitly: a null string converts to RedisValue.Null, which XGROUP CREATE refuses
// ("A null value is not valid"), and a group consumer without streamStartPosition never started.
_options.StreamStartPosition is { } start ? (RedisValue?)start : null,
createStream: true).ConfigureAwait(false);
Logger?.LogInformation("Redis stream consumer group created: {Group} for {Stream}",
consumerGroup, streamName);
}
catch (RedisServerException ex) when (ex.Message.Contains("BUSYGROUP"))
{
Logger?.LogDebug("Redis stream consumer group {Group} already exists", consumerGroup);
}
}
// Without a group the position is this consumer's to keep, and it moves past every entry read.
_streamPosition = string.IsNullOrEmpty(consumerGroup)
? await StartPositionAsync(db, streamName).ConfigureAwait(false)
: default;
}
private async Task RunStreamConsumerAsync(CancellationToken pollCt, CancellationToken processingCt)
{
var db = _db!;
var streamName = _options.StreamName ?? _endpoint.Resource;
var consumerGroup = _options.ConsumerGroup;
var consumerName = _options.ConsumerName ?? Environment.MachineName;
var position = _streamPosition;
RedisValue claimCursor = "0-0";
Logger?.LogInformation("Redis stream consumer started: stream={Stream}, group={Group}, consumer={Consumer}",
streamName, consumerGroup, consumerName);
while (!pollCt.IsCancellationRequested)
{
try
{
StreamEntry[] entries;
var claimedAny = false;
if (!string.IsNullOrEmpty(consumerGroup))
{
if (_options.StreamClaimMinIdleMs is { } minIdle)
{
// Entries of the group pending for longer than minIdle — a failed entry of this consumer, or one
// a dead consumer left behind — are taken over and processed again. The cursor walks the
// pending list and comes back to the start once it has seen all of it.
var claimed = await db.StreamAutoClaimAsync(
streamName, consumerGroup, consumerName, minIdle, claimCursor, _options.StreamReadCount)
.ConfigureAwait(false);
claimCursor = claimed.NextStartId;
foreach (var entry in claimed.ClaimedEntries.Where(e => !e.IsNull))
{
claimedAny = true;
await ProcessStreamEntryAsync(entry, db, streamName, consumerGroup, processingCt)
.ConfigureAwait(false);
}
}
entries = await db.StreamReadGroupAsync(
streamName,
consumerGroup,
consumerName,
StreamPosition.NewMessages,
_options.StreamReadCount,
noAck: _options.AckMode == AckMode.Auto).ConfigureAwait(false);
}
else
{
entries = await db.StreamReadAsync(
streamName,
position,
_options.StreamReadCount).ConfigureAwait(false);
}
if (entries is { Length: > 0 })
{
foreach (var entry in entries)
{
await ProcessStreamEntryAsync(entry, db, streamName, consumerGroup, processingCt)
.ConfigureAwait(false);
// Past a failed entry too: without a group nothing keeps it pending, as a Kafka consumer
// without breakOnFirstError moves on.
if (string.IsNullOrEmpty(consumerGroup))
position = entry.Id;
}
}
else if (!claimedAny)
{
await Task.Delay(_options.StreamBlockTimeMs, pollCt).ConfigureAwait(false);
}
}
catch (OperationCanceledException) { break; }
catch (Exception ex)
{
Logger?.LogError(ex, "Error reading from Redis stream {Stream}", streamName);
try { await Task.Delay(_options.PollDelayMs * 5, pollCt).ConfigureAwait(false); }
catch (OperationCanceledException) { break; }
}
}
}
///
/// Where an XREAD consumer without a group starts. Unset or $: the entries added from now on. XREAD takes
/// $ as "after the last entry at the time of this call", which a polling loop would evaluate again on every
/// call and so skip whatever arrived in between: it is pinned once, to the id of the stream's last entry, or to the
/// start of an empty stream. Anything else (0, an entry id) is taken as given.
///
private async Task StartPositionAsync(IDatabase db, string streamName)
{
if (_options.StreamStartPosition is not (null or "$"))
return _options.StreamStartPosition;
var last = await db.StreamRangeAsync(streamName, "-", "+", count: 1, messageOrder: Order.Descending)
.ConfigureAwait(false);
return last.Length > 0 ? last[0].Id : "0-0";
}
private async Task ProcessStreamEntryAsync(
StreamEntry entry, IDatabase db, string streamName, string? consumerGroup, CancellationToken ct)
{
using var span = StartReceiveSpan();
try
{
var exchange = Exchange.Create(StreamMessage(entry, streamName), _endpoint.ScopeFactory);
exchange.Pattern = ExchangePattern.InOnly;
IncrementInflight();
try
{
// The entry is acknowledged by this consumer after the unit of work ended well (below), not by
// the route transaction: the transaction owns the database and the outgoing sends.
await Processor.Process(exchange, ct).ConfigureAwait(false);
exchange.ThrowIfUnhandledFailure();
// Acknowledge the entry now that the whole unit of work, the route transaction included, is done. A
// failed entry is not acknowledged: it stays pending, for streamClaimMinIdleMs to claim again.
if (!string.IsNullOrEmpty(consumerGroup) && _options.AckMode == AckMode.Manual)
{
await db.StreamAcknowledgeAsync(streamName, consumerGroup, entry.Id).ConfigureAwait(false);
}
ProcessedCount++;
}
finally
{
DecrementInflight();
await exchange.DisposeAsync().ConfigureAwait(false);
}
}
catch (Exception ex)
{
RecordFailure(span, ex, ct);
Logger?.LogError(ex, "Error processing stream entry {MessageId} from {Stream}", entry.Id, streamName);
}
}
// ═══════════════════════════════════════════════════════════
// List (BLPOP / BRPOP)
// ═══════════════════════════════════════════════════════════
private async Task RunListConsumerAsync(CancellationToken pollCt, CancellationToken processingCt)
{
var db = _db!;
var key = _options.Key ?? _endpoint.Resource;
// BLPOP takes from the head, BRPOP from the tail. Both poll: a blocking pop would hold the multiplexed
// connection every other command of this process shares.
var side = _endpoint.OperationType == RedisOperationType.BLPOP ? ListSide.Left : ListSide.Right;
var processing = _options.ProcessingList;
Logger?.LogInformation("Redis list consumer started: key={Key}, operation={Op}, processing list={Processing}",
key, _endpoint.OperationType, processing);
if (processing is not null)
await ReturnLeftoversAsync(db, processing, key, side).ConfigureAwait(false);
while (!pollCt.IsCancellationRequested)
{
try
{
// With a processing list the item is moved there (LMOVE) and leaves it only once processed; without one
// it is popped, and a failed item is gone.
var result = processing is null
? side == ListSide.Left
? await db.ListLeftPopAsync(key).ConfigureAwait(false)
: await db.ListRightPopAsync(key).ConfigureAwait(false)
: await db.ListMoveAsync(key, processing, side, ListSide.Left).ConfigureAwait(false);
if (!result.HasValue)
{
await Task.Delay(_options.PollDelayMs, pollCt).ConfigureAwait(false);
continue;
}
var processed = await ProcessListMessageAsync(result, key, processingCt).ConfigureAwait(false);
if (processing is null)
continue;
if (processed)
{
await db.ListRemoveAsync(processing, result, count: 1).ConfigureAwait(false);
}
else
{
// Back to the side it was taken from, so it is the next one taken; atomically, so a crash in
// between cannot leave it in both lists or in neither.
var back = db.CreateTransaction();
_ = back.ListRemoveAsync(processing, result, count: 1);
_ = side == ListSide.Left ? back.ListLeftPushAsync(key, result) : back.ListRightPushAsync(key, result);
await back.ExecuteAsync().ConfigureAwait(false);
await Task.Delay(_options.PollDelayMs, pollCt).ConfigureAwait(false);
}
}
catch (OperationCanceledException) { break; }
catch (Exception ex)
{
Logger?.LogError(ex, "Error reading from Redis list {Key}", key);
try { await Task.Delay(_options.PollDelayMs * 5, pollCt).ConfigureAwait(false); }
catch (OperationCanceledException) { break; }
}
}
}
///
/// Returns what a previous run left in the processing list — items it took and never finished — to the side of the
/// queue this consumer takes from, oldest first.
///
private async Task ReturnLeftoversAsync(IDatabase db, string processing, string key, ListSide side)
{
var returned = 0;
// The newest item sits at the head of the processing list; moving from the head to the taking side, one by one,
// leaves the oldest nearest to it.
while ((await db.ListMoveAsync(processing, key, ListSide.Left, side).ConfigureAwait(false)).HasValue)
returned++;
if (returned > 0)
Logger?.LogWarning("Redis list consumer returned {Count} unfinished item(s) from {Processing} to {Key}",
returned, processing, key);
}
/// Whether the route succeeded with the item.
private async Task ProcessListMessageAsync(RedisValue message, string key, CancellationToken ct)
{
var exchange = Exchange.Create(new Message(message.ToString()), _endpoint.ScopeFactory);
exchange.Pattern = ExchangePattern.InOnly;
using var span = StartReceiveSpan();
IncrementInflight();
try
{
exchange.In.Headers[RedisHeaders.Key] = key;
exchange.In.Headers[RedisHeaders.MessageType] = "List";
exchange.In.Headers[RedisHeaders.Timestamp] = DateTimeOffset.UtcNow;
await Processor.Process(exchange, ct).ConfigureAwait(false);
exchange.ThrowIfUnhandledFailure();
ProcessedCount++;
return true;
}
catch (Exception ex)
{
RecordFailure(span, ex, ct);
Logger?.LogError(ex, "Error processing list message from {Key}", key);
return false;
}
finally
{
DecrementInflight();
await exchange.DisposeAsync().ConfigureAwait(false);
}
}
///
/// The span of one message, entry or item: it carries no trace context (a Redis value has no headers; a stream entry's
/// fields are its body), so the span is a root, never a child of the activity the consumer loop holds.
///
private TransportSpan StartReceiveSpan() => RouteTelemetryExtensions.StartConsumerSpan