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;
}
}