Path: redb-route/redb.Route.Sqs/SqsConsumer.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.Sqs/SqsConsumer.Batch.cs
----
using Amazon.SQS.Model;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Batching;
using redb.Route.Core;
using redb.Route.Telemetry;
using SqsMessage = Amazon.SQS.Model.Message;
namespace redb.Route.Sqs;
///
/// Batch mode of the SQS consumer (batching=true), on the core batch contract: each worker collects up to
/// maxBatchMessages messages over receives of up to 10, runs them through the route once and settles them once.
/// Success deletes the batch (DeleteMessageBatch); a failure applies the rule of a failed single message to every
/// message: it stays invisible until the visibility timeout, or is made visible at once with
/// resetVisibilityOnFailure=true, and the queue's redrive policy moves it to the dead letter queue after
/// maxReceiveCount receives. A batch the consumer stops on is made visible again.
///
internal sealed partial class SqsConsumer
{
/// The most entries one SQS batch request takes, and the most messages one receive returns.
private const int SqsBatchLimit = 10;
private async Task BatchWorkerLoop(BatchOptions batch, CancellationToken pollCt, CancellationToken processingCt)
{
if (_options.InitialDelay > 0)
{
try { await Task.Delay(_options.InitialDelay, pollCt).ConfigureAwait(false); }
catch (OperationCanceledException) { return; }
}
var settlement = new SqsBatchSettlement(this);
var dispatcher = new BatchDispatcher(Processor, settlement, ToMessage, _endpoint.ScopeFactory,
[SqsHeaders.Queue]);
var collector = new BatchCollector(batch, ReceiveIntoBatch);
while (!pollCt.IsCancellationRequested)
{
CollectedBatch collected;
try
{
collected = await collector.CollectAsync(pollCt).ConfigureAwait(false);
}
catch (Exception ex)
{
Logger?.LogError(ex, "SQS batch receive error on queue {Queue}", _endpoint.QueueName);
_endpoint.RecordError(ex);
try { await Task.Delay(1000, 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, $"{_endpoint.QueueName} receive", "sqs",
_endpoint.Uri.NormalizedKey, _endpoint.QueueName,
items.Select(m => RouteTelemetryExtensions.ExtractTraceContext(m.MessageAttributes,
static (attrs, name) => attrs is not null && attrs.TryGetValue(name, out var value) ? value.StringValue : null)),
items.Count);
IncrementInflight();
try
{
await dispatcher.DispatchAsync(items, span, processingCt).ConfigureAwait(false);
}
catch (OperationCanceledException) when (processingCt.IsCancellationRequested)
{
return;
}
catch (Exception ex)
{
Logger?.LogError(ex, "SQS batch failed to settle on queue {Queue}", _endpoint.QueueName);
_endpoint.RecordError(ex);
}
finally
{
DecrementInflight();
}
}
}
///
/// The transport's part of collection: one ReceiveMessage of up to 10 messages, long-polling for the wait rounded
/// up to whole seconds (SQS waits in seconds, 1 to 20). A stop does not cancel a receive in flight: a long poll the
/// client abandons stays open at the queue and takes the messages the stop makes visible again, holding them for
/// their visibility timeout. The receive runs to its end, its messages join the batch, and the stop then gives the
/// whole batch back; a stop waits at most one receive.
///
private async ValueTask ReceiveIntoBatch(List into, int max, TimeSpan wait, CancellationToken ct)
{
ct.ThrowIfCancellationRequested();
var request = new ReceiveMessageRequest
{
QueueUrl = _queueUrl,
MaxNumberOfMessages = Math.Min(SqsBatchLimit, max),
WaitTimeSeconds = (int)Math.Clamp(Math.Ceiling(wait.TotalSeconds), 1, 20),
MessageSystemAttributeNames = _systemAttributeNames,
MessageAttributeNames = _messageAttributeNames,
};
if (_options.VisibilityTimeout > 0)
request.VisibilityTimeout = _options.VisibilityTimeout;
var response = await _client!.ReceiveMessageAsync(request, CancellationToken.None).ConfigureAwait(false);
var messages = response.Messages ?? [];
into.AddRange(messages);
ct.ThrowIfCancellationRequested();
return messages.Count;
}
/// Deletes the messages in requests of up to 10. An entry SQS refuses is logged: it comes back after its visibility timeout.
private async Task DeleteBatchAsync(IReadOnlyList items, CancellationToken ct)
{
foreach (var chunk in items.Chunk(SqsBatchLimit))
{
var request = new DeleteMessageBatchRequest
{
QueueUrl = _queueUrl,
Entries = chunk.Select((m, i) => new DeleteMessageBatchRequestEntry(i.ToString(), m.ReceiptHandle)).ToList(),
};
var response = await _client!.DeleteMessageBatchAsync(request, ct).ConfigureAwait(false);
ReportFailedEntries(response.Failed, chunk, "delete");
}
}
/// Makes the messages visible again at once, in requests of up to 10.
private async Task MakeVisibleAsync(IReadOnlyList items)
{
foreach (var chunk in items.Chunk(SqsBatchLimit))
{
try
{
var request = new ChangeMessageVisibilityBatchRequest
{
QueueUrl = _queueUrl,
Entries = chunk.Select((m, i) =>
new ChangeMessageVisibilityBatchRequestEntry(i.ToString(), m.ReceiptHandle) { VisibilityTimeout = 0 }).ToList(),
};
var response = await _client!.ChangeMessageVisibilityBatchAsync(request, CancellationToken.None).ConfigureAwait(false);
ReportFailedEntries(response.Failed, chunk, "visibility reset");
}
catch (Exception ex)
{
Logger?.LogWarning(ex, "SQS: failed to reset visibility of {Count} messages on {Queue}",
chunk.Length, _endpoint.QueueName);
}
}
}
private void ReportFailedEntries(List? failed, SqsMessage[] chunk, string operation)
{
if (failed is not { Count: > 0 })
return;
var refused = new List(failed.Count);
foreach (var entry in failed)
{
var messageId = int.TryParse(entry.Id, out var index) && index < chunk.Length ? chunk[index].MessageId : entry.Id;
refused.Add($"{messageId}: {entry.Code} {entry.Message}");
Logger?.LogWarning("SQS batch {Operation} refused for messageId={MessageId} on {Queue}: {Code} {Message}",
operation, messageId, _endpoint.QueueName, entry.Code, entry.Message);
}
_endpoint.RecordError(new InvalidOperationException(
$"SQS batch {operation} on {_endpoint.QueueName}: {failed.Count} of {chunk.Length} messages refused: {string.Join("; ", refused)}"));
}
///
/// SQS's settlement of a batch: each message by its receipt handle, in batch requests. One instance per worker,
/// used by one batch at a time.
///
private sealed class SqsBatchSettlement(SqsConsumer owner) : IBatchSettlement
{
/// The batch in flight was deleted on receipt (ackMode=auto): there is nothing to give back.
private bool _deletedOnReceipt;
public async ValueTask BeforeRouteAsync(IExchange batch, IReadOnlyList items, CancellationToken ct)
{
// ackMode=auto: deleted on receipt, before the route runs (at-most-once), as a single message is.
if (owner._options.AckMode == AckMode.Auto)
{
await owner.DeleteBatchAsync(items, ct).ConfigureAwait(false);
_deletedOnReceipt = true;
}
return null;
}
public async ValueTask AcceptAsync(IExchange batch, IReadOnlyList items, CancellationToken ct)
{
if (!_deletedOnReceipt)
await owner.DeleteBatchAsync(items, ct).ConfigureAwait(false);
_deletedOnReceipt = false;
}
public async ValueTask RejectAsync(IExchange batch, IReadOnlyList items, Exception failure, CancellationToken ct)
{
owner.Logger?.LogError(failure, "SQS batch of {Count} failed on queue {Queue}", items.Count, owner._endpoint.QueueName);
if (!_deletedOnReceipt && owner._options.ResetVisibilityOnFailure)
await owner.MakeVisibleAsync(items).ConfigureAwait(false);
_deletedOnReceipt = false;
}
public async ValueTask ReturnAsync(IReadOnlyList items, CancellationToken ct)
{
if (!_deletedOnReceipt)
await owner.MakeVisibleAsync(items).ConfigureAwait(false);
_deletedOnReceipt = false;
}
}
}