From 85770b52da11a8c735d9ae5fef1efb2d7ae078d9 Mon Sep 17 00:00:00 2001
From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com>
Date: Mon, 2 Nov 2026 13:48:24 +0000
Subject: [PATCH 1/4] feat: add native SQS sending and queue topology (#223)
---
.../Relayer.Benchmarks.csproj | 1 +
.../SqsBindingBenchmarks.cs | 73 ++++
.../Relayer.Benchmarks/SqsSendBenchmarks.cs | 101 +++++
.../AmazonSqsBatchException.cs | 21 +
.../AmazonSqsBuilderExtensions.cs | 52 +++
src/Relayer.AmazonSqs/AmazonSqsTransport.cs | 2 +-
.../AmazonSqsTransportOptions.cs | 7 +
.../Relayer.AmazonSqs.csproj | 5 +
src/Relayer.AmazonSqs/SqsSendState.cs | 155 +++++++
src/Relayer.AmazonSqs/SqsSendTransport.cs | 289 +++++++++++++
tests/Relayer.Tests/SqsSendLocalStackTests.cs | 109 +++++
tests/Relayer.Tests/SqsSendTests.cs | 391 ++++++++++++++++++
website/docs/roadmap.md | 1 +
website/docs/transports/amazon-sqs.md | 97 +++++
website/docs/transports/index.md | 2 +-
website/sidebars.js | 1 +
website/src/pages/index.js | 3 +-
17 files changed, 1307 insertions(+), 3 deletions(-)
create mode 100644 benchmarks/Relayer.Benchmarks/SqsBindingBenchmarks.cs
create mode 100644 benchmarks/Relayer.Benchmarks/SqsSendBenchmarks.cs
create mode 100644 src/Relayer.AmazonSqs/AmazonSqsBatchException.cs
create mode 100644 src/Relayer.AmazonSqs/AmazonSqsBuilderExtensions.cs
create mode 100644 src/Relayer.AmazonSqs/SqsSendState.cs
create mode 100644 src/Relayer.AmazonSqs/SqsSendTransport.cs
create mode 100644 tests/Relayer.Tests/SqsSendLocalStackTests.cs
create mode 100644 tests/Relayer.Tests/SqsSendTests.cs
create mode 100644 website/docs/transports/amazon-sqs.md
diff --git a/benchmarks/Relayer.Benchmarks/Relayer.Benchmarks.csproj b/benchmarks/Relayer.Benchmarks/Relayer.Benchmarks.csproj
index e8da8d0f2..625893ea9 100644
--- a/benchmarks/Relayer.Benchmarks/Relayer.Benchmarks.csproj
+++ b/benchmarks/Relayer.Benchmarks/Relayer.Benchmarks.csproj
@@ -10,6 +10,7 @@
+
diff --git a/benchmarks/Relayer.Benchmarks/SqsBindingBenchmarks.cs b/benchmarks/Relayer.Benchmarks/SqsBindingBenchmarks.cs
new file mode 100644
index 000000000..afa62b5f4
--- /dev/null
+++ b/benchmarks/Relayer.Benchmarks/SqsBindingBenchmarks.cs
@@ -0,0 +1,73 @@
+using System.Text;
+using Amazon.SQS.Model;
+using BenchmarkDotNet.Attributes;
+using Relayer.AmazonSqs;
+
+namespace Relayer.Benchmarks;
+
+/// Isolates Relayer-owned body/header allocations from serialization and SDK/network allocations.
+[MemoryDiagnoser]
+public class SqsBindingBenchmarks
+{
+ private readonly SqsSendState _relayer = new("0");
+ private readonly SendMessageRequest _raw = new() { MessageAttributes = new(10) };
+ private readonly HeaderBuffer _headers = new();
+ private readonly MessageEnvelope _envelope = new(new("benchmark.order", 1), "/benchmarks", new());
+ private readonly byte[] _body = Encoding.UTF8.GetBytes(new string('x', 256));
+ private readonly DateTimeOffset _time = DateTimeOffset.UtcNow;
+ private long _sequence;
+
+ [GlobalSetup]
+ public void Setup()
+ {
+ var message = Next();
+ foreach (var header in message.Headers.Span) _raw.MessageAttributes.Add(header.Key, new() { DataType = "String" });
+ _relayer.Prepare(message, "https://sqs.us-east-1.amazonaws.com/123456789012/orders", false);
+ _relayer.Clear();
+ RawBinding();
+ }
+
+ [Benchmark(Baseline = true)]
+ public int RawBinding()
+ {
+ var message = Next();
+ _raw.MessageBody = Encoding.UTF8.GetString(message.Body.Span);
+ foreach (var header in message.Headers.Span) _raw.MessageAttributes[header.Key].StringValue = header.Value.ToString();
+ return _raw.MessageBody.Length + _raw.MessageAttributes.Count;
+ }
+
+ [Benchmark]
+ public int RelayerBinding()
+ {
+ var size = _relayer.Prepare(Next(), "https://sqs.us-east-1.amazonaws.com/123456789012/orders", false);
+ _relayer.Clear();
+ return size;
+ }
+
+ private OutgoingMessage Next()
+ {
+ _envelope.Write(_headers, new(Guid.CreateVersion7(), _time.AddTicks(++_sequence), default));
+ return new("orders", _body, _headers.Entries);
+ }
+
+ private sealed class HeaderBuffer : IMessageHeaderWriter
+ {
+ internal readonly KeyValuePair[] Entries = new KeyValuePair[6];
+ private readonly byte[][] _values = [new byte[128], new byte[128], new byte[128], new byte[128], new byte[128]];
+ internal HeaderBuffer() => Entries[5] = new("content-type", new("application/json"));
+
+ public static void SetHeader(HeaderBuffer message, string name, ReadOnlySpan value)
+ {
+ for (var i = 0; i < message._values.Length; i++)
+ {
+ if (message.Entries[i].Key is not null && message.Entries[i].Key != name) continue;
+ var length = Encoding.UTF8.GetBytes(value, message._values[i]);
+ message.Entries[i] = new(name, new WireString(message._values[i].AsMemory(0, length)));
+ return;
+ }
+ throw new InvalidOperationException("Unexpected envelope header.");
+ }
+
+ public static void RemoveHeader(HeaderBuffer message, string name) { }
+ }
+}
diff --git a/benchmarks/Relayer.Benchmarks/SqsSendBenchmarks.cs b/benchmarks/Relayer.Benchmarks/SqsSendBenchmarks.cs
new file mode 100644
index 000000000..dc2c747d5
--- /dev/null
+++ b/benchmarks/Relayer.Benchmarks/SqsSendBenchmarks.cs
@@ -0,0 +1,101 @@
+using System.Text;
+using Amazon;
+using Amazon.Runtime;
+using Amazon.SQS;
+using Amazon.SQS.Model;
+using BenchmarkDotNet.Attributes;
+using BenchmarkDotNet.Configs;
+using Relayer.AmazonSqs;
+
+namespace Relayer.Benchmarks;
+
+/// Native acknowledged SQS sends. Both paths reuse requests and include UTF-8-to-native-text conversion.
+[MemoryDiagnoser]
+[CategoriesColumn]
+[GroupBenchmarksBy(BenchmarkLogicalGroupRule.ByCategory)]
+public class SqsSendBenchmarks
+{
+ private AmazonSQSClient _client = null!;
+ private SqsSendTransport _transport = null!;
+ private string _queue = null!;
+ private string _url = null!;
+ private byte[] _body = null!;
+ private KeyValuePair[] _headers = null!;
+ private OutgoingMessage _message;
+ private OutgoingMessage[] _batch = null!;
+ private SendMessageRequest _rawSingle = null!;
+ private SendMessageBatchRequest _rawBatch = null!;
+
+ [GlobalSetup]
+ public async Task Setup()
+ {
+ var serviceUrl = Environment.GetEnvironmentVariable("RELAYER_SQS_SERVICE_URL");
+ _client = serviceUrl is null
+ ? new AmazonSQSClient(RegionEndpoint.GetBySystemName(Environment.GetEnvironmentVariable("AWS_REGION") ?? "us-east-1"))
+ : new AmazonSQSClient(new BasicAWSCredentials("test", "test"), new AmazonSQSConfig { ServiceURL = serviceUrl, AuthenticationRegion = "us-east-1" });
+ _queue = "relayer-benchmark-" + Guid.NewGuid().ToString("N");
+ _url = (await _client.CreateQueueAsync(_queue)).QueueUrl;
+ await Task.Delay(TimeSpan.FromSeconds(1));
+ var options = new AmazonSqsTransportOptions { SqsClient = _client };
+ options.Queues.Add(new(_queue));
+ _transport = new("benchmark", _client, false, options);
+ await _transport.StartAsync(default);
+ _body = Encoding.UTF8.GetBytes(new string('x', 256));
+ _headers = [new("ce_id", new("019a3c1b-97c0-7000-8000-000000000001")), new("ce_type", new("benchmark.order;v=1")),
+ new("ce_source", new("/benchmarks")), new("ce_specversion", new("1.0")), new("content-type", new("application/json"))];
+ _message = new(_queue, _body, _headers);
+ _batch = Enumerable.Repeat(_message, 10).ToArray();
+ _rawSingle = new() { QueueUrl = _url, MessageAttributes = Attributes() };
+ _rawBatch = new() { QueueUrl = _url, Entries = new(10) };
+ for (var i = 0; i < 10; i++) _rawBatch.Entries.Add(new() { Id = i.ToString(), MessageAttributes = Attributes() });
+ await RawSingle();
+ await RelayerSingle();
+ await RawBatch();
+ await RelayerBatch();
+ }
+
+ private Dictionary Attributes()
+ {
+ var attributes = new Dictionary(10);
+ foreach (var header in _headers) attributes.Add(header.Key, new() { DataType = "String" });
+ return attributes;
+ }
+
+ private void Prepare(Dictionary attributes)
+ {
+ foreach (var header in _headers) attributes[header.Key].StringValue = header.Value.ToString();
+ }
+
+ [Benchmark(Baseline = true), BenchmarkCategory("Single")]
+ public Task RawSingle()
+ {
+ _rawSingle.MessageBody = Encoding.UTF8.GetString(_body);
+ Prepare(_rawSingle.MessageAttributes);
+ return _client.SendMessageAsync(_rawSingle);
+ }
+
+ [Benchmark, BenchmarkCategory("Single")]
+ public ValueTask RelayerSingle() => _transport.SendAsync(_message, default);
+
+ [Benchmark(Baseline = true, OperationsPerInvoke = 10), BenchmarkCategory("Batch")]
+ public Task RawBatch()
+ {
+ foreach (var entry in _rawBatch.Entries)
+ {
+ entry.MessageBody = Encoding.UTF8.GetString(_body);
+ Prepare(entry.MessageAttributes);
+ }
+ return _client.SendMessageBatchAsync(_rawBatch);
+ }
+
+ [Benchmark(OperationsPerInvoke = 10), BenchmarkCategory("Batch")]
+ public ValueTask RelayerBatch() => _transport.SendBatchAsync(_batch, default);
+
+ [GlobalCleanup]
+ public async Task Cleanup()
+ {
+ if (_transport is not null) await _transport.DisposeAsync();
+ try { if (_client is not null && _url is not null) await _client.DeleteQueueAsync(_url); }
+ finally { _client?.Dispose(); }
+ }
+}
diff --git a/src/Relayer.AmazonSqs/AmazonSqsBatchException.cs b/src/Relayer.AmazonSqs/AmazonSqsBatchException.cs
new file mode 100644
index 000000000..52a84d256
--- /dev/null
+++ b/src/Relayer.AmazonSqs/AmazonSqsBatchException.cs
@@ -0,0 +1,21 @@
+using Amazon.SQS;
+using Amazon.SQS.Model;
+
+namespace Relayer.AmazonSqs;
+
+/// A native batch accepted some entries but rejected others. Successful entries are not resent.
+public sealed class AmazonSqsBatchException : AmazonSQSException
+{
+ internal AmazonSqsBatchException(SendMessageBatchResponse response, int batchOffset)
+ : base($"SQS SendMessageBatch rejected {response.Failed.Count} entries. Inspect Response.Failed; earlier entries may already be delivered.")
+ {
+ Response = response;
+ BatchOffset = batchOffset;
+ RequestId = response.ResponseMetadata?.RequestId;
+ }
+
+ /// The unmodified native response, including successful and failed entry IDs.
+ public SendMessageBatchResponse Response { get; }
+ /// The starting index of this native batch within its contiguous destination group.
+ public int BatchOffset { get; }
+}
diff --git a/src/Relayer.AmazonSqs/AmazonSqsBuilderExtensions.cs b/src/Relayer.AmazonSqs/AmazonSqsBuilderExtensions.cs
new file mode 100644
index 000000000..544324883
--- /dev/null
+++ b/src/Relayer.AmazonSqs/AmazonSqsBuilderExtensions.cs
@@ -0,0 +1,52 @@
+using Amazon.SQS;
+using Amazon.SQS.Model;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Hosting;
+using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.Options;
+using Relayer.Transports;
+
+namespace Relayer.AmazonSqs;
+
+/// Registers named native SQS send transports.
+public static class AmazonSqsBuilderExtensions
+{
+ /// Declares SQS queue sending and topology. Receivers and SNS are not implemented yet.
+ public static IRelayerBuilder AmazonSqs(this IRelayerBuilder builder, string name,
+ Action> configure)
+ {
+ ArgumentNullException.ThrowIfNull(builder);
+ ArgumentNullException.ThrowIfNull(configure);
+ builder.AddTransport(name, configure);
+ builder.Services.AddSingleton(provider =>
+ {
+ var declaration = provider.GetRequiredService().Transports.Single(item => item.Name == name);
+ if (declaration.Consumers.Count != 0)
+ throw new NotSupportedException($"SQS transport '{name}': receiver composition is not implemented yet.");
+ var options = provider.GetRequiredService>().Get(name);
+ SqsSendTransport.ValidateDeclarations(name, options, declaration.Routes.Select(route => route.Destination));
+ var client = options.SqsClient ?? new AmazonSQSClient(options.Sqs);
+ return new SqsSendTransport(name, client, options.SqsClient is null, options,
+ provider.GetRequiredService(), provider.GetService());
+ });
+ builder.Services.AddSingleton(provider => new SqsSendHostedService(provider, name));
+ return builder;
+ }
+
+ /// Customizes the native request immediately before single or batch sending.
+ public static SendOptions AmazonSqs(this SendOptions options, Action configure) =>
+ options.ConfigureNative(configure);
+}
+
+/// SQS route options. Native queue settings belong on the transport declaration.
+public sealed class AmazonSqsRouteOptions;
+
+/// Reserved for native receiver composition.
+public sealed class AmazonSqsConsumerOptions;
+
+internal sealed class SqsSendHostedService(IServiceProvider provider, string name) : IHostedService
+{
+ private ITransport Transport => provider.GetServices().Single(transport => transport.Name == name);
+ public Task StartAsync(CancellationToken cancellationToken) => Transport.StartAsync(cancellationToken);
+ public Task StopAsync(CancellationToken cancellationToken) => Transport.StopAsync(cancellationToken);
+}
diff --git a/src/Relayer.AmazonSqs/AmazonSqsTransport.cs b/src/Relayer.AmazonSqs/AmazonSqsTransport.cs
index 893b3380f..b812516fe 100644
--- a/src/Relayer.AmazonSqs/AmazonSqsTransport.cs
+++ b/src/Relayer.AmazonSqs/AmazonSqsTransport.cs
@@ -18,7 +18,7 @@ public static class AmazonSqsTransport
OrderedByKey = true,
};
- /// Returns conservative SQS queue capabilities for the transport stub (docs/decisions.md D24).
+ /// Returns conservative SQS queue capabilities, independently of a registered native adapter (docs/decisions.md D24).
///
/// Accepts a queue name or URL. FIFO queues require the case-sensitive .fifo suffix and do not support
/// per-message delivery timers. Redrive cannot dead-letter an individual message on demand with error metadata.
diff --git a/src/Relayer.AmazonSqs/AmazonSqsTransportOptions.cs b/src/Relayer.AmazonSqs/AmazonSqsTransportOptions.cs
index 7f12f9853..c5ca09db7 100644
--- a/src/Relayer.AmazonSqs/AmazonSqsTransportOptions.cs
+++ b/src/Relayer.AmazonSqs/AmazonSqsTransportOptions.cs
@@ -1,11 +1,18 @@
using Amazon.SimpleNotificationService;
using Amazon.SQS;
+using Amazon.SQS.Model;
namespace Relayer.AmazonSqs;
/// Options for the AmazonSqs transport. Native client configuration is passed through unchanged (docs/decisions.md D1).
public sealed class AmazonSqsTransportOptions
{
+ /// A caller-owned SQS client. When absent, Relayer uses Sqs and the AWS credential chain.
+ public IAmazonSQS? SqsClient { get; set; }
+
+ /// Native queue declarations. Queue names must match route destinations.
+ public IList Queues { get; } = [];
+
/// Native SQS client configuration.
public AmazonSQSConfig Sqs { get; set; } = new();
diff --git a/src/Relayer.AmazonSqs/Relayer.AmazonSqs.csproj b/src/Relayer.AmazonSqs/Relayer.AmazonSqs.csproj
index b82c926c5..e76513543 100644
--- a/src/Relayer.AmazonSqs/Relayer.AmazonSqs.csproj
+++ b/src/Relayer.AmazonSqs/Relayer.AmazonSqs.csproj
@@ -13,4 +13,9 @@
+
+
+
+
+
diff --git a/src/Relayer.AmazonSqs/SqsSendState.cs b/src/Relayer.AmazonSqs/SqsSendState.cs
new file mode 100644
index 000000000..2171472e4
--- /dev/null
+++ b/src/Relayer.AmazonSqs/SqsSendState.cs
@@ -0,0 +1,155 @@
+using System.Text;
+using Amazon.SQS.Model;
+
+namespace Relayer.AmazonSqs;
+
+// Native requests borrow these objects until the SDK task completes. Each concurrent operation rents its own state.
+internal sealed class SqsSendState
+{
+ private static readonly UTF8Encoding Utf8 = new(false, true);
+ private readonly Dictionary _attributes = new(10, StringComparer.Ordinal);
+ private readonly MessageAttributeValue[] _values = new MessageAttributeValue[10];
+ internal SendMessageRequest Request { get; } = new();
+ internal SendMessageBatchRequestEntry Entry { get; }
+
+ internal SqsSendState(string id)
+ {
+ Entry = new() { Id = id };
+ for (var i = 0; i < _values.Length; i++) _values[i] = new() { DataType = "String" };
+ }
+
+ internal int Prepare(OutgoingMessage outgoing, string queueUrl, bool fifo)
+ {
+ Request.QueueUrl = queueUrl;
+ // SQS has a native text body. Reject invalid UTF-8 rather than silently replacing serializer bytes.
+ Request.MessageBody = Utf8.GetString(outgoing.Body.Span);
+ if (outgoing.OrderingKey is { } orderingKey) Request.MessageGroupId = orderingKey.ToString();
+ Request.MessageAttributes = _attributes;
+ outgoing.ApplyNative(Request);
+ // Keep caller-supplied attribute dictionaries caller-owned, while retaining reusable transport storage.
+ if (!ReferenceEquals(Request.MessageAttributes, _attributes))
+ {
+ if (Request.MessageAttributes is { } native)
+ foreach (var attribute in native) _attributes.Add(attribute.Key, attribute.Value);
+ Request.MessageAttributes = _attributes;
+ }
+ var index = 0;
+ foreach (var header in outgoing.Headers.Span)
+ {
+ if (index == _values.Length)
+ throw new InvalidOperationException("SQS supports at most 10 message attributes, including CloudEvents and tracing headers.");
+ var value = _values[index++];
+ value.StringValue = header.Value.ToString();
+ _attributes[header.Key] = value;
+ if (fifo && header.Key == "ce_id") Request.MessageDeduplicationId = value.StringValue;
+ }
+ if (_attributes.Count > 10)
+ throw new InvalidOperationException("SQS supports at most 10 message attributes, including CloudEvents and tracing headers.");
+ Request.QueueUrl = queueUrl;
+ if (outgoing.OrderingKey is { } key) Request.MessageGroupId = key.ToString();
+ if (outgoing.DeliverAt is { } deliverAt)
+ {
+ var delay = deliverAt - DateTimeOffset.UtcNow;
+ if (delay > TimeSpan.Zero)
+ {
+ if (fifo || delay > TimeSpan.FromMinutes(15))
+ throw new NotSupportedException("SQS per-message timers require a standard queue and a delay at most 15 minutes. Use the durable outbox for longer delays or FIFO scheduling.");
+ Request.DelaySeconds = (int)Math.Ceiling(delay.TotalSeconds);
+ }
+ else Request.DelaySeconds = fifo ? null : 0;
+ }
+ if (fifo && (string.IsNullOrWhiteSpace(Request.MessageGroupId) || Request.DelaySeconds is not null))
+ throw new InvalidOperationException("SQS FIFO sends require MessageGroupId and cannot specify per-message DelaySeconds.");
+ if (Request.DelaySeconds is < 0 or > 900)
+ throw new ArgumentOutOfRangeException(nameof(Request.DelaySeconds), "SQS DelaySeconds must be between 0 and 900.");
+ var size = Utf8.GetByteCount(Request.MessageBody);
+ foreach (var attribute in _attributes)
+ {
+ var value = attribute.Value;
+ size = checked(size + Utf8.GetByteCount(attribute.Key) + Utf8.GetByteCount(value.DataType));
+ if (value.StringValue is { } text) size = checked(size + Utf8.GetByteCount(text));
+ if (value.BinaryValue is { } binary) size = checked(size + (int)binary.Length);
+ }
+ return size;
+ }
+
+ internal void CopyToEntry()
+ {
+ Entry.MessageBody = Request.MessageBody;
+ Entry.MessageAttributes = Request.MessageAttributes;
+ Entry.MessageSystemAttributes = Request.MessageSystemAttributes;
+ Entry.DelaySeconds = Request.DelaySeconds;
+ Entry.MessageGroupId = Request.MessageGroupId;
+ Entry.MessageDeduplicationId = Request.MessageDeduplicationId;
+ }
+
+ internal void Clear()
+ {
+ _attributes.Clear();
+ foreach (var value in _values) value.StringValue = null;
+ Request.QueueUrl = null;
+ Request.MessageBody = null;
+ Request.MessageAttributes = null;
+ Request.MessageSystemAttributes = null;
+ Request.MessageGroupId = null;
+ Request.MessageDeduplicationId = null;
+ Request.DelaySeconds = null;
+ Entry.MessageBody = null;
+ Entry.MessageAttributes = null;
+ Entry.MessageSystemAttributes = null;
+ Entry.MessageGroupId = null;
+ Entry.MessageDeduplicationId = null;
+ Entry.DelaySeconds = null;
+ }
+}
+
+internal sealed class SqsOperationState
+{
+ internal readonly SqsSendState[] Messages = new SqsSendState[10];
+ internal readonly string[] Ids = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
+ internal readonly SendMessageBatchRequest Batch = new() { Entries = new(10) };
+ internal int Used;
+ internal SqsOperationState()
+ {
+ for (var i = 0; i < Messages.Length; i++) Messages[i] = new(i.ToString(System.Globalization.CultureInfo.InvariantCulture));
+ }
+
+ internal void Clear()
+ {
+ for (var i = 0; i < Used; i++) Messages[i].Clear();
+ Used = 0;
+ Batch.Entries.Clear();
+ Batch.QueueUrl = null;
+ }
+}
+
+// Same lock-free high-water-mark strategy as the Service Bus adapter; no shared mutable static state.
+internal sealed class SqsOperationPool
+{
+ private readonly Page _first = new();
+ internal SqsOperationState Rent()
+ {
+ for (Page? page = _first; page is not null; page = Volatile.Read(ref page.Next))
+ for (var i = 0; i < page.Slots.Length; i++)
+ if (Interlocked.Exchange(ref page.Slots[i], null) is { } state) return state;
+ return new();
+ }
+
+ internal void Return(SqsOperationState state)
+ {
+ state.Clear();
+ var page = _first;
+ while (true)
+ {
+ for (var i = 0; i < page.Slots.Length; i++)
+ if (Interlocked.CompareExchange(ref page.Slots[i], state, null) is null) return;
+ page = Volatile.Read(ref page.Next) ?? Interlocked.CompareExchange(ref page.Next, new Page(), null) ?? page.Next!;
+ }
+ }
+
+ private sealed class Page
+ {
+ internal readonly SqsOperationState?[] Slots = new SqsOperationState?[32];
+ internal Page? Next;
+ }
+}
diff --git a/src/Relayer.AmazonSqs/SqsSendTransport.cs b/src/Relayer.AmazonSqs/SqsSendTransport.cs
new file mode 100644
index 000000000..ddba8dae2
--- /dev/null
+++ b/src/Relayer.AmazonSqs/SqsSendTransport.cs
@@ -0,0 +1,289 @@
+using System.Collections.Frozen;
+using System.Diagnostics;
+using System.Globalization;
+using System.Runtime.CompilerServices;
+using System.Text.Json;
+using Amazon.SQS;
+using Amazon.SQS.Model;
+using Microsoft.Extensions.Logging;
+using Relayer.Transports;
+
+namespace Relayer.AmazonSqs;
+
+internal sealed class SqsSendTransport : ITransport, ITransportSendTracing
+{
+ private readonly IAmazonSQS _client;
+ private readonly bool _ownsClient;
+ private readonly FrozenDictionary _endpoints;
+ private readonly MessageTracing? _tracing;
+ private readonly SqsOperationPool _operations = new();
+ private int _disposed;
+
+ internal static void ValidateDeclarations(string name, AmazonSqsTransportOptions options, IEnumerable destinations)
+ {
+ ArgumentNullException.ThrowIfNull(options.Sqs);
+ var names = new HashSet(StringComparer.Ordinal);
+ foreach (var queue in options.Queues)
+ {
+ ArgumentException.ThrowIfNullOrWhiteSpace(queue.QueueName);
+ if (!names.Add(queue.QueueName))
+ throw new InvalidOperationException($"SQS transport '{name}': duplicate queue '{queue.QueueName}'.");
+ var fifo = queue.QueueName.EndsWith(".fifo", StringComparison.Ordinal);
+ var declaresFifo = queue.Attributes?.TryGetValue("FifoQueue", out var value) == true && value == "true";
+ if (fifo != declaresFifo)
+ throw new InvalidOperationException($"SQS queue '{queue.QueueName}': the .fifo suffix and native FifoQueue=true declaration must agree.");
+ }
+ foreach (var destination in destinations)
+ if (!names.Contains(destination))
+ throw new InvalidOperationException($"SQS transport '{name}': destination '{destination}' needs a native CreateQueueRequest declaration.");
+ }
+
+ internal SqsSendTransport(string name, IAmazonSQS client, bool ownsClient, AmazonSqsTransportOptions options,
+ MessageTracing? tracing = null, ILoggerFactory? logging = null)
+ {
+ Name = name;
+ _client = client;
+ _ownsClient = ownsClient;
+ _tracing = tracing;
+ var endpoints = new Dictionary(StringComparer.Ordinal);
+ foreach (var declaration in options.Queues)
+ {
+ var endpoint = new Endpoint(declaration);
+ if (tracing is not null)
+ endpoint.Tracing = new(tracing, new() { System = "aws_sqs", Destination = declaration.QueueName },
+ SendCoreAsync, SendBatchCoreAsync, logging?.CreateLogger());
+ endpoints.Add(declaration.QueueName, endpoint);
+ }
+ _endpoints = endpoints.ToFrozenDictionary(StringComparer.Ordinal);
+ }
+
+ public string Name { get; }
+ private Endpoint GetEndpoint(string destination) => _endpoints.TryGetValue(destination, out var endpoint) ? endpoint
+ : throw new InvalidOperationException($"SQS transport '{Name}': undeclared destination '{destination}'.");
+ public TransportCapabilities GetCapabilities(string endpoint) => GetEndpoint(endpoint).Capabilities;
+ public SendTracing? GetSendTracing(string destination) => GetEndpoint(destination).Tracing;
+
+ public async ValueTask ApplyTopologyAsync(TopologyMode mode, CancellationToken cancellationToken)
+ {
+ Check(cancellationToken);
+ if (mode == TopologyMode.None) return new([]);
+ if (mode is not (TopologyMode.Validate or TopologyMode.Provision)) throw new ArgumentOutOfRangeException(nameof(mode));
+ var differences = new List();
+ foreach (var endpoint in _endpoints.Values)
+ {
+ try { endpoint.Url = (await _client.GetQueueUrlAsync(endpoint.Declaration.QueueName, cancellationToken).ConfigureAwait(false)).QueueUrl; }
+ catch (QueueDoesNotExistException)
+ {
+ if (mode == TopologyMode.Validate)
+ {
+ differences.Add($"Missing SQS queue '{endpoint.Declaration.QueueName}'. Provision it outside the application or use Provision explicitly.");
+ continue;
+ }
+ endpoint.Url = (await _client.CreateQueueAsync(endpoint.Declaration, cancellationToken).ConfigureAwait(false)).QueueUrl;
+ // AWS requires a one-second wait after CreateQueue before using the new queue.
+ await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken).ConfigureAwait(false);
+ }
+ var actual = await _client.GetQueueAttributesAsync(new GetQueueAttributesRequest
+ {
+ QueueUrl = endpoint.Url, AttributeNames = ["All"],
+ }, cancellationToken).ConfigureAwait(false);
+ if (endpoint.Declaration.Attributes is { } expected)
+ foreach (var attribute in expected)
+ if (actual.Attributes?.TryGetValue(attribute.Key, out var value) != true || value is null || !AttributeEquals(attribute.Key, attribute.Value, value))
+ differences.Add($"SQS queue '{endpoint.Declaration.QueueName}': {attribute.Key} differs. Reconcile it through infrastructure configuration; Relayer never modifies or deletes existing queues.");
+ if (endpoint.Declaration.Tags is { Count: > 0 } tags)
+ {
+ var actualTags = await _client.ListQueueTagsAsync(new ListQueueTagsRequest { QueueUrl = endpoint.Url }, cancellationToken).ConfigureAwait(false);
+ foreach (var tag in tags)
+ if (actualTags.Tags?.TryGetValue(tag.Key, out var value) != true || value != tag.Value)
+ differences.Add($"SQS queue '{endpoint.Declaration.QueueName}': declared tag '{tag.Key}' differs. Reconcile it through infrastructure configuration.");
+ }
+ if (actual.Attributes?.TryGetValue("MaximumMessageSize", out var maximum) == true)
+ endpoint.Capabilities = endpoint.Capabilities with { MaxMessageBytes = long.Parse(maximum, CultureInfo.InvariantCulture) };
+ }
+ return new(differences);
+ }
+
+ private static bool AttributeEquals(string name, string expected, string actual)
+ {
+ if (name is not ("Policy" or "RedrivePolicy" or "RedriveAllowPolicy")) return expected == actual;
+ using var expectedJson = JsonDocument.Parse(expected);
+ using var actualJson = JsonDocument.Parse(actual);
+ return JsonElement.DeepEquals(expectedJson.RootElement, actualJson.RootElement);
+ }
+
+ public ValueTask SendAsync(OutgoingMessage message, CancellationToken cancellationToken) =>
+ GetEndpoint(message.Destination).Tracing is { } tracing ? tracing.SendAsync(message, cancellationToken) : SendCoreAsync(message, cancellationToken);
+
+ [AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder))]
+ private async ValueTask SendCoreAsync(OutgoingMessage message, CancellationToken cancellationToken)
+ {
+ var endpoint = Validate(message, cancellationToken);
+ var state = _operations.Rent();
+ state.Used = 1;
+ var activity = CurrentActivity();
+ Enrich(activity, endpoint.Url!, null);
+ try
+ {
+ var size = state.Messages[0].Prepare(message, endpoint.Url!, endpoint.Fifo);
+ ValidateSize(endpoint, size);
+ var response = await _client.SendMessageAsync(state.Messages[0].Request, cancellationToken).ConfigureAwait(false);
+ Enrich(activity, endpoint.Url!, response.ResponseMetadata?.RequestId);
+ }
+ catch (AmazonSQSException error)
+ {
+ Enrich(activity, endpoint.Url!, error.RequestId);
+ throw;
+ }
+ finally { _operations.Return(state); }
+ }
+
+ [AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder))]
+ public async ValueTask SendBatchAsync(ReadOnlyMemory messages, CancellationToken cancellationToken)
+ {
+ Check(cancellationToken);
+ var start = 0;
+ while (start < messages.Length)
+ {
+ var destination = messages.Span[start].Destination;
+ var end = start + 1;
+ while (end < messages.Length && messages.Span[end].Destination == destination) end++;
+ var group = messages.Slice(start, end - start);
+ var tracing = GetEndpoint(destination).Tracing;
+ if (tracing is null) await SendBatchCoreAsync(group, cancellationToken).ConfigureAwait(false);
+ else await tracing.SendBatchAsync(group, cancellationToken).ConfigureAwait(false);
+ start = end;
+ }
+ }
+
+ [AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder))]
+ private async ValueTask SendBatchCoreAsync(ReadOnlyMemory messages, CancellationToken cancellationToken)
+ {
+ Check(cancellationToken);
+ if (messages.IsEmpty) return;
+ var endpoint = GetEndpoint(messages.Span[0].Destination);
+ var state = _operations.Rent();
+ var count = 0;
+ var bytes = 0;
+ var batchStart = 0;
+ state.Batch.QueueUrl = endpoint.Url;
+ try
+ {
+ for (var i = 0; i < messages.Length; i++)
+ {
+ Validate(messages.Span[i], cancellationToken);
+ if (count == 10)
+ {
+ await FlushAsync(state, batchStart, cancellationToken).ConfigureAwait(false);
+ for (var j = 0; j < count; j++) state.Messages[j].Clear();
+ state.Batch.Entries.Clear();
+ state.Used = 0;
+ count = bytes = 0;
+ batchStart = i;
+ }
+ var pending = state.Messages[count];
+ state.Used = count + 1;
+ var size = pending.Prepare(messages.Span[i], endpoint.Url!, endpoint.Fifo);
+ ValidateSize(endpoint, size);
+ if (count > 0 && bytes + size > 1_048_576)
+ {
+ await FlushAsync(state, batchStart, cancellationToken).ConfigureAwait(false);
+ for (var j = 0; j < count; j++) state.Messages[j].Clear();
+ state.Batch.Entries.Clear();
+ // Carry the already prepared request across a byte boundary without repeating its callback.
+ (state.Messages[0], state.Messages[count]) = (pending, state.Messages[0]);
+ state.Used = 1;
+ count = bytes = 0;
+ batchStart = i;
+ }
+ pending.CopyToEntry();
+ pending.Entry.Id = state.Ids[count];
+ state.Batch.Entries.Add(pending.Entry);
+ count++;
+ bytes += size;
+ }
+ if (count > 0) await FlushAsync(state, batchStart, cancellationToken).ConfigureAwait(false);
+ }
+ finally { _operations.Return(state); }
+ }
+
+ [AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder))]
+ private async ValueTask FlushAsync(SqsOperationState state, int offset, CancellationToken cancellationToken)
+ {
+ var activity = CurrentActivity();
+ Enrich(activity, state.Batch.QueueUrl, null);
+ try
+ {
+ var response = await _client.SendMessageBatchAsync(state.Batch, cancellationToken).ConfigureAwait(false);
+ Enrich(activity, state.Batch.QueueUrl, response.ResponseMetadata?.RequestId);
+ if (response.Failed is { Count: > 0 }) throw new AmazonSqsBatchException(response, offset);
+ }
+ catch (AmazonSQSException error)
+ {
+ Enrich(activity, state.Batch.QueueUrl, error.RequestId);
+ throw;
+ }
+ }
+
+ private Activity? CurrentActivity() => Activity.Current is { } activity && ReferenceEquals(activity.Source, _tracing?.Source) ? activity : null;
+ private static void Enrich(Activity? activity, string url, string? requestId)
+ {
+ activity?.SetTag("aws.sqs.queue.url", url);
+ if (requestId is not null) activity?.SetTag("aws.request_id", requestId);
+ }
+
+ private Endpoint Validate(OutgoingMessage message, CancellationToken cancellationToken)
+ {
+ Check(cancellationToken);
+ var endpoint = GetEndpoint(message.Destination);
+ if (endpoint.Url is null) throw new InvalidOperationException($"SQS transport '{Name}': start the host or apply topology before sending to '{message.Destination}'.");
+ if (message.IsTombstone) throw new NotSupportedException("SQS does not support native tombstones.");
+ if (message.OrderingKey is not null && !endpoint.Fifo)
+ throw new NotSupportedException("SQS ordering keys require a FIFO queue.");
+ return endpoint;
+ }
+
+ private static void ValidateSize(Endpoint endpoint, int size)
+ {
+ if (size > (endpoint.Capabilities.MaxMessageBytes ?? 1_048_576))
+ throw new InvalidOperationException($"SQS message for '{endpoint.Declaration.QueueName}' exceeds the native message byte limit, including attributes.");
+ }
+
+ private void Check(CancellationToken cancellationToken)
+ {
+ ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this);
+ cancellationToken.ThrowIfCancellationRequested();
+ }
+
+ public async Task StartAsync(CancellationToken cancellationToken)
+ {
+ Check(cancellationToken);
+ // None skips topology validation/provisioning, but the native send API still requires queue URLs.
+ foreach (var endpoint in _endpoints.Values)
+ if (endpoint.Url is null)
+ endpoint.Url = (await _client.GetQueueUrlAsync(endpoint.Declaration.QueueName, cancellationToken).ConfigureAwait(false)).QueueUrl;
+ }
+ public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
+ public ValueTask DisposeAsync()
+ {
+ if (Interlocked.Exchange(ref _disposed, 1) == 0 && _ownsClient) _client.Dispose();
+ return ValueTask.CompletedTask;
+ }
+
+ private sealed class Endpoint
+ {
+ internal Endpoint(CreateQueueRequest declaration)
+ {
+ Declaration = declaration;
+ Fifo = declaration.QueueName.EndsWith(".fifo", StringComparison.Ordinal);
+ Capabilities = new() { OrderedByKey = Fifo, MaxBatchSize = 10, MaxDeliveryDelay = Fifo ? null : TimeSpan.FromMinutes(15) };
+ if (declaration.Attributes?.TryGetValue("MaximumMessageSize", out var maximum) == true)
+ Capabilities = Capabilities with { MaxMessageBytes = long.Parse(maximum, CultureInfo.InvariantCulture) };
+ }
+ internal CreateQueueRequest Declaration { get; }
+ internal bool Fifo { get; }
+ internal string? Url { get; set; }
+ internal TransportCapabilities Capabilities { get; set; }
+ internal SendTracing? Tracing { get; set; }
+ }
+}
diff --git a/tests/Relayer.Tests/SqsSendLocalStackTests.cs b/tests/Relayer.Tests/SqsSendLocalStackTests.cs
new file mode 100644
index 000000000..d68b53d7d
--- /dev/null
+++ b/tests/Relayer.Tests/SqsSendLocalStackTests.cs
@@ -0,0 +1,109 @@
+using Amazon.Runtime;
+using Amazon.SQS;
+using Amazon.SQS.Model;
+using DotNet.Testcontainers.Builders;
+using Relayer.AmazonSqs;
+
+namespace Relayer.Tests;
+
+public class SqsSendLocalStackTests
+{
+ [Test]
+ public async Task Standard_fifo_batches_delays_and_read_only_topology_round_trip()
+ {
+ using var timeout = new CancellationTokenSource(TimeSpan.FromMinutes(3));
+ var token = timeout.Token;
+ var containerBuilder = new ContainerBuilder("localstack/localstack:4.10.0")
+ .WithEnvironment("SERVICES", "sqs")
+ .WithPortBinding(4566, true)
+ .WithWaitStrategy(Wait.ForUnixContainer().UntilMessageIsLogged("Ready\\."));
+ if (OperatingSystem.IsLinux()) containerBuilder = containerBuilder.WithPortBinding("20000-29999", "4566");
+ await using var container = containerBuilder.Build();
+ var externalUrl = Environment.GetEnvironmentVariable("RELAYER_SQS_SERVICE_URL");
+ if (externalUrl is null) await container.StartAsync(token);
+ using var client = new AmazonSQSClient(new BasicAWSCredentials("test", "test"), new AmazonSQSConfig
+ {
+ ServiceURL = externalUrl ?? $"http://{container.Hostname}:{container.GetMappedPublicPort(4566)}",
+ AuthenticationRegion = "us-east-1",
+ });
+ var standard = "relayer-" + Guid.NewGuid().ToString("N");
+ var fifo = standard + ".fifo";
+ var options = new AmazonSqsTransportOptions { SqsClient = client };
+ options.Queues.Add(new(standard) { Attributes = new() { ["MaximumMessageSize"] = "4096" }, Tags = new() { ["application"] = "relayer" } });
+ options.Queues.Add(new(fifo) { Attributes = new() { ["FifoQueue"] = "true" } });
+ var urls = new List();
+ try
+ {
+ await using var transport = new SqsSendTransport("localstack", client, false, options);
+ var missing = await transport.ApplyTopologyAsync(TopologyMode.Validate, token);
+ await Assert.That(missing.Differences.Count).IsEqualTo(2);
+ await Assert.That((await transport.ApplyTopologyAsync(TopologyMode.Provision, token)).Differences.Count).IsEqualTo(0);
+ var standardUrl = (await client.GetQueueUrlAsync(standard, token)).QueueUrl;
+ var fifoUrl = (await client.GetQueueUrlAsync(fifo, token)).QueueUrl;
+ urls.Add(standardUrl);
+ urls.Add(fifoUrl);
+ await Assert.That((await transport.ApplyTopologyAsync(TopologyMode.Validate, token)).Differences.Count).IsEqualTo(0);
+ await Assert.That(transport.GetCapabilities(standard).MaxMessageBytes).IsEqualTo(4096);
+
+ KeyValuePair[] headers = [new("ce_id", new("event-id")), new("ce_type", new("orders.created;v=1")), new("content-type", new("application/json")), new("traceparent", new("creation-context"))];
+ await transport.SendAsync(new(standard, "{\"value\":1}"u8.ToArray(), headers), token);
+ var received = await ReceiveAsync(client, standardUrl, token);
+ await Assert.That(received.Body).IsEqualTo("{\"value\":1}");
+ await Assert.That(received.MessageAttributes["ce_type"].StringValue).IsEqualTo("orders.created;v=1");
+ await Assert.That(received.MessageAttributes["content-type"].StringValue).IsEqualTo("application/json");
+ await Assert.That(received.MessageAttributes["traceparent"].StringValue).IsEqualTo("creation-context");
+ await client.DeleteMessageAsync(standardUrl, received.ReceiptHandle, token);
+
+ var batch = new OutgoingMessage[12];
+ for (var i = 0; i < batch.Length; i++)
+ batch[i] = new(fifo, System.Text.Encoding.UTF8.GetBytes(i.ToString()),
+ new KeyValuePair[] { new("ce_id", new WireString("event-" + i)) }, new WireString("customer"));
+ await transport.SendBatchAsync(batch, token);
+ for (var i = 0; i < batch.Length; i++)
+ {
+ var ordered = await ReceiveAsync(client, fifoUrl, token);
+ await Assert.That(ordered.Body).IsEqualTo(i.ToString());
+ await Assert.That(ordered.Attributes["MessageGroupId"]).IsEqualTo("customer");
+ await Assert.That(ordered.Attributes["MessageDeduplicationId"]).IsEqualTo("event-" + i);
+ await client.DeleteMessageAsync(fifoUrl, ordered.ReceiptHandle, token);
+ }
+ // Replaying the stable event identity uses native FIFO deduplication, without a second delivery.
+ await transport.SendAsync(batch[0], token);
+ var duplicate = await client.ReceiveMessageAsync(new ReceiveMessageRequest { QueueUrl = fifoUrl, WaitTimeSeconds = 1 }, token);
+ await Assert.That(duplicate.Messages?.Count ?? 0).IsEqualTo(0);
+
+ var due = DateTimeOffset.UtcNow.AddSeconds(2);
+ await transport.SendAsync(new(standard, "scheduled"u8.ToArray(), deliverAt: due), token);
+ var early = await client.ReceiveMessageAsync(new ReceiveMessageRequest { QueueUrl = standardUrl, WaitTimeSeconds = 0 }, token);
+ await Assert.That(early.Messages?.Count ?? 0).IsEqualTo(0);
+ var delayed = await ReceiveAsync(client, standardUrl, token);
+ await Assert.That(DateTimeOffset.UtcNow >= due).IsTrue();
+ await Assert.That(delayed.Body).IsEqualTo("scheduled");
+ await client.DeleteMessageAsync(standardUrl, delayed.ReceiptHandle, token);
+
+ options.Queues[0].Attributes["MaximumMessageSize"] = "8192";
+ await Assert.That((await transport.ApplyTopologyAsync(TopologyMode.Provision, token)).Differences.Single()).Contains("MaximumMessageSize");
+ var unchanged = await client.GetQueueAttributesAsync(standardUrl, ["MaximumMessageSize"], token);
+ await Assert.That(unchanged.Attributes["MaximumMessageSize"]).IsEqualTo("4096");
+ options.Queues[0].Attributes["MaximumMessageSize"] = "4096";
+ options.Queues[0].Tags["application"] = "changed";
+ await Assert.That((await transport.ApplyTopologyAsync(TopologyMode.Validate, token)).Differences.Single()).Contains("tag 'application'");
+ var tags = await client.ListQueueTagsAsync(new ListQueueTagsRequest { QueueUrl = standardUrl }, token);
+ await Assert.That(tags.Tags["application"]).IsEqualTo("relayer");
+ }
+ finally
+ {
+ foreach (var url in urls) await client.DeleteQueueAsync(url, CancellationToken.None);
+ }
+ }
+
+ private static async Task ReceiveAsync(IAmazonSQS client, string url, CancellationToken token)
+ {
+ var response = await client.ReceiveMessageAsync(new ReceiveMessageRequest
+ {
+ QueueUrl = url, WaitTimeSeconds = 10, MaxNumberOfMessages = 1,
+ MessageAttributeNames = ["All"], MessageSystemAttributeNames = ["All"],
+ }, token);
+ return response.Messages?.SingleOrDefault() ?? throw new InvalidOperationException("LocalStack did not deliver the expected SQS message.");
+ }
+}
diff --git a/tests/Relayer.Tests/SqsSendTests.cs b/tests/Relayer.Tests/SqsSendTests.cs
new file mode 100644
index 000000000..0221446ee
--- /dev/null
+++ b/tests/Relayer.Tests/SqsSendTests.cs
@@ -0,0 +1,391 @@
+using System.Diagnostics;
+using System.Text;
+using Amazon.Runtime;
+using Amazon.SQS;
+using Amazon.SQS.Model;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Hosting;
+using Microsoft.Extensions.Options;
+using Relayer.AmazonSqs;
+using Relayer.Transports;
+
+namespace Relayer.Tests;
+
+public class SqsSendTests
+{
+ [Test]
+ public async Task Hosted_sender_serializes_the_real_generated_envelope()
+ {
+ using var client = new SqsTestClient();
+ var app = Host.CreateApplicationBuilder();
+ app.Services.AddRelayer(builder =>
+ {
+ builder.AddMessageTypesFromThisAssembly();
+ builder.AmazonSqs("test", sqs =>
+ {
+ sqs.Options.Configure(o => { o.SqsClient = client; o.Queues.Add(new("orders")); });
+ sqs.Send("orders");
+ });
+ });
+ using var host = app.Build();
+ await host.StartAsync();
+ try
+ {
+ await using var scope = host.Services.CreateAsyncScope();
+ await scope.ServiceProvider.GetRequiredService().SendNowAsync(new Order());
+ var sent = client.Sent.Single();
+ await Assert.That(sent.Body).IsEqualTo("{}");
+ await Assert.That(sent.Attributes["ce_type"]).Contains("sqs.test.order");
+ await Assert.That(sent.Attributes["ce_specversion"]).IsEqualTo("1.0");
+ await Assert.That(sent.Attributes["content-type"]).IsEqualTo("application/json");
+ await Assert.That(sent.Attributes.Count <= 10).IsTrue();
+ }
+ finally { await host.StopAsync(); }
+ }
+
+ [Test]
+ public async Task Named_registration_preserves_options_and_caller_owned_clients()
+ {
+ using var first = new SqsTestClient();
+ using var second = new SqsTestClient();
+ var config = new AmazonSQSConfig { ServiceURL = "http://localhost:4566" };
+ var services = new ServiceCollection();
+ services.AddRelayer(builder =>
+ {
+ builder.AmazonSqs("first", sqs =>
+ {
+ sqs.Options.Configure(o => { o.SqsClient = first; o.Sqs = config; o.Queues.Add(new("orders")); });
+ sqs.Send("orders");
+ });
+ builder.AmazonSqs("second", sqs =>
+ {
+ sqs.Options.Configure(o => { o.SqsClient = second; o.Queues.Add(new("audit")); });
+ sqs.Send("audit");
+ });
+ });
+ await using (var provider = services.BuildServiceProvider())
+ {
+ var options = provider.GetRequiredService>();
+ await Assert.That(options.Get("first").Sqs).IsSameReferenceAs(config);
+ var transports = provider.GetServices().ToArray();
+ foreach (var transport in transports) await transport.StartAsync(default);
+ await transports[0].SendAsync(new("orders", "{}"u8.ToArray()), default);
+ await transports[1].SendAsync(new("audit", "{}"u8.ToArray()), default);
+ await Assert.That(first.Sent.Single().Url).Contains("orders");
+ await Assert.That(second.Sent.Single().Url).Contains("audit");
+ }
+ await Assert.That(first.Disposals).IsEqualTo(0);
+ await Assert.That(second.Disposals).IsEqualTo(0);
+ }
+
+ [Test]
+ public async Task Headers_callbacks_fifo_identity_and_state_are_preserved()
+ {
+ using var client = new SqsTestClient();
+ await using var transport = Transport(client);
+ await transport.StartAsync(default);
+ var calls = 0;
+ var options = new SendOptions().AmazonSqs(request =>
+ {
+ calls++;
+ request.MessageAttributes["native"] = new() { DataType = "String", StringValue = "value" };
+ request.MessageAttributes["traceparent"] = new() { DataType = "String", StringValue = "wrong" };
+ request.MessageDeduplicationId = "wrong";
+ });
+ KeyValuePair[] headers = [new("ce_id", new("event-1")), new("traceparent", new("creation"u8.ToArray()))];
+ await transport.SendAsync(new("ordered.fifo", "héllo"u8.ToArray(), headers, new WireString("customer"), options: options), default);
+ await transport.SendAsync(new("orders", "{}"u8.ToArray()), default);
+ var sent = client.Sent;
+ await Assert.That(calls).IsEqualTo(1);
+ await Assert.That(sent[0].Body).IsEqualTo("héllo");
+ await Assert.That(sent[0].Group).IsEqualTo("customer");
+ await Assert.That(sent[0].Deduplication).IsEqualTo("event-1");
+ await Assert.That(sent[0].Attributes["traceparent"]).IsEqualTo("creation");
+ await Assert.That(sent[0].Attributes["native"]).IsEqualTo("value");
+ await Assert.That(sent[1].Group).IsNull();
+ await Assert.That(sent[1].Deduplication).IsNull();
+ await Assert.That(sent[1].Attributes.Count).IsEqualTo(0);
+ await Assert.That(client.Requests[0]).IsSameReferenceAs(client.Requests[1]);
+ }
+
+ [Test]
+ public async Task Native_replacement_dictionaries_remain_caller_owned()
+ {
+ using var client = new SqsTestClient();
+ await using var transport = Transport(client);
+ await transport.StartAsync(default);
+ var attributes = new Dictionary { ["native"] = new() { DataType = "String", StringValue = "keep" } };
+ var options = new SendOptions().AmazonSqs(request => request.MessageAttributes = attributes);
+ await transport.SendAsync(new("orders", "{}"u8.ToArray(), options: options), default);
+ await Assert.That(attributes["native"].StringValue).IsEqualTo("keep");
+ await Assert.That(attributes.Count).IsEqualTo(1);
+ }
+
+ [Test]
+ public async Task Batches_split_by_count_bytes_and_destination_without_repeating_callbacks()
+ {
+ using var client = new SqsTestClient();
+ await using var transport = Transport(client);
+ await transport.StartAsync(default);
+ var calls = 0;
+ var options = new SendOptions().AmazonSqs(_ => calls++);
+ var messages = new List();
+ for (var i = 0; i < 11; i++) messages.Add(new("orders", "{}"u8.ToArray(), options: options));
+ var large = Encoding.UTF8.GetBytes(new string('x', 600_000));
+ messages.Add(new("orders", large, options: options));
+ messages.Add(new("orders", large, options: options));
+ messages.Add(new("ordered.fifo", "{}"u8.ToArray(), orderingKey: new WireString("key"), options:
+ new SendOptions().AmazonSqs(request => { calls++; request.MessageDeduplicationId = "native-id"; })));
+ await transport.SendBatchAsync(messages.ToArray(), default);
+ await Assert.That(client.Batches.Select(batch => batch.Length).SequenceEqual(new[] { 10, 2, 1, 1 })).IsTrue();
+ await Assert.That(calls).IsEqualTo(messages.Count);
+ await Assert.That(client.Batches.All(batch => batch.Select(item => item.Id).SequenceEqual(Enumerable.Range(0, batch.Length).Select(i => i.ToString())))).IsTrue();
+ await Assert.That(client.Batches[^1][0].Message.Group).IsEqualTo("key");
+ }
+
+ [Test]
+ public async Task Partial_batch_failure_exposes_native_response_and_does_not_retry_successes()
+ {
+ using var client = new SqsTestClient { FailBatch = true };
+ await using var transport = Transport(client);
+ await transport.StartAsync(default);
+ AmazonSqsBatchException? failure = null;
+ try { await transport.SendBatchAsync(new OutgoingMessage[] { new("orders", "{}"u8.ToArray()), new("orders", "{}"u8.ToArray()) }, default); }
+ catch (AmazonSqsBatchException error) { failure = error; }
+ await Assert.That(failure).IsNotNull();
+ await Assert.That(failure!.Response.Failed.Single().Id).IsEqualTo("1");
+ await Assert.That(failure.Response.Successful.Single().Id).IsEqualTo("0");
+ await Assert.That(failure.BatchOffset).IsEqualTo(0);
+ await Assert.That(client.Batches.Count).IsEqualTo(1);
+ await transport.SendAsync(new("orders", "{}"u8.ToArray()), default);
+ await Assert.That(client.Sent.Single().Attributes.Count).IsEqualTo(0);
+ }
+
+ [Test]
+ public async Task Timers_use_native_seconds_and_do_not_leak_to_following_messages()
+ {
+ using var client = new SqsTestClient();
+ await using var transport = Transport(client);
+ await transport.StartAsync(default);
+ await transport.SendAsync(new("orders", "{}"u8.ToArray(), deliverAt: DateTimeOffset.UtcNow.AddMinutes(10)), default);
+ await transport.SendAsync(new("orders", "{}"u8.ToArray()), default);
+ await Assert.That(client.Sent[0].Delay is > 590 and <= 600).IsTrue();
+ await Assert.That(client.Sent[1].Delay).IsNull();
+ await transport.SendAsync(new("orders", "{}"u8.ToArray(), deliverAt: DateTimeOffset.UtcNow.AddMinutes(-1),
+ options: new SendOptions().AmazonSqs(request => request.DelaySeconds = 900)), default);
+ await Assert.That(client.Sent[2].Delay).IsEqualTo(0);
+ await Assert.That(async () => await transport.SendAsync(new("orders", "{}"u8.ToArray(), deliverAt: DateTimeOffset.UtcNow.AddHours(1)), default)).Throws();
+ await Assert.That(async () => await transport.SendAsync(new("ordered.fifo", "{}"u8.ToArray(), orderingKey: new WireString("key"), deliverAt: DateTimeOffset.UtcNow.AddMinutes(1)), default)).Throws();
+ }
+
+ [Test]
+ public async Task Invalid_attributes_payload_ordering_and_size_fail_without_native_sends()
+ {
+ using var client = new SqsTestClient();
+ await using var transport = Transport(client);
+ await transport.StartAsync(default);
+ var headers = Enumerable.Range(0, 11).Select(i => new KeyValuePair("h" + i, new("value"))).ToArray();
+ await Assert.That(async () => await transport.SendAsync(new("orders", "{}"u8.ToArray(), headers), default)).Throws();
+ await Assert.That(async () => await transport.SendAsync(new("orders", new byte[] { 0xff }), default)).Throws();
+ await Assert.That(async () => await transport.SendAsync(new("orders", "{}"u8.ToArray(), orderingKey: new WireString("key")), default)).Throws();
+ await Assert.That(async () => await transport.SendAsync(new("ordered.fifo", "{}"u8.ToArray()), default)).Throws();
+ await Assert.That(async () => await transport.SendAsync(new("orders", Encoding.UTF8.GetBytes(new string('x', 1_048_577))), default)).Throws();
+ await Assert.That(client.Sent.Count).IsEqualTo(0);
+ await transport.SendAsync(new("orders", "{}"u8.ToArray()), default);
+ await Assert.That(client.Sent.Single().Attributes.Count).IsEqualTo(0);
+ }
+
+ [Test]
+ public async Task Concurrent_sends_have_independent_borrowed_storage()
+ {
+ using var client = new SqsTestClient { Gate = new(TaskCreationOptions.RunContinuationsAsynchronously) };
+ await using var transport = Transport(client);
+ await transport.StartAsync(default);
+ var first = transport.SendAsync(new("orders", "first"u8.ToArray()), default);
+ var second = transport.SendAsync(new("orders", "second"u8.ToArray()), default);
+ await Assert.That(client.Requests.Count).IsEqualTo(2);
+ await Assert.That(ReferenceEquals(client.Requests[0], client.Requests[1])).IsFalse();
+ await Assert.That(client.Requests[0].MessageBody).IsEqualTo("first");
+ await Assert.That(client.Requests[1].MessageBody).IsEqualTo("second");
+ client.Gate.SetResult();
+ await first;
+ await second;
+ }
+
+ [Test]
+ public async Task Topology_validate_is_read_only_and_provision_never_updates_existing_queues()
+ {
+ using var client = new SqsTestClient { Missing = true };
+ var options = Options(client);
+ options.Queues[0].Attributes = new() { ["MaximumMessageSize"] = "4096" };
+ await using var transport = new SqsSendTransport("test", client, false, options);
+ await Assert.That((await transport.ApplyTopologyAsync(TopologyMode.None, default)).Differences.Count).IsEqualTo(0);
+ await Assert.That(client.Lookups).IsEqualTo(0);
+ await Assert.That((await transport.ApplyTopologyAsync(TopologyMode.Validate, default)).Differences.Count).IsEqualTo(2);
+ await Assert.That(client.Creates.Count).IsEqualTo(0);
+ var provision = await transport.ApplyTopologyAsync(TopologyMode.Provision, default);
+ await Assert.That(provision.Differences.Count).IsEqualTo(1);
+ await Assert.That(client.Creates.Count).IsEqualTo(1);
+ await Assert.That(client.Creates[0]).IsSameReferenceAs(options.Queues[0]);
+ await Assert.That(transport.GetCapabilities("orders").MaxMessageBytes).IsEqualTo(1_048_576);
+ await Assert.That(transport.GetCapabilities("ordered.fifo").OrderedByKey).IsTrue();
+ await transport.ApplyTopologyAsync(TopologyMode.Provision, default);
+ await Assert.That(client.Creates.Count).IsEqualTo(1);
+ }
+
+ [Test]
+ public async Task Native_policy_json_compares_structurally_and_reports_real_drift()
+ {
+ using var client = new SqsTestClient();
+ var options = Options(client);
+ options.Queues[0].Attributes = new() { ["Policy"] = "{\"Version\":\"2012-10-17\",\"Statement\":[]}" };
+ client.NativeAttributes["Policy"] = "{ \"Statement\": [], \"Version\": \"2012-10-17\" }";
+ await using var transport = new SqsSendTransport("test", client, false, options);
+ await Assert.That((await transport.ApplyTopologyAsync(TopologyMode.Validate, default)).Differences.Count).IsEqualTo(0);
+ options.Queues[0].Attributes["Policy"] = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Deny\"}]}";
+ await Assert.That((await transport.ApplyTopologyAsync(TopologyMode.Provision, default)).Differences.Single()).Contains("Policy");
+ await Assert.That(client.Creates.Count).IsEqualTo(0);
+ }
+
+ [Test]
+ public async Task Declarations_and_unsupported_receivers_fail_early()
+ {
+ var options = new AmazonSqsTransportOptions();
+ options.Queues.Add(new("wrong.fifo"));
+ await Assert.That(() => SqsSendTransport.ValidateDeclarations("test", options, [])).Throws();
+ options.Queues.Clear();
+ await Assert.That(() => SqsSendTransport.ValidateDeclarations("test", options, ["missing"])).Throws();
+ var services = new ServiceCollection();
+ services.AddRelayer(builder => builder.AmazonSqs("test", sqs => sqs.Consume("orders", consumer => consumer.Handler())));
+ await using var provider = services.BuildServiceProvider();
+ await Assert.That(() => provider.GetServices().ToArray()).Throws();
+ }
+
+ [Test]
+ public async Task Cancellation_disposal_and_failed_callbacks_return_clean_state()
+ {
+ var client = new SqsTestClient();
+ var transport = new SqsSendTransport("test", client, true, Options(client));
+ await transport.StartAsync(default);
+ using var cancelled = new CancellationTokenSource();
+ cancelled.Cancel();
+ await Assert.That(async () => await transport.SendAsync(new("orders", "{}"u8.ToArray()), cancelled.Token)).Throws();
+ var options = new SendOptions().AmazonSqs(request => { request.MessageGroupId = "bad"; throw new InvalidOperationException("callback"); });
+ await Assert.That(async () => await transport.SendAsync(new("orders", "{}"u8.ToArray(), options: options), default)).Throws();
+ await transport.SendAsync(new("orders", "{}"u8.ToArray()), default);
+ await Assert.That(client.Sent.Single().Group).IsNull();
+ await transport.DisposeAsync();
+ await transport.DisposeAsync();
+ await Assert.That(client.Disposals).IsEqualTo(1);
+ await Assert.That(async () => await transport.SendAsync(new("orders", "{}"u8.ToArray()), default)).Throws();
+ }
+
+ [Test]
+ public async Task Send_telemetry_uses_sqs_system_queue_url_and_native_request_id()
+ {
+ using var client = new SqsTestClient();
+ var services = new ServiceCollection();
+ services.AddRelayer(_ => { });
+ await using var provider = services.BuildServiceProvider();
+ var tracing = provider.GetRequiredService();
+ var spans = new List();
+ using var listener = new ActivityListener
+ {
+ ShouldListenTo = source => ReferenceEquals(source, tracing.Source),
+ Sample = (ref ActivityCreationOptions _) => ActivitySamplingResult.AllDataAndRecorded,
+ ActivityStopped = spans.Add,
+ };
+ ActivitySource.AddActivityListener(listener);
+ await using var transport = new SqsSendTransport("test", client, false, Options(client), tracing);
+ await transport.StartAsync(default);
+ await transport.SendAsync(new("orders", "{}"u8.ToArray()), default);
+ var span = spans.Single();
+ await Assert.That(span.GetTagItem("messaging.system")).IsEqualTo("aws_sqs");
+ await Assert.That(span.GetTagItem("aws.sqs.queue.url")).IsEqualTo("http://localhost/queues/orders");
+ await Assert.That(span.GetTagItem("aws.request_id")).IsEqualTo("request-1");
+ await Assert.That(client.Sent.Single().Attributes.ContainsKey("traceparent")).IsTrue();
+ client.FailBatch = true;
+ await Assert.That(async () => await transport.SendBatchAsync(new OutgoingMessage[] { new("orders", "{}"u8.ToArray()) }, default)).Throws();
+ var failed = spans.Last();
+ await Assert.That(failed.GetTagItem("aws.request_id")).IsEqualTo("batch-request");
+ await Assert.That(failed.GetTagItem("aws.sqs.queue.url")).IsEqualTo("http://localhost/queues/orders");
+ await Assert.That(failed.Status).IsEqualTo(ActivityStatusCode.Error);
+ }
+
+ internal static AmazonSqsTransportOptions Options(IAmazonSQS client)
+ {
+ var options = new AmazonSqsTransportOptions { SqsClient = client };
+ options.Queues.Add(new("orders"));
+ options.Queues.Add(new("ordered.fifo") { Attributes = new() { ["FifoQueue"] = "true", ["ContentBasedDeduplication"] = "true" } });
+ return options;
+ }
+
+ private static SqsSendTransport Transport(IAmazonSQS client) => new("test", client, false, Options(client));
+ [Message("sqs.test.order")]
+ public sealed record Order;
+ [Message("sqs.test.audit")]
+ public sealed record Audit;
+ public sealed class OrderHandler : IHandler
+ {
+ public ValueTask HandleAsync(Order message, MessageContext context, CancellationToken cancellationToken) => ValueTask.CompletedTask;
+ }
+}
+
+internal sealed record SqsSent(string Url, string Body, string? Group, string? Deduplication, int? Delay, Dictionary Attributes);
+
+internal sealed class SqsTestClient() : AmazonSQSClient(new AnonymousAWSCredentials(), new AmazonSQSConfig { ServiceURL = "http://localhost:4566" })
+{
+ internal readonly List Sent = [];
+ internal readonly List Requests = [];
+ internal readonly List<(string Id, SqsSent Message)[]> Batches = [];
+ internal readonly List Creates = [];
+ internal readonly Dictionary NativeAttributes = new() { ["MaximumMessageSize"] = "1048576", ["FifoQueue"] = "true", ["ContentBasedDeduplication"] = "true" };
+ internal bool FailBatch;
+ internal bool Missing;
+ internal int Lookups;
+ internal int Disposals;
+ internal TaskCompletionSource? Gate;
+
+ public override async Task SendMessageAsync(SendMessageRequest request, CancellationToken cancellationToken = default)
+ {
+ Requests.Add(request);
+ Sent.Add(Snapshot(request));
+ if (Gate is not null) await Gate.Task.WaitAsync(cancellationToken);
+ return new() { ResponseMetadata = new() { RequestId = "request-1" } };
+ }
+
+ public override Task SendMessageBatchAsync(SendMessageBatchRequest request, CancellationToken cancellationToken = default)
+ {
+ Batches.Add(request.Entries.Select(entry => (entry.Id, Snapshot(new()
+ {
+ QueueUrl = request.QueueUrl, MessageBody = entry.MessageBody, MessageGroupId = entry.MessageGroupId,
+ MessageDeduplicationId = entry.MessageDeduplicationId, DelaySeconds = entry.DelaySeconds, MessageAttributes = entry.MessageAttributes,
+ }))).ToArray());
+ return Task.FromResult(new SendMessageBatchResponse
+ {
+ Successful = [new() { Id = "0" }],
+ Failed = FailBatch ? [new() { Id = "1", Code = "InvalidMessageContents", SenderFault = true }] : [],
+ ResponseMetadata = new() { RequestId = "batch-request" },
+ });
+ }
+
+ public override Task GetQueueUrlAsync(string queueName, CancellationToken cancellationToken = default)
+ {
+ Lookups++;
+ if (Missing) throw new QueueDoesNotExistException("missing");
+ return Task.FromResult(new GetQueueUrlResponse { QueueUrl = "http://localhost/queues/" + queueName });
+ }
+ public override Task CreateQueueAsync(CreateQueueRequest request, CancellationToken cancellationToken = default)
+ {
+ Creates.Add(request);
+ Missing = false;
+ return Task.FromResult(new CreateQueueResponse { QueueUrl = "http://localhost/queues/" + request.QueueName });
+ }
+ public override Task GetQueueAttributesAsync(GetQueueAttributesRequest request, CancellationToken cancellationToken = default) =>
+ Task.FromResult(new GetQueueAttributesResponse { Attributes = NativeAttributes });
+ protected override void Dispose(bool disposing) { if (disposing) Disposals++; base.Dispose(disposing); }
+
+ private static SqsSent Snapshot(SendMessageRequest request) => new(request.QueueUrl, request.MessageBody, request.MessageGroupId,
+ request.MessageDeduplicationId, request.DelaySeconds,
+ request.MessageAttributes?.ToDictionary(item => item.Key, item => item.Value.StringValue) ?? []);
+}
diff --git a/website/docs/roadmap.md b/website/docs/roadmap.md
index 03d9b9e98..aed51e770 100644
--- a/website/docs/roadmap.md
+++ b/website/docs/roadmap.md
@@ -34,6 +34,7 @@ Relayer is in early development. Track progress in [GitHub issues](https://githu
- [Bounded partition completion watermarks](transports/partition-completion.md) and the core [fallback partition scheduler](transports/partition-scheduler.md) for transport authors whose clients have no equivalent native runtime, with key ordering, bounded concurrency, backpressure and ownership-fenced drain. Kafka parallel receive remains planned and will wrap Dekaf's `RunPartitionedAsync`.
- Explicit [message upcaster chains](guides/messages.md#versioning-and-unknown-types), composed at startup for single-message and batch handlers.
- [Service Bus transport](transports/service-bus.md): named sending and queue/subscription processors, owned/caller-owned clients, native sessions, manual settlement, durable failure handling, telemetry, optional keyed health adapters and Testcontainers conformance. Native send batching, scheduling and non-destructive topology remain available; positive delayed abandon and transactions are not advertised. [Receive primitives](transports/service-bus-receive.md) support application-owned processors.
+- [SQS native sending and queue topology](transports/amazon-sqs.md): named AWS SDK v4 clients, standard/FIFO queues, native timers, byte/count-limited batches, partial-failure responses, send telemetry and non-destructive topology. Receivers, full conformance, SNS and health adapters remain planned.
- [RabbitMQ connection and topology](transports/rabbitmq.md): named native connections, exchanges, queues, queue bindings and DLX arguments, non-destructive provisioning and passive existence checks with explicit validation limits. Send, receive, delayed delivery and health adapters remain planned.
- [RabbitMQ Streams connection and topology](transports/rabbitmq-streams.md): owned native stream systems, existence validation and create-only native stream specifications. Message execution remains blocked on native recovery of failed processing offsets.
- [NATS JetStream native connection and topology](transports/nats.md): named native options, owned connections and non-destructive stream/consumer provisioning. Message execution and full read-only configuration equivalence checks remain planned; the native byte-backed header API is an upstream prerequisite for allocation-free sends.
diff --git a/website/docs/transports/amazon-sqs.md b/website/docs/transports/amazon-sqs.md
new file mode 100644
index 000000000..05a6cad25
--- /dev/null
+++ b/website/docs/transports/amazon-sqs.md
@@ -0,0 +1,97 @@
+---
+title: Amazon SQS
+description: "Named native SQS sending, FIFO groups, timers, batch failures and queue topology."
+---
+
+`Relayer.AmazonSqs` implements native SQS queue sending with AWS SDK v4. Receiver composition and full LocalStack transport conformance remain planned in [#224](https://github.com/thomhurst/Relayer/issues/224), SNS topics/subscriptions in [#225](https://github.com/thomhurst/Relayer/issues/225), and connectivity/liveness health adapters in [#226](https://github.com/thomhurst/Relayer/issues/226). Consumer declarations fail at startup until receivers are implemented.
+
+## Register sending
+
+```csharp
+using Amazon;
+using Amazon.SQS;
+using Amazon.SQS.Model;
+using Relayer;
+using Relayer.AmazonSqs;
+
+services.AddRelayer(relayer =>
+{
+ relayer.AddMessageTypesFromThisAssembly();
+ relayer.UseJsonSerializer(AppJsonContext.Default);
+ relayer.AmazonSqs("orders", sqs =>
+ {
+ sqs.Options.Configure(options =>
+ {
+ options.Sqs = new AmazonSQSConfig { RegionEndpoint = RegionEndpoint.EUWest2 };
+ options.Queues.Add(new CreateQueueRequest("orders"));
+ });
+ sqs.Send("orders");
+ });
+});
+
+await sender.SendAsync(new OrderPlaced(customerId));
+```
+
+Messages need a stable `[Message]` identity and a source-generated JSON context. Start the host before sending. Every route destination must match a declared **queue name**, not a URL. Relayer resolves native queue URLs at startup. Named options support the [Options pattern](../guides/configuration.md).
+
+The native `AmazonSQSConfig` passes unchanged to an owned client, which uses the AWS credential chain. Alternatively, set `SqsClient` to an existing `IAmazonSQS`; its configuration and credentials stay caller-owned, and Relayer never disposes it. Do not mutate captured configuration after startup. `Sns` remains reserved for the planned SNS adapter.
+
+## Queue topology
+
+Declare queues with native `CreateQueueRequest` objects in `Queues`, including native attributes and tags. The default `Validate` mode calls only read APIs: `GetQueueUrl`, `GetQueueAttributes`, and, when tags are declared, `ListQueueTags`. It sends no probe message and requires no create, update or delete permission. Missing queues and mismatched declared settings fail startup with a topology report.
+
+`Provision` creates missing queues with the original request and reports drift on existing queues. It never modifies or deletes existing queues. Declare native `RedrivePolicy` and related queue settings in `Attributes`; receiver-driven dead-letter handling remains planned. Policy JSON is compared structurally rather than by whitespace or property order. Additional undeclared attributes/tags are allowed. `None` skips topology validation and provisioning, but startup still resolves queue names through `GetQueueUrl` because native sending needs URLs. Message-size limits are read during topology validation; without validation the SDK enforces the queue's configured limit.
+
+## FIFO ordering and timers
+
+Declare FIFO queues with both the `.fifo` suffix and the native `FifoQueue = "true"` attribute:
+
+```csharp
+options.Queues.Add(new CreateQueueRequest("orders.fifo")
+{
+ Attributes = new() { ["FifoQueue"] = "true" },
+});
+// Inside the transport declaration:
+sqs.Send("orders.fifo", route => route.OrderingKey(order => order.CustomerId));
+```
+
+The resolved ordering key becomes native `MessageGroupId`. CloudEvents `ce_id` becomes `MessageDeduplicationId`, preserving native FIFO deduplication across retries. Low-level sends without an event ID need native deduplication configuration or an explicit native deduplication ID. FIFO sends require a message group; standard queues reject portable ordering requirements. Relayer adds no ordering layer.
+
+For standard queues, a future `SendOptions.DeliverAt` becomes native `DelaySeconds`, rounded up to the next second so delivery is not early. Timers support at most 15 minutes. FIFO queues do not support per-message timers. Longer delays and FIFO scheduling require a configured [durable outbox](../guides/sending.md); unsupported low-level scheduled sends fail explicitly. Unscheduled sends leave `DelaySeconds` unset, preserving the queue's native default delay.
+
+## Wire format and native callbacks
+
+CloudEvents attributes use string message attributes with the `ce_` prefix. `content-type`, `traceparent` and `tracestate` remain native message attributes. SQS allows at most **10 attributes total**, including CloudEvents, tracing and application headers; exceeding the limit fails without discarding metadata. Serialized bodies must be valid UTF-8 text allowed by SQS. Invalid UTF-8 fails rather than replacing bytes. Binary serializers must supply an SQS-compatible text encoding themselves; Relayer does not silently base64-encode bodies.
+
+```csharp
+await sender.SendAsync(order, options => options.AmazonSqs(request =>
+{
+ request.MessageAttributes["priority"] = new MessageAttributeValue
+ {
+ DataType = "String",
+ StringValue = "high",
+ };
+}));
+```
+
+Callbacks receive native `SendMessageRequest` for both single and batch sends. They run once per message before native admission. Original envelope headers, resolved destination, portable group key and scheduled time take precedence over conflicting callback values. Do not retain borrowed request objects. Native callbacks cannot be persisted in the outbox.
+
+## Batching and telemetry
+
+Serialized transport batches use native `SendMessageBatch`, splitting at destination changes, 10 entries, or the aggregate 1 MiB byte limit, including attributes. Input order is preserved; native FIFO groups govern broker ordering. An individual message exceeding the resolved queue limit fails before native sending. Batches are not atomic: earlier batches or entries can succeed before a failure or cancellation.
+
+Even HTTP 200 responses can contain failed entries. `AmazonSqsBatchException.Response` exposes the unmodified native successful/failed lists; `BatchOffset` identifies the native batch's start within its contiguous destination group. Entry IDs are zero-based indexes within that native batch. Successful entries are not automatically resent. Application retries must account for native partial delivery and FIFO deduplication semantics.
+
+Send spans use `messaging.system = aws_sqs`, `aws.sqs.queue.url`, and the native response's `aws.request_id`. Native AWS exceptions retain their request IDs. Creation context stays in message attributes. SNS telemetry and SQS `delete` settlement spans arrive with their respective adapters.
+
+## Performance validation
+
+`SqsSendBenchmarks` compares acknowledged single sends and 10-message batches with the raw AWS SDK using `MemoryDiagnoser`. Both paths reuse native requests and include text/header conversion. The benchmark creates and deletes a fresh standard queue per case. Use a test AWS account/region with create/delete rights, or set `RELAYER_SQS_SERVICE_URL` to LocalStack (test credentials, `us-east-1`):
+
+```shell
+dotnet run -c Release --project benchmarks/Relayer.Benchmarks -- --filter "*SqsSendBenchmarks*"
+```
+
+Native request, entry and attribute containers are pooled per concurrent operation. SQS requires a text body, so decoding serialized UTF-8 bytes allocates a native-body string on each send. Nonempty UTF-8 header values and group keys also allocate strings. These conversions belong to Relayer and are not excluded as serializer or SDK allocations. This adapter does not currently meet the zero-allocation target. Matching the raw client's conversion allocations does not waive that target, and this serialized-send benchmark does not establish the full default-JSON pipeline's 5% throughput budget.
+
+`SqsBindingBenchmarks` isolates these conversions without network, SDK response, or serializer allocations. It writes the default binary-mode envelope with changing IDs/timestamps and a 256-byte body on each invocation. Run it with `--filter "*SqsBindingBenchmarks*"` to measure Relayer's allocation gap independently of native request overhead.
diff --git a/website/docs/transports/index.md b/website/docs/transports/index.md
index 9e4435e6a..b9994b473 100644
--- a/website/docs/transports/index.md
+++ b/website/docs/transports/index.md
@@ -10,7 +10,7 @@ A transport is an adapter over one native client. Each transport package depends
| `Relayer` | [In-memory](in-memory.md), for tests and samples | Built in | Implemented |
| `Relayer.Kafka` | [Apache Kafka](kafka.md) | [Dekaf](https://dekaf.tomlonghurst.dev/), a pure C# Kafka client | Producers and serial consumers implemented; parallel partition scheduling planned |
| `Relayer.AzureServiceBus` | Azure Service Bus | `Azure.Messaging.ServiceBus` | [Native sending and topology](service-bus.md), [receive primitives](service-bus-receive.md) implemented; receiver composition in development |
-| `Relayer.AmazonSqs` | Amazon SQS and SNS | `AWSSDK.SQS` and `AWSSDK.SimpleNotificationService` | In development |
+| `Relayer.AmazonSqs` | Amazon SQS and SNS | `AWSSDK.SQS` and `AWSSDK.SimpleNotificationService` | [SQS native sending and queue topology](amazon-sqs.md) implemented; receivers, SNS and health adapters planned |
| `Relayer.RabbitMQ` | RabbitMQ | `RabbitMQ.Client` | [Native connection and topology](rabbitmq.md) implemented; send, receive and health adapters planned |
| `Relayer.RabbitMQ.Streams` | RabbitMQ Streams | `RabbitMQ.Stream.Client` | [Native connection and stream topology](rabbitmq-streams.md) implemented; message execution blocked on native failed-offset recovery |
| `Relayer.Nats` | NATS JetStream | `NATS.Client.JetStream` | [Native connection and topology](nats.md) implemented; message execution blocked on native byte-backed headers |
diff --git a/website/sidebars.js b/website/sidebars.js
index 3b8e6c92b..1883ff493 100644
--- a/website/sidebars.js
+++ b/website/sidebars.js
@@ -37,6 +37,7 @@ const sidebars = {
'transports/kafka',
'transports/service-bus',
'transports/service-bus-receive',
+ 'transports/amazon-sqs',
'transports/rabbitmq',
'transports/rabbitmq-streams',
'transports/nats',
diff --git a/website/src/pages/index.js b/website/src/pages/index.js
index d929073ea..879e0ffd2 100644
--- a/website/src/pages/index.js
+++ b/website/src/pages/index.js
@@ -298,12 +298,13 @@ const status = [
['Optional Protobuf and MessagePack serializers', 'Implemented; explicit generated contracts and Native AOT coverage', true],
['Avro with generated codecs and startup-prepared schema registry', 'Implemented; Native AOT/trimming unsupported', true],
['Fallback partition watermarks, key scheduling, backpressure and bounded drain', 'Implemented core SPI; native runtime first', true],
+ ['SQS native sending and queue topology', 'Implemented', true],
['RabbitMQ native connection and topology', 'Implemented', true],
['RabbitMQ Streams native connection and topology', 'Implemented; message execution blocked upstream', true],
['NATS JetStream native connection and topology', 'Implemented; message execution blocked upstream', true],
['Apache Pulsar transport', 'Planned; native UTF-8 properties and Native AOT prerequisites', false],
['AsyncAPI topology and JSON contract export', 'Implemented; protocol bindings unsupported', true],
- ['Kafka parallel receive via Dekaf, SQS/SNS and RabbitMQ send/receive adapters', 'In progress', false],
+ ['Kafka parallel receive via Dekaf, SQS receiver composition, SNS and RabbitMQ send/receive adapters', 'In progress', false],
['Health checks with application-provided adapters', 'Implemented', true],
['Scoped tenant header propagation', 'Implemented; tenant stores and dispatch planned', true],
['Durable outbox contracts and keyed health adapter', 'Implemented core seam', true],
From 202a9659f93642562104ca50eb489d270ab797ac Mon Sep 17 00:00:00 2001
From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com>
Date: Fri, 6 Nov 2026 22:49:18 +0000
Subject: [PATCH 2/4] fix: preserve configured SQS FIFO identity headers (#223)
---
.../AmazonSqsBuilderExtensions.cs | 3 +-
src/Relayer.AmazonSqs/SqsSendState.cs | 4 +-
src/Relayer.AmazonSqs/SqsSendTransport.cs | 27 +++++--
.../Configuration/ConfigurationDefinitions.cs | 3 +
tests/Relayer.Tests/SqsSendLocalStackTests.cs | 10 +--
tests/Relayer.Tests/SqsSendTests.cs | 70 +++++++++++++++++++
website/docs/transports/amazon-sqs.md | 6 +-
7 files changed, 108 insertions(+), 15 deletions(-)
diff --git a/src/Relayer.AmazonSqs/AmazonSqsBuilderExtensions.cs b/src/Relayer.AmazonSqs/AmazonSqsBuilderExtensions.cs
index 544324883..38bbd4c57 100644
--- a/src/Relayer.AmazonSqs/AmazonSqsBuilderExtensions.cs
+++ b/src/Relayer.AmazonSqs/AmazonSqsBuilderExtensions.cs
@@ -25,9 +25,10 @@ public static IRelayerBuilder AmazonSqs(this IRelayerBuilder builder, string nam
throw new NotSupportedException($"SQS transport '{name}': receiver composition is not implemented yet.");
var options = provider.GetRequiredService>().Get(name);
SqsSendTransport.ValidateDeclarations(name, options, declaration.Routes.Select(route => route.Destination));
+ var identityHeaders = SqsSendTransport.ResolveIdentityHeaders(declaration.Routes);
var client = options.SqsClient ?? new AmazonSQSClient(options.Sqs);
return new SqsSendTransport(name, client, options.SqsClient is null, options,
- provider.GetRequiredService(), provider.GetService());
+ provider.GetRequiredService(), provider.GetService(), identityHeaders);
});
builder.Services.AddSingleton(provider => new SqsSendHostedService(provider, name));
return builder;
diff --git a/src/Relayer.AmazonSqs/SqsSendState.cs b/src/Relayer.AmazonSqs/SqsSendState.cs
index 2171472e4..b1a1dc367 100644
--- a/src/Relayer.AmazonSqs/SqsSendState.cs
+++ b/src/Relayer.AmazonSqs/SqsSendState.cs
@@ -18,7 +18,7 @@ internal SqsSendState(string id)
for (var i = 0; i < _values.Length; i++) _values[i] = new() { DataType = "String" };
}
- internal int Prepare(OutgoingMessage outgoing, string queueUrl, bool fifo)
+ internal int Prepare(OutgoingMessage outgoing, string queueUrl, bool fifo, string identityHeader = "ce_id")
{
Request.QueueUrl = queueUrl;
// SQS has a native text body. Reject invalid UTF-8 rather than silently replacing serializer bytes.
@@ -41,7 +41,7 @@ internal int Prepare(OutgoingMessage outgoing, string queueUrl, bool fifo)
var value = _values[index++];
value.StringValue = header.Value.ToString();
_attributes[header.Key] = value;
- if (fifo && header.Key == "ce_id") Request.MessageDeduplicationId = value.StringValue;
+ if (fifo && header.Key == identityHeader) Request.MessageDeduplicationId = value.StringValue;
}
if (_attributes.Count > 10)
throw new InvalidOperationException("SQS supports at most 10 message attributes, including CloudEvents and tracing headers.");
diff --git a/src/Relayer.AmazonSqs/SqsSendTransport.cs b/src/Relayer.AmazonSqs/SqsSendTransport.cs
index ddba8dae2..ad1186a55 100644
--- a/src/Relayer.AmazonSqs/SqsSendTransport.cs
+++ b/src/Relayer.AmazonSqs/SqsSendTransport.cs
@@ -38,8 +38,23 @@ internal static void ValidateDeclarations(string name, AmazonSqsTransportOptions
throw new InvalidOperationException($"SQS transport '{name}': destination '{destination}' needs a native CreateQueueRequest declaration.");
}
+ // Resolve bindings before constructing an owned client, so invalid declarations cannot leak it.
+ internal static IReadOnlyDictionary ResolveIdentityHeaders(IReadOnlyList routes)
+ {
+ var headers = new Dictionary(StringComparer.Ordinal);
+ foreach (var route in routes)
+ {
+ if (!route.Destination.EndsWith(".fifo", StringComparison.Ordinal) ||
+ route.SendOptions.EnvelopeMode != MessageEnvelopeMode.CloudEvents) continue;
+ var identityHeader = route.SendOptions.HeaderNames.Id;
+ if (headers.TryGetValue(route.Destination, out var existing) && existing != identityHeader)
+ throw new InvalidOperationException($"SQS FIFO queue '{route.Destination}': CloudEvents routes must use the same HeaderNames identity binding. Configure matching HeaderNames for every route to this queue.");
+ headers[route.Destination] = identityHeader;
+ }
+ return headers;
+ }
internal SqsSendTransport(string name, IAmazonSQS client, bool ownsClient, AmazonSqsTransportOptions options,
- MessageTracing? tracing = null, ILoggerFactory? logging = null)
+ MessageTracing? tracing = null, ILoggerFactory? logging = null, IReadOnlyDictionary? identityHeaders = null)
{
Name = name;
_client = client;
@@ -48,7 +63,7 @@ internal SqsSendTransport(string name, IAmazonSQS client, bool ownsClient, Amazo
var endpoints = new Dictionary(StringComparer.Ordinal);
foreach (var declaration in options.Queues)
{
- var endpoint = new Endpoint(declaration);
+ var endpoint = new Endpoint(declaration, identityHeaders?.GetValueOrDefault(declaration.QueueName) ?? "ce_id");
if (tracing is not null)
endpoint.Tracing = new(tracing, new() { System = "aws_sqs", Destination = declaration.QueueName },
SendCoreAsync, SendBatchCoreAsync, logging?.CreateLogger());
@@ -125,7 +140,7 @@ private async ValueTask SendCoreAsync(OutgoingMessage message, CancellationToken
Enrich(activity, endpoint.Url!, null);
try
{
- var size = state.Messages[0].Prepare(message, endpoint.Url!, endpoint.Fifo);
+ var size = state.Messages[0].Prepare(message, endpoint.Url!, endpoint.Fifo, endpoint.IdentityHeader);
ValidateSize(endpoint, size);
var response = await _client.SendMessageAsync(state.Messages[0].Request, cancellationToken).ConfigureAwait(false);
Enrich(activity, endpoint.Url!, response.ResponseMetadata?.RequestId);
@@ -183,7 +198,7 @@ private async ValueTask SendBatchCoreAsync(ReadOnlyMemory messa
}
var pending = state.Messages[count];
state.Used = count + 1;
- var size = pending.Prepare(messages.Span[i], endpoint.Url!, endpoint.Fifo);
+ var size = pending.Prepare(messages.Span[i], endpoint.Url!, endpoint.Fifo, endpoint.IdentityHeader);
ValidateSize(endpoint, size);
if (count > 0 && bytes + size > 1_048_576)
{
@@ -272,9 +287,10 @@ public ValueTask DisposeAsync()
private sealed class Endpoint
{
- internal Endpoint(CreateQueueRequest declaration)
+ internal Endpoint(CreateQueueRequest declaration, string identityHeader)
{
Declaration = declaration;
+ IdentityHeader = identityHeader;
Fifo = declaration.QueueName.EndsWith(".fifo", StringComparison.Ordinal);
Capabilities = new() { OrderedByKey = Fifo, MaxBatchSize = 10, MaxDeliveryDelay = Fifo ? null : TimeSpan.FromMinutes(15) };
if (declaration.Attributes?.TryGetValue("MaximumMessageSize", out var maximum) == true)
@@ -282,6 +298,7 @@ internal Endpoint(CreateQueueRequest declaration)
}
internal CreateQueueRequest Declaration { get; }
internal bool Fifo { get; }
+ internal string IdentityHeader { get; }
internal string? Url { get; set; }
internal TransportCapabilities Capabilities { get; set; }
internal SendTracing? Tracing { get; set; }
diff --git a/src/Relayer/Configuration/ConfigurationDefinitions.cs b/src/Relayer/Configuration/ConfigurationDefinitions.cs
index 751ad0c51..56bb4f69c 100644
--- a/src/Relayer/Configuration/ConfigurationDefinitions.cs
+++ b/src/Relayer/Configuration/ConfigurationDefinitions.cs
@@ -45,6 +45,9 @@ internal TransportDefinition(string name, Type optionsType, IRouteDefinition[] r
/// A message route. CLR types identify registrations only, never wire messages.
public interface IRouteDefinition
{
+ /// Portable send settings captured when the route declaration is frozen.
+ public SendRouteOptions SendOptions { get; }
+
/// The CLR type used to select this declaration at startup.
public Type MessageType { get; }
/// The native destination name.
diff --git a/tests/Relayer.Tests/SqsSendLocalStackTests.cs b/tests/Relayer.Tests/SqsSendLocalStackTests.cs
index d68b53d7d..700d21a62 100644
--- a/tests/Relayer.Tests/SqsSendLocalStackTests.cs
+++ b/tests/Relayer.Tests/SqsSendLocalStackTests.cs
@@ -34,7 +34,8 @@ public async Task Standard_fifo_batches_delays_and_read_only_topology_round_trip
var urls = new List();
try
{
- await using var transport = new SqsSendTransport("localstack", client, false, options);
+ IRouteDefinition[] routes = [new RouteDefinition(fifo, new(), null, null, new() { HeaderNames = new("event_") })];
+ await using var transport = new SqsSendTransport("localstack", client, false, options, identityHeaders: SqsSendTransport.ResolveIdentityHeaders(routes));
var missing = await transport.ApplyTopologyAsync(TopologyMode.Validate, token);
await Assert.That(missing.Differences.Count).IsEqualTo(2);
await Assert.That((await transport.ApplyTopologyAsync(TopologyMode.Provision, token)).Differences.Count).IsEqualTo(0);
@@ -56,13 +57,14 @@ public async Task Standard_fifo_batches_delays_and_read_only_topology_round_trip
var batch = new OutgoingMessage[12];
for (var i = 0; i < batch.Length; i++)
- batch[i] = new(fifo, System.Text.Encoding.UTF8.GetBytes(i.ToString()),
- new KeyValuePair[] { new("ce_id", new WireString("event-" + i)) }, new WireString("customer"));
+ batch[i] = new(fifo, "identical body"u8.ToArray(),
+ new KeyValuePair[] { new("event_id", new WireString("event-" + i)) }, new WireString("customer"));
await transport.SendBatchAsync(batch, token);
for (var i = 0; i < batch.Length; i++)
{
var ordered = await ReceiveAsync(client, fifoUrl, token);
- await Assert.That(ordered.Body).IsEqualTo(i.ToString());
+ await Assert.That(ordered.Body).IsEqualTo("identical body");
+ await Assert.That(ordered.MessageAttributes["event_id"].StringValue).IsEqualTo("event-" + i);
await Assert.That(ordered.Attributes["MessageGroupId"]).IsEqualTo("customer");
await Assert.That(ordered.Attributes["MessageDeduplicationId"]).IsEqualTo("event-" + i);
await client.DeleteMessageAsync(fifoUrl, ordered.ReceiptHandle, token);
diff --git a/tests/Relayer.Tests/SqsSendTests.cs b/tests/Relayer.Tests/SqsSendTests.cs
index 0221446ee..81bde7896 100644
--- a/tests/Relayer.Tests/SqsSendTests.cs
+++ b/tests/Relayer.Tests/SqsSendTests.cs
@@ -43,6 +43,76 @@ public async Task Hosted_sender_serializes_the_real_generated_envelope()
finally { await host.StopAsync(); }
}
+ [Test]
+ public async Task Custom_fifo_identity_binding_preserves_distinct_events_and_replays()
+ {
+ using var client = new SqsTestClient();
+ var app = Host.CreateApplicationBuilder();
+ app.Services.AddRelayer(builder =>
+ {
+ builder.AddMessageTypesFromThisAssembly();
+ builder.AmazonSqs("test", sqs =>
+ {
+ sqs.Options.Configure(o =>
+ {
+ o.SqsClient = client;
+ o.Queues.Add(new("ordered.fifo") { Attributes = new() { ["FifoQueue"] = "true" } });
+ });
+ sqs.Send("ordered.fifo", route =>
+ {
+ route.SendOptions = new() { HeaderNames = new("event_") };
+ route.OrderingKey(_ => "customer");
+ });
+ });
+ });
+ using var host = app.Build();
+ await host.StartAsync();
+ try
+ {
+ await using var scope = host.Services.CreateAsyncScope();
+ var sender = scope.ServiceProvider.GetRequiredService();
+ await sender.SendNowAsync(new Order());
+ await sender.SendNowAsync(new Order());
+ var first = client.Sent[0];
+ var second = client.Sent[1];
+ await Assert.That(first.Body).IsEqualTo(second.Body);
+ await Assert.That(first.Deduplication).IsEqualTo(first.Attributes["event_id"]);
+ await Assert.That(second.Deduplication).IsEqualTo(second.Attributes["event_id"]);
+ await Assert.That(first.Deduplication).IsNotEqualTo(second.Deduplication);
+ var transport = host.Services.GetServices().Single();
+ var replay = new OutgoingMessage("ordered.fifo", Encoding.UTF8.GetBytes(first.Body),
+ first.Attributes.Select(pair => new KeyValuePair(pair.Key, new(pair.Value))).ToArray(),
+ new WireString("customer"));
+ await transport.SendAsync(replay, default);
+ await transport.SendBatchAsync(new[] { replay, replay }, default);
+ await Assert.That(client.Sent[2].Deduplication).IsEqualTo(first.Deduplication);
+ await Assert.That(client.Batches.Single().All(entry => entry.Message.Deduplication == first.Deduplication)).IsTrue();
+ }
+ finally { await host.StopAsync(); }
+ }
+
+ [Test]
+ public async Task Conflicting_fifo_identity_bindings_fail_before_native_calls()
+ {
+ using var client = new SqsTestClient();
+ var services = new ServiceCollection();
+ services.AddRelayer(builder => builder.AmazonSqs("test", sqs =>
+ {
+ sqs.Options.Configure(o =>
+ {
+ o.SqsClient = client;
+ o.Queues.Add(new("ordered.fifo") { Attributes = new() { ["FifoQueue"] = "true" } });
+ });
+ sqs.Send("ordered.fifo");
+ sqs.Send("ordered.fifo", route => route.SendOptions = new() { HeaderNames = new("event_") });
+ }));
+ await using var provider = services.BuildServiceProvider();
+ await Assert.That(() => provider.GetServices().ToArray()).Throws()
+ .WithMessage("SQS FIFO queue 'ordered.fifo': CloudEvents routes must use the same HeaderNames identity binding. Configure matching HeaderNames for every route to this queue.");
+ await Assert.That(client.Lookups).IsEqualTo(0);
+ await Assert.That(client.Sent.Count).IsEqualTo(0);
+ }
+
[Test]
public async Task Named_registration_preserves_options_and_caller_owned_clients()
{
diff --git a/website/docs/transports/amazon-sqs.md b/website/docs/transports/amazon-sqs.md
index 05a6cad25..e4fe11864 100644
--- a/website/docs/transports/amazon-sqs.md
+++ b/website/docs/transports/amazon-sqs.md
@@ -3,7 +3,7 @@ title: Amazon SQS
description: "Named native SQS sending, FIFO groups, timers, batch failures and queue topology."
---
-`Relayer.AmazonSqs` implements native SQS queue sending with AWS SDK v4. Receiver composition and full LocalStack transport conformance remain planned in [#224](https://github.com/thomhurst/Relayer/issues/224), SNS topics/subscriptions in [#225](https://github.com/thomhurst/Relayer/issues/225), and connectivity/liveness health adapters in [#226](https://github.com/thomhurst/Relayer/issues/226). Consumer declarations fail at startup until receivers are implemented.
+`Relayer.AmazonSqs` implements native SQS queue sending with AWS SDK v4. Receiver composition and full LocalStack transport conformance remain planned in [#224](https://github.com/thomhurst/Relayer/issues/224), SNS topics/subscriptions in [#225](https://github.com/thomhurst/Relayer/issues/225), and connectivity/liveness health adapters with receivers in [#224](https://github.com/thomhurst/Relayer/issues/224). Consumer declarations fail at startup until receivers are implemented.
## Register sending
@@ -55,13 +55,13 @@ options.Queues.Add(new CreateQueueRequest("orders.fifo")
sqs.Send("orders.fifo", route => route.OrderingKey(order => order.CustomerId));
```
-The resolved ordering key becomes native `MessageGroupId`. CloudEvents `ce_id` becomes `MessageDeduplicationId`, preserving native FIFO deduplication across retries. Low-level sends without an event ID need native deduplication configuration or an explicit native deduplication ID. FIFO sends require a message group; standard queues reject portable ordering requirements. Relayer adds no ordering layer.
+The resolved ordering key becomes native `MessageGroupId`. The CloudEvents identity header selected by `SendRouteOptions.HeaderNames` (default `ce_id`) becomes `MessageDeduplicationId`, preserving native FIFO deduplication across retries and stored-message replay. Custom prefixes such as `new HeaderNames("event_")` are supported. All CloudEvents routes to the same FIFO queue must use the same identity header; conflicting bindings fail startup with an actionable error. Low-level replay uses that queue's configured identity header, or `ce_id` when no CloudEvents route declares one. Low-level sends without an event ID need native deduplication configuration or an explicit native deduplication ID. FIFO sends require a message group; standard queues reject portable ordering requirements. Relayer adds no ordering layer.
For standard queues, a future `SendOptions.DeliverAt` becomes native `DelaySeconds`, rounded up to the next second so delivery is not early. Timers support at most 15 minutes. FIFO queues do not support per-message timers. Longer delays and FIFO scheduling require a configured [durable outbox](../guides/sending.md); unsupported low-level scheduled sends fail explicitly. Unscheduled sends leave `DelaySeconds` unset, preserving the queue's native default delay.
## Wire format and native callbacks
-CloudEvents attributes use string message attributes with the `ce_` prefix. `content-type`, `traceparent` and `tracestate` remain native message attributes. SQS allows at most **10 attributes total**, including CloudEvents, tracing and application headers; exceeding the limit fails without discarding metadata. Serialized bodies must be valid UTF-8 text allowed by SQS. Invalid UTF-8 fails rather than replacing bytes. Binary serializers must supply an SQS-compatible text encoding themselves; Relayer does not silently base64-encode bodies.
+CloudEvents attributes use string message attributes with the configured prefix (`ce_` by default). `content-type`, `traceparent` and `tracestate` remain native message attributes. SQS allows at most **10 attributes total**, including CloudEvents, tracing and application headers; exceeding the limit fails without discarding metadata. Serialized bodies must be valid UTF-8 text allowed by SQS. Invalid UTF-8 fails rather than replacing bytes. Binary serializers must supply an SQS-compatible text encoding themselves; Relayer does not silently base64-encode bodies.
```csharp
await sender.SendAsync(order, options => options.AmazonSqs(request =>
From a59bd050e8bd62c5f6ad0c1a5ea49d051901aa17 Mon Sep 17 00:00:00 2001
From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com>
Date: Mon, 9 Nov 2026 23:59:30 +0000
Subject: [PATCH 3/4] Fix native SQS send metrics and document D52 approval
(#223)
---
.../Relayer.Benchmarks/SqsSendBenchmarks.cs | 23 ++++++-
src/Relayer.AmazonSqs/SqsSendTransport.cs | 25 +++++--
tests/Relayer.Tests/SqsSendTests.cs | 68 ++++++++++++++++++-
website/docs/transports/amazon-sqs.md | 8 ++-
4 files changed, 110 insertions(+), 14 deletions(-)
diff --git a/benchmarks/Relayer.Benchmarks/SqsSendBenchmarks.cs b/benchmarks/Relayer.Benchmarks/SqsSendBenchmarks.cs
index dc2c747d5..5a8bb0c46 100644
--- a/benchmarks/Relayer.Benchmarks/SqsSendBenchmarks.cs
+++ b/benchmarks/Relayer.Benchmarks/SqsSendBenchmarks.cs
@@ -1,4 +1,6 @@
using System.Text;
+using System.Diagnostics.Metrics;
+using Microsoft.Extensions.Options;
using Amazon;
using Amazon.Runtime;
using Amazon.SQS;
@@ -15,6 +17,11 @@ namespace Relayer.Benchmarks;
[GroupBenchmarksBy(BenchmarkLogicalGroupRule.ByCategory)]
public class SqsSendBenchmarks
{
+ [Params(false, true)]
+ public bool Metrics { get; set; }
+ private RelayerInstrumentation _instrumentation = null!;
+ private MessageTracing _tracing = null!;
+ private MeterListener _listener = null!;
private AmazonSQSClient _client = null!;
private SqsSendTransport _transport = null!;
private string _queue = null!;
@@ -38,7 +45,19 @@ public async Task Setup()
await Task.Delay(TimeSpan.FromSeconds(1));
var options = new AmazonSqsTransportOptions { SqsClient = _client };
options.Queues.Add(new(_queue));
- _transport = new("benchmark", _client, false, options);
+ _instrumentation = new();
+ _listener = new()
+ {
+ InstrumentPublished = (instrument, observer) =>
+ {
+ if (Metrics && ReferenceEquals(instrument.Meter.Scope, _instrumentation)) observer.EnableMeasurementEvents(instrument);
+ },
+ };
+ _listener.SetMeasurementEventCallback(static (_, _, _, _) => { });
+ _listener.SetMeasurementEventCallback(static (_, _, _, _) => { });
+ _listener.Start();
+ _tracing = new(Options.Create(new TracingOptions()), [], instrumentation: _instrumentation);
+ _transport = new("benchmark", _client, false, options, _tracing);
await _transport.StartAsync(default);
_body = Encoding.UTF8.GetBytes(new string('x', 256));
_headers = [new("ce_id", new("019a3c1b-97c0-7000-8000-000000000001")), new("ce_type", new("benchmark.order;v=1")),
@@ -96,6 +115,6 @@ public async Task Cleanup()
{
if (_transport is not null) await _transport.DisposeAsync();
try { if (_client is not null && _url is not null) await _client.DeleteQueueAsync(_url); }
- finally { _client?.Dispose(); }
+ finally { _client?.Dispose(); _tracing?.Dispose(); _listener?.Dispose(); _instrumentation?.Dispose(); }
}
}
diff --git a/src/Relayer.AmazonSqs/SqsSendTransport.cs b/src/Relayer.AmazonSqs/SqsSendTransport.cs
index ad1186a55..436add86a 100644
--- a/src/Relayer.AmazonSqs/SqsSendTransport.cs
+++ b/src/Relayer.AmazonSqs/SqsSendTransport.cs
@@ -142,8 +142,16 @@ private async ValueTask SendCoreAsync(OutgoingMessage message, CancellationToken
{
var size = state.Messages[0].Prepare(message, endpoint.Url!, endpoint.Fifo, endpoint.IdentityHeader);
ValidateSize(endpoint, size);
- var response = await _client.SendMessageAsync(state.Messages[0].Request, cancellationToken).ConfigureAwait(false);
- Enrich(activity, endpoint.Url!, response.ResponseMetadata?.RequestId);
+ endpoint.Tracing?.RecordNativeSend();
+ var duration = endpoint.Tracing?.StartNativeSend() ?? default;
+ var failed = true;
+ try
+ {
+ var response = await _client.SendMessageAsync(state.Messages[0].Request, cancellationToken).ConfigureAwait(false);
+ failed = false;
+ Enrich(activity, endpoint.Url!, response.ResponseMetadata?.RequestId);
+ }
+ finally { duration.Complete(failed); }
}
catch (AmazonSQSException error)
{
@@ -189,7 +197,7 @@ private async ValueTask SendBatchCoreAsync(ReadOnlyMemory messa
Validate(messages.Span[i], cancellationToken);
if (count == 10)
{
- await FlushAsync(state, batchStart, cancellationToken).ConfigureAwait(false);
+ await FlushAsync(state, endpoint, batchStart, cancellationToken).ConfigureAwait(false);
for (var j = 0; j < count; j++) state.Messages[j].Clear();
state.Batch.Entries.Clear();
state.Used = 0;
@@ -202,7 +210,7 @@ private async ValueTask SendBatchCoreAsync(ReadOnlyMemory messa
ValidateSize(endpoint, size);
if (count > 0 && bytes + size > 1_048_576)
{
- await FlushAsync(state, batchStart, cancellationToken).ConfigureAwait(false);
+ await FlushAsync(state, endpoint, batchStart, cancellationToken).ConfigureAwait(false);
for (var j = 0; j < count; j++) state.Messages[j].Clear();
state.Batch.Entries.Clear();
// Carry the already prepared request across a byte boundary without repeating its callback.
@@ -217,27 +225,32 @@ private async ValueTask SendBatchCoreAsync(ReadOnlyMemory messa
count++;
bytes += size;
}
- if (count > 0) await FlushAsync(state, batchStart, cancellationToken).ConfigureAwait(false);
+ if (count > 0) await FlushAsync(state, endpoint, batchStart, cancellationToken).ConfigureAwait(false);
}
finally { _operations.Return(state); }
}
[AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder))]
- private async ValueTask FlushAsync(SqsOperationState state, int offset, CancellationToken cancellationToken)
+ private async ValueTask FlushAsync(SqsOperationState state, Endpoint endpoint, int offset, CancellationToken cancellationToken)
{
var activity = CurrentActivity();
Enrich(activity, state.Batch.QueueUrl, null);
+ endpoint.Tracing?.RecordNativeSend(state.Batch.Entries.Count);
+ var duration = endpoint.Tracing?.StartNativeSend() ?? default;
+ var failed = true;
try
{
var response = await _client.SendMessageBatchAsync(state.Batch, cancellationToken).ConfigureAwait(false);
Enrich(activity, state.Batch.QueueUrl, response.ResponseMetadata?.RequestId);
if (response.Failed is { Count: > 0 }) throw new AmazonSqsBatchException(response, offset);
+ failed = false;
}
catch (AmazonSQSException error)
{
Enrich(activity, state.Batch.QueueUrl, error.RequestId);
throw;
}
+ finally { duration.Complete(failed); }
}
private Activity? CurrentActivity() => Activity.Current is { } activity && ReferenceEquals(activity.Source, _tracing?.Source) ? activity : null;
diff --git a/tests/Relayer.Tests/SqsSendTests.cs b/tests/Relayer.Tests/SqsSendTests.cs
index 81bde7896..1d0cd08c1 100644
--- a/tests/Relayer.Tests/SqsSendTests.cs
+++ b/tests/Relayer.Tests/SqsSendTests.cs
@@ -382,6 +382,67 @@ public async Task Send_telemetry_uses_sqs_system_queue_url_and_native_request_id
await Assert.That(failed.Status).IsEqualTo(ActivityStatusCode.Error);
}
+ [Test]
+ [Arguments(false, false)]
+ [Arguments(false, true)]
+ [Arguments(true, false)]
+ [Arguments(true, true)]
+ public async Task Native_metrics_wait_for_completion_and_include_failures(bool batch, bool fail)
+ {
+ using var instrumentation = new RelayerInstrumentation();
+ using var durations = new SendDurationCapture(instrumentation);
+ long sent = 0;
+ using var meter = new System.Diagnostics.Metrics.MeterListener
+ {
+ InstrumentPublished = (instrument, observer) =>
+ {
+ if (ReferenceEquals(instrument.Meter.Scope, instrumentation) && instrument.Name == "messaging.client.sent.messages")
+ observer.EnableMeasurementEvents(instrument);
+ },
+ };
+ meter.SetMeasurementEventCallback((_, value, _, _) => sent += value);
+ meter.Start();
+ using var tracing = new MessageTracing(Microsoft.Extensions.Options.Options.Create(new TracingOptions()), [], instrumentation: instrumentation);
+ using var client = new SqsTestClient { Gate = new(TaskCreationOptions.RunContinuationsAsynchronously) };
+ await using var transport = new SqsSendTransport("test", client, false, Options(client), tracing);
+ await transport.StartAsync(default);
+ var message = new OutgoingMessage("orders", "{}"u8.ToArray());
+ var pending = batch ? transport.SendBatchAsync(new[] { message, message }, default) : transport.SendAsync(message, default);
+ await Assert.That(pending.IsCompleted).IsFalse();
+ await Assert.That(sent).IsEqualTo(batch ? 2L : 1L);
+ await Assert.That(durations.Values.Count).IsEqualTo(0);
+ if (fail) client.Gate.SetException(new AmazonSQSException("failure"));
+ else client.Gate.SetResult();
+ if (fail) await Assert.That(async () => await pending).Throws();
+ else await pending;
+ var duration = durations.Values.Single();
+ await Assert.That(duration.Tags["messaging.system"]).IsEqualTo("aws_sqs");
+ await Assert.That(duration.Tags["messaging.destination.name"]).IsEqualTo("orders");
+ await Assert.That(duration.Tags.ContainsKey("error.type")).IsEqualTo(fail);
+ }
+
+ [Test]
+ public async Task Split_batches_count_native_attempts_and_partial_failure_stops_later_batches()
+ {
+ using var instrumentation = new RelayerInstrumentation();
+ using var durations = new SendDurationCapture(instrumentation);
+ using var tracing = new MessageTracing(Microsoft.Extensions.Options.Options.Create(new TracingOptions()), [], instrumentation: instrumentation);
+ using var client = new SqsTestClient();
+ await using var transport = new SqsSendTransport("test", client, false, Options(client), tracing);
+ await transport.StartAsync(default);
+ var messages = Enumerable.Repeat(new OutgoingMessage("orders", "{}"u8.ToArray()), 11).ToArray();
+ await transport.SendBatchAsync(messages, default);
+ await Assert.That(durations.Values.Count).IsEqualTo(2);
+ durations.Values.Clear();
+ client.FailBatch = true;
+ await Assert.That(async () => await transport.SendBatchAsync(messages, default)).Throws();
+ await Assert.That(durations.Values.Single().Tags["error.type"]).IsEqualTo("_OTHER");
+ durations.Values.Clear();
+ await transport.SendBatchAsync(Array.Empty(), default);
+ await Assert.That(async () => await transport.SendAsync(new("orders", new byte[] { 0xff }), default)).Throws();
+ await Assert.That(durations.Values.Count).IsEqualTo(0);
+ }
+
internal static AmazonSqsTransportOptions Options(IAmazonSQS client)
{
var options = new AmazonSqsTransportOptions { SqsClient = client };
@@ -424,19 +485,20 @@ public override async Task SendMessageAsync(SendMessageRequ
return new() { ResponseMetadata = new() { RequestId = "request-1" } };
}
- public override Task SendMessageBatchAsync(SendMessageBatchRequest request, CancellationToken cancellationToken = default)
+ public override async Task SendMessageBatchAsync(SendMessageBatchRequest request, CancellationToken cancellationToken = default)
{
Batches.Add(request.Entries.Select(entry => (entry.Id, Snapshot(new()
{
QueueUrl = request.QueueUrl, MessageBody = entry.MessageBody, MessageGroupId = entry.MessageGroupId,
MessageDeduplicationId = entry.MessageDeduplicationId, DelaySeconds = entry.DelaySeconds, MessageAttributes = entry.MessageAttributes,
}))).ToArray());
- return Task.FromResult(new SendMessageBatchResponse
+ if (Gate is not null) await Gate.Task.WaitAsync(cancellationToken);
+ return new SendMessageBatchResponse
{
Successful = [new() { Id = "0" }],
Failed = FailBatch ? [new() { Id = "1", Code = "InvalidMessageContents", SenderFault = true }] : [],
ResponseMetadata = new() { RequestId = "batch-request" },
- });
+ };
}
public override Task GetQueueUrlAsync(string queueName, CancellationToken cancellationToken = default)
diff --git a/website/docs/transports/amazon-sqs.md b/website/docs/transports/amazon-sqs.md
index e4fe11864..082762817 100644
--- a/website/docs/transports/amazon-sqs.md
+++ b/website/docs/transports/amazon-sqs.md
@@ -80,7 +80,9 @@ Callbacks receive native `SendMessageRequest` for both single and batch sends. T
Serialized transport batches use native `SendMessageBatch`, splitting at destination changes, 10 entries, or the aggregate 1 MiB byte limit, including attributes. Input order is preserved; native FIFO groups govern broker ordering. An individual message exceeding the resolved queue limit fails before native sending. Batches are not atomic: earlier batches or entries can succeed before a failure or cancellation.
-Even HTTP 200 responses can contain failed entries. `AmazonSqsBatchException.Response` exposes the unmodified native successful/failed lists; `BatchOffset` identifies the native batch's start within its contiguous destination group. Entry IDs are zero-based indexes within that native batch. Successful entries are not automatically resent. Application retries must account for native partial delivery and FIFO deduplication semantics.
+Even HTTP 200 responses can contain failed entries. `AmazonSqsBatchException.Response` exposes the unmodified native successful/failed lists; `BatchOffset` identifies the native batch's start within its contiguous destination group. Entry IDs are zero-based indexes within that native batch. Successful entries are not automatically resent, and a partial failure stops submission of later sub-batches. Application retries must account for native partial delivery and FIFO deduplication semantics.
+
+Native send attempts count actual entries in `messaging.client.sent.messages`; each SDK call records `messaging.client.operation.duration` through acknowledgement or failure, including partial batch failure. Preparation failures and empty batches record neither metric.
Send spans use `messaging.system = aws_sqs`, `aws.sqs.queue.url`, and the native response's `aws.request_id`. Native AWS exceptions retain their request IDs. Creation context stays in message attributes. SNS telemetry and SQS `delete` settlement spans arrive with their respective adapters.
@@ -92,6 +94,6 @@ Send spans use `messaging.system = aws_sqs`, `aws.sqs.queue.url`, and the native
dotnet run -c Release --project benchmarks/Relayer.Benchmarks -- --filter "*SqsSendBenchmarks*"
```
-Native request, entry and attribute containers are pooled per concurrent operation. SQS requires a text body, so decoding serialized UTF-8 bytes allocates a native-body string on each send. Nonempty UTF-8 header values and group keys also allocate strings. These conversions belong to Relayer and are not excluded as serializer or SDK allocations. This adapter does not currently meet the zero-allocation target. Matching the raw client's conversion allocations does not waive that target, and this serialized-send benchmark does not establish the full default-JSON pipeline's 5% throughput budget.
+Native request, entry and attribute containers are pooled per concurrent operation. SQS requires a text body, so decoding serialized UTF-8 bytes allocates a native-body string on each send. Nonempty UTF-8 header values and group keys also allocate strings. Under the approved native-boundary allocation policy (D52), these required `SendMessageRequest.MessageBody`, `MessageAttributeValue.StringValue`, and `MessageGroupId` strings count as native-client cost when the equivalent raw-client preparation allocates at least as much. All other pipeline allocations remain subject to the zero-allocation requirement. The 5% throughput budget is unchanged; the serialized-send benchmark does not establish the full default-JSON pipeline budget.
-`SqsBindingBenchmarks` isolates these conversions without network, SDK response, or serializer allocations. It writes the default binary-mode envelope with changing IDs/timestamps and a 256-byte body on each invocation. Run it with `--filter "*SqsBindingBenchmarks*"` to measure Relayer's allocation gap independently of native request overhead.
+`SqsBindingBenchmarks` isolates these conversions without network, SDK response, or serializer allocations. It writes the default binary-mode envelope with changing IDs/timestamps and a 256-byte body on each invocation. Run it with `--filter "*SqsBindingBenchmarks*"` to pin Relayer's additional allocation cost against equivalent raw-client preparation, independently of native request overhead. The earlier default-envelope probe reported 856 B/message on each path (0 additional B); that historical report is not a measurement of every payload or configuration.
From 86ff83de2ea47d29bf208eab6a21fc5694b0eda7 Mon Sep 17 00:00:00 2001
From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com>
Date: Tue, 10 Nov 2026 00:24:25 +0000
Subject: [PATCH 4/4] fix: reuse native SQS group ID decoding (#223)
---
.../SqsBindingBenchmarks.cs | 19 +++++++++++++----
src/Relayer.AmazonSqs/SqsSendState.cs | 5 +++--
tests/Relayer.Tests/SqsSendTests.cs | 21 +++++++++++++++++++
website/docs/transports/amazon-sqs.md | 4 ++--
4 files changed, 41 insertions(+), 8 deletions(-)
diff --git a/benchmarks/Relayer.Benchmarks/SqsBindingBenchmarks.cs b/benchmarks/Relayer.Benchmarks/SqsBindingBenchmarks.cs
index afa62b5f4..225bb3456 100644
--- a/benchmarks/Relayer.Benchmarks/SqsBindingBenchmarks.cs
+++ b/benchmarks/Relayer.Benchmarks/SqsBindingBenchmarks.cs
@@ -16,13 +16,17 @@ public class SqsBindingBenchmarks
private readonly byte[] _body = Encoding.UTF8.GetBytes(new string('x', 256));
private readonly DateTimeOffset _time = DateTimeOffset.UtcNow;
private long _sequence;
+ private readonly byte[] _group = "customer-123"u8.ToArray();
+
+ [Params(false, true)]
+ public bool Fifo { get; set; }
[GlobalSetup]
public void Setup()
{
var message = Next();
foreach (var header in message.Headers.Span) _raw.MessageAttributes.Add(header.Key, new() { DataType = "String" });
- _relayer.Prepare(message, "https://sqs.us-east-1.amazonaws.com/123456789012/orders", false);
+ _relayer.Prepare(message, "https://sqs.us-east-1.amazonaws.com/123456789012/orders", Fifo);
_relayer.Clear();
RawBinding();
}
@@ -32,14 +36,21 @@ public int RawBinding()
{
var message = Next();
_raw.MessageBody = Encoding.UTF8.GetString(message.Body.Span);
- foreach (var header in message.Headers.Span) _raw.MessageAttributes[header.Key].StringValue = header.Value.ToString();
+ _raw.MessageGroupId = message.OrderingKey?.ToString();
+ _raw.MessageDeduplicationId = null;
+ foreach (var header in message.Headers.Span)
+ {
+ var value = header.Value.ToString();
+ _raw.MessageAttributes[header.Key].StringValue = value;
+ if (Fifo && header.Key == "ce_id") _raw.MessageDeduplicationId = value;
+ }
return _raw.MessageBody.Length + _raw.MessageAttributes.Count;
}
[Benchmark]
public int RelayerBinding()
{
- var size = _relayer.Prepare(Next(), "https://sqs.us-east-1.amazonaws.com/123456789012/orders", false);
+ var size = _relayer.Prepare(Next(), "https://sqs.us-east-1.amazonaws.com/123456789012/orders", Fifo);
_relayer.Clear();
return size;
}
@@ -47,7 +58,7 @@ public int RelayerBinding()
private OutgoingMessage Next()
{
_envelope.Write(_headers, new(Guid.CreateVersion7(), _time.AddTicks(++_sequence), default));
- return new("orders", _body, _headers.Entries);
+ return new("orders", _body, _headers.Entries, Fifo ? new WireString(_group) : null);
}
private sealed class HeaderBuffer : IMessageHeaderWriter
diff --git a/src/Relayer.AmazonSqs/SqsSendState.cs b/src/Relayer.AmazonSqs/SqsSendState.cs
index b1a1dc367..792735e62 100644
--- a/src/Relayer.AmazonSqs/SqsSendState.cs
+++ b/src/Relayer.AmazonSqs/SqsSendState.cs
@@ -23,7 +23,8 @@ internal int Prepare(OutgoingMessage outgoing, string queueUrl, bool fifo, strin
Request.QueueUrl = queueUrl;
// SQS has a native text body. Reject invalid UTF-8 rather than silently replacing serializer bytes.
Request.MessageBody = Utf8.GetString(outgoing.Body.Span);
- if (outgoing.OrderingKey is { } orderingKey) Request.MessageGroupId = orderingKey.ToString();
+ var groupId = outgoing.OrderingKey?.ToString();
+ if (groupId is not null) Request.MessageGroupId = groupId;
Request.MessageAttributes = _attributes;
outgoing.ApplyNative(Request);
// Keep caller-supplied attribute dictionaries caller-owned, while retaining reusable transport storage.
@@ -46,7 +47,7 @@ internal int Prepare(OutgoingMessage outgoing, string queueUrl, bool fifo, strin
if (_attributes.Count > 10)
throw new InvalidOperationException("SQS supports at most 10 message attributes, including CloudEvents and tracing headers.");
Request.QueueUrl = queueUrl;
- if (outgoing.OrderingKey is { } key) Request.MessageGroupId = key.ToString();
+ if (groupId is not null) Request.MessageGroupId = groupId;
if (outgoing.DeliverAt is { } deliverAt)
{
var delay = deliverAt - DateTimeOffset.UtcNow;
diff --git a/tests/Relayer.Tests/SqsSendTests.cs b/tests/Relayer.Tests/SqsSendTests.cs
index 1d0cd08c1..cc1e6e0fd 100644
--- a/tests/Relayer.Tests/SqsSendTests.cs
+++ b/tests/Relayer.Tests/SqsSendTests.cs
@@ -178,6 +178,27 @@ public async Task Headers_callbacks_fifo_identity_and_state_are_preserved()
await Assert.That(client.Requests[0]).IsSameReferenceAs(client.Requests[1]);
}
+ [Test]
+ public async Task Utf8_fifo_group_reuses_the_string_seen_by_the_native_callback()
+ {
+ var state = new SqsSendState("0");
+ string? decodedGroup = null;
+ var options = new SendOptions().AmazonSqs(request =>
+ {
+ decodedGroup = request.MessageGroupId;
+ request.MessageGroupId = "callback-override";
+ });
+ var message = new OutgoingMessage("ordered.fifo", "{}"u8.ToArray(),
+ orderingKey: new WireString("customer-123"u8.ToArray()), options: options);
+
+ state.Prepare(message, "https://sqs.example/ordered.fifo", true);
+ state.CopyToEntry();
+
+ await Assert.That(decodedGroup).IsEqualTo("customer-123");
+ await Assert.That(state.Request.MessageGroupId).IsSameReferenceAs(decodedGroup);
+ await Assert.That(state.Entry.MessageGroupId).IsSameReferenceAs(decodedGroup);
+ }
+
[Test]
public async Task Native_replacement_dictionaries_remain_caller_owned()
{
diff --git a/website/docs/transports/amazon-sqs.md b/website/docs/transports/amazon-sqs.md
index 082762817..b3b2a8150 100644
--- a/website/docs/transports/amazon-sqs.md
+++ b/website/docs/transports/amazon-sqs.md
@@ -74,7 +74,7 @@ await sender.SendAsync(order, options => options.AmazonSqs(request =>
}));
```
-Callbacks receive native `SendMessageRequest` for both single and batch sends. They run once per message before native admission. Original envelope headers, resolved destination, portable group key and scheduled time take precedence over conflicting callback values. Do not retain borrowed request objects. Native callbacks cannot be persisted in the outbox.
+Callbacks receive native `SendMessageRequest` for both single and batch sends. They run once per message before native admission. Original envelope headers, resolved destination, portable group key and scheduled time take precedence over conflicting callback values. The portable group key is decoded once and the same native string is restored after the callback. Do not retain borrowed request objects. Native callbacks cannot be persisted in the outbox.
## Batching and telemetry
@@ -96,4 +96,4 @@ dotnet run -c Release --project benchmarks/Relayer.Benchmarks -- --filter "*SqsS
Native request, entry and attribute containers are pooled per concurrent operation. SQS requires a text body, so decoding serialized UTF-8 bytes allocates a native-body string on each send. Nonempty UTF-8 header values and group keys also allocate strings. Under the approved native-boundary allocation policy (D52), these required `SendMessageRequest.MessageBody`, `MessageAttributeValue.StringValue`, and `MessageGroupId` strings count as native-client cost when the equivalent raw-client preparation allocates at least as much. All other pipeline allocations remain subject to the zero-allocation requirement. The 5% throughput budget is unchanged; the serialized-send benchmark does not establish the full default-JSON pipeline budget.
-`SqsBindingBenchmarks` isolates these conversions without network, SDK response, or serializer allocations. It writes the default binary-mode envelope with changing IDs/timestamps and a 256-byte body on each invocation. Run it with `--filter "*SqsBindingBenchmarks*"` to pin Relayer's additional allocation cost against equivalent raw-client preparation, independently of native request overhead. The earlier default-envelope probe reported 856 B/message on each path (0 additional B); that historical report is not a measurement of every payload or configuration.
+`SqsBindingBenchmarks` isolates these conversions without network, SDK response, or serializer allocations. It writes the default binary-mode envelope with changing IDs/timestamps and a 256-byte body on each invocation, for both standard messages and FIFO messages with a UTF-8 group key. Run it with `--filter "*SqsBindingBenchmarks*"` to pin Relayer's additional allocation cost against equivalent raw-client preparation, independently of native request overhead. The earlier default-envelope probe reported 856 B/message on each path (0 additional B); that historical report is not a measurement of every payload or configuration.