From d2335d9e74ef15b1b03ef105f6f62744dc66ac37 Mon Sep 17 00:00:00 2001
From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com>
Date: Tue, 10 Nov 2026 04:04:46 +0000
Subject: [PATCH 1/4] Add atomic SQL Server consumer inbox integration (#332)
---
.../SqlServerConsumerBenchmarks.cs | 106 ++++++
.../SqlServerOutboxEnlistmentBenchmarks.cs | 2 +-
.../SqlServerOutboxReadBenchmarks.cs | 2 +-
docs/decisions.md | 31 ++
docs/design.md | 7 +-
.../SqlServerConsumerExtensions.cs | 102 ++++++
.../SqlServerOutbox.cs | 5 +
.../SqlServerOutboxSchema.cs | 11 +
.../SqlServerOutboxTransaction.cs | 10 +
.../InboxTests.cs | 337 ++++++++++++++++++
.../Relayer.Outbox.SqlServer.Tests.csproj | 2 +
website/docs/reference/sqlserver-store.md | 54 ++-
website/docs/roadmap.md | 4 +-
website/src/pages/index.js | 2 +-
14 files changed, 667 insertions(+), 8 deletions(-)
create mode 100644 benchmarks/Relayer.Benchmarks/SqlServerConsumerBenchmarks.cs
create mode 100644 src/Relayer.Outbox.SqlServer/SqlServerConsumerExtensions.cs
create mode 100644 tests/Relayer.Outbox.SqlServer.Tests/InboxTests.cs
diff --git a/benchmarks/Relayer.Benchmarks/SqlServerConsumerBenchmarks.cs b/benchmarks/Relayer.Benchmarks/SqlServerConsumerBenchmarks.cs
new file mode 100644
index 000000000..45f92947f
--- /dev/null
+++ b/benchmarks/Relayer.Benchmarks/SqlServerConsumerBenchmarks.cs
@@ -0,0 +1,106 @@
+#pragma warning disable RLY001 // This benchmark uses an explicitly registered cached serializer.
+using System.Buffers;
+using BenchmarkDotNet.Attributes;
+using Microsoft.Data.SqlClient;
+using Microsoft.Extensions.DependencyInjection;
+using Relayer.Outbox.SqlServer;
+using Relayer.Serialization;
+
+namespace Relayer.Benchmarks;
+
+/// Native inbox transaction versus scoped consumer boundary, including SqlClient I/O and allocations.
+[MemoryDiagnoser]
+public class SqlServerConsumerBenchmarks
+{
+ private readonly SqlServerOutboxOptions _options = new() { TablePrefix = "consumer_" + Guid.NewGuid().ToString("N") + "_" };
+ private string _connection = null!;
+ private string _table = null!;
+ private string _insert = null!;
+ private string _id = null!;
+ private ServiceProvider _provider = null!;
+ private ConsumePipeline _pipeline = null!;
+
+ [Params(false, true)]
+ public bool Duplicate { get; set; }
+
+ [GlobalSetup]
+ public async Task Setup()
+ {
+ _connection = Environment.GetEnvironmentVariable("RELAYER_SQLSERVER_BENCHMARK_CONNECTION")
+ ?? throw new InvalidOperationException("Set RELAYER_SQLSERVER_BENCHMARK_CONNECTION to an isolated SQL Server database.");
+ _table = $"[dbo].[{_options.TablePrefix}inbox]";
+ _insert = $"INSERT INTO {_table} (consumer, message_id) SELECT @consumer, @id WHERE NOT EXISTS (SELECT 1 FROM {_table} WITH (UPDLOCK, HOLDLOCK) WHERE consumer = @consumer AND message_id = @id)";
+ _id = Guid.CreateVersion7().ToString("D");
+ var services = new ServiceCollection();
+ services.AddRelayerSqlServerOutbox(_options);
+ services.AddRelayer(r => { r.MessageTypes.Add("benchmark.sql-consumer"); r.Handler(); });
+ _provider = services.BuildServiceProvider();
+ _pipeline = new ConsumePipelineBuilder(_provider.GetRequiredService(),
+ _provider.GetRequiredService(), new Serializer(), static (_, error, _) => ValueTask.FromException(error))
+ .SqlServer("benchmark", _connection, inbox: true)
+ .Handler(_provider.GetRequiredService().GetHandler()).Build(contextPoolCapacity: 1);
+ await Execute(SqlServerOutboxSchema.CreateScript(_options));
+ if (Duplicate) await NativeInbox();
+ }
+
+ // IterationSetup limits invocation count to one, keeping fresh-key measurements bounded.
+ [IterationSetup]
+ public void Reset()
+ {
+ if (Duplicate) return;
+ using var connection = new SqlConnection(_connection);
+ connection.Open();
+ using var command = new SqlCommand($"DELETE FROM {_table}", connection);
+ command.ExecuteNonQuery();
+ }
+
+ [Benchmark(Baseline = true)]
+ public async Task NativeInbox()
+ {
+ await using var connection = new SqlConnection(_connection);
+ await connection.OpenAsync();
+ await using var transaction = (SqlTransaction)await connection.BeginTransactionAsync();
+ await using var command = new SqlCommand(_insert, connection, transaction);
+ command.Parameters.Add(new SqlParameter("@consumer", System.Data.SqlDbType.NVarChar, 256) { Value = "benchmark" });
+ command.Parameters.Add(new SqlParameter("@id", System.Data.SqlDbType.UniqueIdentifier) { Value = Guid.Parse(_id) });
+ await command.ExecuteNonQueryAsync();
+ await transaction.CommitAsync();
+ }
+
+ [Benchmark]
+ public async ValueTask ConsumerInbox()
+ {
+ using var context = _pipeline.RentContext(new ConsumeMessage
+ {
+ MessageId = _id, MessageType = new("benchmark.sql-consumer", 1), Body = ReadOnlySequence.Empty
+ });
+ await _pipeline.ProcessAsync(context);
+ }
+
+ private async Task Execute(string sql)
+ {
+ await using var connection = new SqlConnection(_connection);
+ await connection.OpenAsync();
+ await using var command = new SqlCommand(sql, connection);
+ await command.ExecuteNonQueryAsync();
+ }
+
+ [GlobalCleanup]
+ public async Task Cleanup()
+ {
+ await _provider.DisposeAsync();
+ await Execute($"DROP TABLE {_table}, [dbo].[{_options.TablePrefix}outbox]");
+ }
+ public sealed class Probe;
+ public sealed class Handler : IHandler
+ {
+ public ValueTask HandleAsync(Probe message, MessageContext context, CancellationToken cancellationToken) => default;
+ }
+ private sealed class Serializer : IMessageSerializer
+ {
+ private readonly Probe _probe = new();
+ public string ContentType => "benchmark/cached";
+ public TMessage Deserialize(ReadOnlySequence source) => (TMessage)(object)_probe;
+ public void Serialize(TMessage message, IBufferWriter destination) => throw new NotSupportedException();
+ }
+}
diff --git a/benchmarks/Relayer.Benchmarks/SqlServerOutboxEnlistmentBenchmarks.cs b/benchmarks/Relayer.Benchmarks/SqlServerOutboxEnlistmentBenchmarks.cs
index 260c63d04..0a8086b21 100644
--- a/benchmarks/Relayer.Benchmarks/SqlServerOutboxEnlistmentBenchmarks.cs
+++ b/benchmarks/Relayer.Benchmarks/SqlServerOutboxEnlistmentBenchmarks.cs
@@ -124,7 +124,7 @@ public async Task Cleanup()
{
await using var connection = new SqlConnection(_connectionString);
await connection.OpenAsync();
- await using var drop = new SqlCommand($"DROP TABLE IF EXISTS {_table}", connection);
+ await using var drop = new SqlCommand($"DROP TABLE IF EXISTS {_table}, [dbo].[{_options.TablePrefix}inbox]", connection);
await drop.ExecuteNonQueryAsync();
_nativeRows.Dispose();
_scope.Dispose();
diff --git a/benchmarks/Relayer.Benchmarks/SqlServerOutboxReadBenchmarks.cs b/benchmarks/Relayer.Benchmarks/SqlServerOutboxReadBenchmarks.cs
index ed17c9a84..be8c2b833 100644
--- a/benchmarks/Relayer.Benchmarks/SqlServerOutboxReadBenchmarks.cs
+++ b/benchmarks/Relayer.Benchmarks/SqlServerOutboxReadBenchmarks.cs
@@ -55,7 +55,7 @@ public async Task Cleanup()
{
await using var connection = new SqlConnection(_connectionString);
await connection.OpenAsync();
- await using var command = new SqlCommand($"DROP TABLE IF EXISTS [dbo].[{_options.TablePrefix}outbox]", connection);
+ await using var command = new SqlCommand($"DROP TABLE IF EXISTS [dbo].[{_options.TablePrefix}outbox], [dbo].[{_options.TablePrefix}inbox]", connection);
await command.ExecuteNonQueryAsync();
}
}
diff --git a/docs/decisions.md b/docs/decisions.md
index 0084ccbf7..e3a914679 100644
--- a/docs/decisions.md
+++ b/docs/decisions.md
@@ -69,6 +69,7 @@ To change a decision, add a new entry that supersedes it rather than editing his
| [D56](#d56-postgresql-cdc-wakes-existing-unordered-recovery) | PostgreSQL CDC wakes existing unordered recovery | Accepted |
| [D57](#d57-google-pubsub-uses-prepared-native-api-clients) | Google Pub/Sub uses prepared native API clients | Accepted |
| [D58](#d58-mysql-consumers-share-the-adonet-outbox-transaction) | MySQL consumers share the ADO.NET outbox transaction | Accepted |
+| [D59](#d59-sql-server-consumers-reuse-the-adonet-outbox-transaction) | SQL Server consumers reuse the ADO.NET outbox transaction | Accepted |
---
@@ -1315,3 +1316,33 @@ unsupported, as in D48. EF Core, saga persistence, ordered workers and inbox ret
separate work. Existing scoped enlistment/transaction allocations remain visible in comparisons;
no inbox buffers are allocated on the enqueue-only path. See the
[MySQL guide](../website/docs/reference/mysql-store.md#atomic-consumer-inbox).
+
+## D59. SQL Server consumers reuse the ADO.NET outbox transaction
+
+**Status.** Accepted.
+
+**Context.** #332 needs atomic inbox identity, handler business writes and outgoing rows. The existing
+EF consumer is specific to Npgsql and cannot enlist SQL Server business writes. SqlClient 7.1.1's
+[SqlTransaction](https://github.com/dotnet/SqlClient/blob/v7.1.1/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlTransaction.cs)
+already owns native commit, rollback and disposal, and D47 wraps it for ADO.NET/Dapper enlistment.
+SQL Server primary keys and `UPDLOCK, HOLDLOCK` supply uniqueness and serializable key-range locking.
+No distributed lock, duplicate exception loop, pool or retry engine is needed.
+
+**Decision.** An explicit outer `.SqlServer(consumer, connectionString, inbox: true)` boundary owns
+the existing scoped outbox transaction. Expose its borrowed `CurrentTransaction` for business commands.
+Insert the `(consumer, message_id)` inbox key before handling through a conditional insert protected
+by native update/range locks. A competing delivery waits for commit or rollback; a committed key skips
+the handler. Consumer names are binary case-sensitive, bounded to 256 UTF-16 code units and reject
+trailing spaces so SQL padding cannot alias accepted names. Inbox UUIDs use native `uniqueidentifier`
+for equality; ordered outbox IDs retain D46's binary representation.
+
+Commit/rollback by handlers is rejected; premature disposal rolls back and fails the delivery. Ordinary
+failure handling receives native failures after transaction disposal. Retry/dead-letter requests roll back;
+otherwise request immutable completion before committing, as in D36. Count duplicates only after commit.
+
+**Consequences.** The opt-in inbox supports ADO.NET/Dapper single-message consumers with the existing
+SQL Server outbox registration, schema/options and direct dispatcher. EF Core, sagas, batch consumers,
+provider retry strategies and inbox retention workers remain separate work. The connection string fixes
+the database per pipeline; outbox options fix the schema/prefix at composition. A mismatching reloaded
+scope fails before opening a transaction; restart the pipeline to select a new schema/prefix. D46's trimming/AOT restriction
+continues to apply. See the [SQL Server guide](../website/docs/reference/sqlserver-store.md#atomic-consumer-inbox).
diff --git a/docs/design.md b/docs/design.md
index 59556869c..a17494965 100644
--- a/docs/design.md
+++ b/docs/design.md
@@ -458,7 +458,7 @@ The outbox is the area where every existing library has had correctness bugs, so
### 6.2 Enlisting: hard to misuse
- **EF Core:** Relayer registers a `SaveChangesInterceptor` and a `DbTransactionInterceptor`. Before an implicit save, `context.EnlistRelayerOutbox()` explicitly selects the context that owns buffered sends. An explicit EF transaction activates enlistment automatically when unambiguous. `SaveChangesAsync`, or committing the EF transaction directly, writes business data and outgoing rows atomically. You do not need to override `SaveChanges` (Silverback #164), and it works with **multiple DbContexts** (Silverback #163). Commit through EF's `IDbContextTransaction`, including its `UseTransaction` wrapper: calling the underlying `DbTransaction.Commit` bypasses EF interception. D31 records ownership and failure boundaries; [the site](https://relayer.tomlonghurst.dev/docs/reference/ef-core-outbox) documents implemented PostgreSQL enlistment and remaining dispatch work.
-- **ADO.NET / Dapper:** `await using var tx = await outbox.BeginTransactionAsync(connection)` returns a `DbTransaction` subclass. Commit writes the shared outbox batch before the native commit. Create business commands through `tx.Connection`, including Dapper calls: Npgsql commands from the original connection cannot accept a wrapper transaction (D32). Rollback and disposal discard buffered messages. See [PostgreSQL transactions](../website/docs/reference/postgres-outbox.md) for ownership and recovery boundaries. SQL Server follows the same command-connection lifecycle (D47), flushing reusable rows through native `SqlBulkCopy` on the business transaction. Its opt-in unordered commit dispatcher uses native fenced batches (D49); see [SQL Server transactions and dispatch](../website/docs/reference/sqlserver-store.md). SQL Server EF Core, inbox, ordered dispatch and recovery remain planned. MySQL ADO.NET/Dapper enqueue (D48) also supports opt-in commit-triggered unordered dispatch using native MySqlBatch and fenced row counts (D55); its opt-in ADO.NET/Dapper consumer boundary commits inbox identity, business writes and outgoing rows atomically before settlement; ordered and recovery workers remain planned.
+- **ADO.NET / Dapper:** `await using var tx = await outbox.BeginTransactionAsync(connection)` returns a `DbTransaction` subclass. Commit writes the shared outbox batch before the native commit. Create business commands through `tx.Connection`, including Dapper calls: Npgsql commands from the original connection cannot accept a wrapper transaction (D32). Rollback and disposal discard buffered messages. See [PostgreSQL transactions](../website/docs/reference/postgres-outbox.md) for ownership and recovery boundaries. SQL Server follows the same command-connection lifecycle (D47), flushing reusable rows through native `SqlBulkCopy` on the business transaction. Its opt-in unordered commit dispatcher uses native fenced batches (D49); see [SQL Server transactions and dispatch](../website/docs/reference/sqlserver-store.md). SQL Server offers an opt-in ADO.NET consumer inbox boundary using native key-range locking and the same outbox transaction (D59). SQL Server EF Core, ordered dispatch and recovery remain planned. MySQL ADO.NET/Dapper enqueue (D48) also supports opt-in commit-triggered unordered dispatch using native MySqlBatch and fenced row counts (D55); its opt-in ADO.NET/Dapper consumer boundary commits inbox identity, business writes and outgoing rows atomically before settlement; ordered and recovery workers remain planned.
- **MongoDB / DynamoDB:** use their session and transaction APIs in the same style.
### 6.3 Schema
@@ -554,6 +554,11 @@ Before commit the boundary requests completion if no settlement outcome is pendi
one-request rule rejects settlement changes during scope disposal after the work is durable.
See [consumer configuration and failure boundaries](https://relayer.tomlonghurst.dev/docs/reference/ef-core-inbox).
+SQL Server ADO.NET/Dapper consumers opt into `.SqlServer(consumer, connectionString, inbox: true)`
+as their outer transaction boundary (D59). Native key-range locks and primary-key uniqueness protect
+the inbox identity; business writes and outgoing rows share the existing outbox transaction.
+See [SQL Server consumer boundaries](../website/docs/reference/sqlserver-store.md#atomic-consumer-inbox).
+
### 6.6 Multi-tenancy
- Application-owned scoped factories select native connections or DbContexts, supporting a database per tenant or a schema per tenant (CAP #699, Rebus #1218, Wolverine #556). Reuse native `AddDbContext`/Npgsql configuration instead of introducing a library-owned `IOutboxStoreResolver` facade (D45). Manual units, explicit tenant endpoints and incoming single-message EF consumers use native scoped factories. With tenancy registered, the EF boundary validates the selected context per delivery/retry scope without resolving a startup context or requiring a fallback tenant. See the [native tenant store contract](../website/docs/reference/tenant-stores.md).
diff --git a/src/Relayer.Outbox.SqlServer/SqlServerConsumerExtensions.cs b/src/Relayer.Outbox.SqlServer/SqlServerConsumerExtensions.cs
new file mode 100644
index 000000000..83b5210d8
--- /dev/null
+++ b/src/Relayer.Outbox.SqlServer/SqlServerConsumerExtensions.cs
@@ -0,0 +1,102 @@
+using System.Data;
+using System.Diagnostics.CodeAnalysis;
+using System.Runtime.CompilerServices;
+using Microsoft.Data.SqlClient;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Options;
+
+namespace Relayer.Outbox.SqlServer;
+
+/// Configures atomic SQL Server handling with the scoped ADO.NET outbox.
+public static class SqlServerConsumerExtensions
+{
+ /// Owns one transaction around handling, optionally deduplicating by consumer and original UUIDv7.
+ ///
+ /// Register first. Register AddRelayerSqlServerOutbox and use SqlServerOutbox.CurrentTransaction.Connection
+ /// for business commands. Handlers must not complete or replace the transaction. No EF Core integration,
+ /// automatic retry strategy, ambient transactions or batch consumers are supported.
+ /// The native connection string passes through unchanged. Keep consumer identities stable across replicas.
+ ///
+ [RequiresUnreferencedCode("SqlClient 7.1.1 runtime trimming is unsupported; see https://github.com/dotnet/SqlClient/issues/1947.")]
+ [RequiresDynamicCode("SqlClient 7.1.1 runtime Native AOT is unsupported; see https://github.com/dotnet/SqlClient/issues/1947.")]
+ public static ConsumePipelineBuilder SqlServer(this ConsumePipelineBuilder builder, string consumer,
+ string connectionString, bool inbox = false)
+ {
+ ArgumentNullException.ThrowIfNull(builder);
+ ArgumentException.ThrowIfNullOrWhiteSpace(consumer);
+ if (consumer.Length > 256 || consumer.EndsWith(' '))
+ throw new ArgumentException("Consumer identities must fit 256 UTF-16 code units and must not end in a space.", nameof(consumer));
+ ArgumentException.ThrowIfNullOrWhiteSpace(connectionString);
+ _ = new SqlConnectionStringBuilder(connectionString);
+ return builder.Use(services =>
+ {
+ var outbox = services.GetRequiredService();
+ var options = services.GetRequiredService>().Value;
+ var table = SqlServerOutboxSchema.InboxTable(options);
+ var insert = inbox ? $"INSERT INTO {table} (consumer, message_id) SELECT @consumer, @id WHERE NOT EXISTS (SELECT 1 FROM {table} WITH (UPDLOCK, HOLDLOCK) WHERE consumer = @consumer AND message_id = @id)" : null;
+ return new Boundary(consumer, connectionString, outbox.Table, insert, services.GetRequiredService());
+ });
+ }
+
+ private sealed class Boundary(string consumer, string connectionString, string outboxTable, string? insert,
+ RelayerInstrumentation instrumentation) : IConsumeTransactionMiddleware
+ {
+ [AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder))]
+ public async ValueTask InvokeAsync(MessageContext context, ConsumeDelegate next)
+ {
+ var id = default(Guid);
+ if (insert is not null && (!Guid.TryParse(context.MessageId, out id) || id == Guid.Empty || id.Version != 7))
+ throw new MessageEnvelopeException("Inbox processing requires the original non-empty UUIDv7 message ID.");
+ var outbox = context.Services.GetRequiredService();
+ if (outbox.Table != outboxTable)
+ throw new InvalidOperationException("SQL Server consumer schema or prefix changed after composition. Restart the consumer pipeline with matching deployed outbox options.");
+ var cancellation = context.CancellationToken;
+ await using var transaction = (SqlServerOutboxTransaction)await outbox.BeginTransactionAsync(
+ connectionString, IsolationLevel.ReadCommitted, cancellation).ConfigureAwait(false);
+ transaction.ConsumerOwned = true;
+ if (insert is not null)
+ {
+ // Native serializable key-range locking waits for an overlapping owner before checking its committed key.
+ // UPDLOCK prevents two absent-key readers from taking shared ranges and then deadlocking on insert.
+ var native = transaction.Unwrap(transaction.Connection);
+ await using var command = new SqlCommand(insert, native.Connection, native);
+ var consumerParameter = command.CreateParameter();
+ consumerParameter.ParameterName = "@consumer";
+ consumerParameter.DbType = DbType.String;
+ consumerParameter.Size = 256;
+ consumerParameter.Value = consumer;
+ command.Parameters.Add(consumerParameter);
+ var idParameter = command.CreateParameter();
+ idParameter.ParameterName = "@id";
+ idParameter.DbType = DbType.Guid;
+ idParameter.Value = id;
+ command.Parameters.Add(idParameter);
+ if (await command.ExecuteNonQueryAsync(cancellation).ConfigureAwait(false) == 0)
+ {
+ RequestCompletion(context);
+ transaction.ConsumerOwned = false;
+ await transaction.CommitAsync(cancellation).ConfigureAwait(false);
+ instrumentation.RecordInboxDuplicate(consumer);
+ return;
+ }
+ }
+ await next(context).ConfigureAwait(false);
+ if (!ReferenceEquals(outbox.CurrentTransaction, transaction))
+ throw new InvalidOperationException("The handler ended the SQL Server consumer transaction. Let Relayer complete it.");
+ transaction.ConsumerOwned = false;
+ if (context.Features.Get()?.RequestedDisposition is { Kind: not DispositionKind.Complete })
+ await transaction.RollbackAsync(cancellation).ConfigureAwait(false);
+ else
+ {
+ RequestCompletion(context);
+ await transaction.CommitAsync(cancellation).ConfigureAwait(false);
+ }
+ }
+
+ private static void RequestCompletion(MessageContext context)
+ {
+ if (context.Features.Get() is { RequestedDisposition: null } settlement)
+ settlement.Complete();
+ }
+ }
+}
diff --git a/src/Relayer.Outbox.SqlServer/SqlServerOutbox.cs b/src/Relayer.Outbox.SqlServer/SqlServerOutbox.cs
index 250cb329f..adf7993d7 100644
--- a/src/Relayer.Outbox.SqlServer/SqlServerOutbox.cs
+++ b/src/Relayer.Outbox.SqlServer/SqlServerOutbox.cs
@@ -42,6 +42,11 @@ internal SqlServerOutbox(IOptionsSnapshot options, Relay
_table = SqlServerOutboxSchema.Table(options.Value);
}
+ /// The active borrowed transaction. Create business commands through its Connection; consumer middleware owns completion.
+ public DbTransaction? CurrentTransaction => _transaction is { IsActive: true } ? _transaction : null;
+
+ internal string Table => _table;
+
///
public bool IsActive => _transaction is { IsActive: true };
diff --git a/src/Relayer.Outbox.SqlServer/SqlServerOutboxSchema.cs b/src/Relayer.Outbox.SqlServer/SqlServerOutboxSchema.cs
index 420e5dedb..5220b44ff 100644
--- a/src/Relayer.Outbox.SqlServer/SqlServerOutboxSchema.cs
+++ b/src/Relayer.Outbox.SqlServer/SqlServerOutboxSchema.cs
@@ -10,11 +10,19 @@ public static string CreateScript(SqlServerOutboxOptions? options = null)
var schema = options.Schema ?? "dbo";
var quotedSchema = QuoteIdentifier(schema);
var table = Table(options);
+ var inbox = InboxTable(options);
var index = QuoteIdentifier(options.TablePrefix + "outbox_pending_idx");
// Dynamic DDL is needed for CREATE SCHEMA. Escape both identifier and SQL literal contexts.
return $"""
IF SCHEMA_ID(N'{Literal(schema)}') IS NULL
EXEC(N'CREATE SCHEMA {Literal(quotedSchema)}');
+ IF OBJECT_ID(N'{Literal(inbox)}', N'U') IS NULL
+ CREATE TABLE {inbox} (
+ consumer nvarchar(256) COLLATE Latin1_General_100_BIN2 NOT NULL,
+ message_id uniqueidentifier NOT NULL,
+ processed_at datetimeoffset(7) NOT NULL DEFAULT SYSUTCDATETIME(),
+ PRIMARY KEY (consumer, message_id)
+ );
IF OBJECT_ID(N'{Literal(table)}', N'U') IS NULL
BEGIN
CREATE TABLE {table} (
@@ -44,6 +52,9 @@ claim_expires_at datetimeoffset(7) NULL,
""";
}
+ internal static string InboxTable(SqlServerOutboxOptions options) =>
+ QuoteIdentifier(options.Schema ?? "dbo") + "." + QuoteIdentifier(options.TablePrefix + "inbox");
+
internal static string Table(SqlServerOutboxOptions options)
{
ArgumentNullException.ThrowIfNull(options.TablePrefix);
diff --git a/src/Relayer.Outbox.SqlServer/SqlServerOutboxTransaction.cs b/src/Relayer.Outbox.SqlServer/SqlServerOutboxTransaction.cs
index 6a651681a..b48c02126 100644
--- a/src/Relayer.Outbox.SqlServer/SqlServerOutboxTransaction.cs
+++ b/src/Relayer.Outbox.SqlServer/SqlServerOutboxTransaction.cs
@@ -11,6 +11,7 @@ internal sealed class SqlServerOutboxTransaction : DbTransaction
private readonly SqlConnection? _ownedConnection;
private readonly SqlServerOutboxConnection _connection;
private readonly IsolationLevel _isolationLevel;
+ internal bool ConsumerOwned { get; set; }
private bool _finished;
private bool _completing;
@@ -49,8 +50,14 @@ private void EnsureActive()
if (!IsActive) throw new InvalidOperationException("The SQL Server outbox transaction has completed or is completing.");
}
+ private void EnsureCompletionAllowed()
+ {
+ if (ConsumerOwned) throw new InvalidOperationException("The SQL Server consumer owns transaction completion. Let Relayer commit or roll back after handling.");
+ }
+
public override void Commit()
{
+ EnsureCompletionAllowed();
EnsureActive();
_completing = true;
try
@@ -64,6 +71,7 @@ public override void Commit()
public override async Task CommitAsync(CancellationToken cancellationToken = default)
{
+ EnsureCompletionAllowed();
EnsureActive();
_completing = true;
try
@@ -79,6 +87,7 @@ public override async Task CommitAsync(CancellationToken cancellationToken = def
public override void Rollback()
{
+ EnsureCompletionAllowed();
EnsureActive();
_completing = true;
try { _native.Rollback(); }
@@ -87,6 +96,7 @@ public override void Rollback()
public override async Task RollbackAsync(CancellationToken cancellationToken = default)
{
+ EnsureCompletionAllowed();
EnsureActive();
_completing = true;
try { await _native.RollbackAsync(cancellationToken).ConfigureAwait(false); }
diff --git a/tests/Relayer.Outbox.SqlServer.Tests/InboxTests.cs b/tests/Relayer.Outbox.SqlServer.Tests/InboxTests.cs
new file mode 100644
index 000000000..aec35d399
--- /dev/null
+++ b/tests/Relayer.Outbox.SqlServer.Tests/InboxTests.cs
@@ -0,0 +1,337 @@
+using System.Buffers;
+using Microsoft.Extensions.Options;
+using Microsoft.Extensions.Configuration;
+using Dapper;
+using Microsoft.Data.SqlClient;
+using Microsoft.Extensions.DependencyInjection;
+using Relayer.Serialization;
+using Relayer.TestFixtures;
+using Relayer.Transports;
+
+namespace Relayer.Outbox.SqlServer.Tests;
+
+[InheritsTests]
+[ClassDataSource(Shared = SharedType.PerTestSession)]
+public class InboxTests(SqlServerFixture server) : InboxContractTests
+{
+ protected override async Task CreateFixtureAsync()
+ {
+ var database = new Database(server.ConnectionString);
+ await database.Start();
+ return database;
+ }
+
+ [Test]
+ public async Task Inbox_is_opt_in()
+ {
+ await using var database = new Database(server.ConnectionString);
+ await database.Start();
+ await using var consumer = new Consumer(database, "orders", inbox: false);
+ var id = Guid.CreateVersion7();
+ await consumer.DeliverAsync(id);
+ await consumer.DeliverAsync(id);
+ await Assert.That(consumer.Invocations).IsEqualTo(2);
+ await Assert.That(await database.ReadStateAsync()).IsEqualTo(new DurableState(2, 0, 2));
+ }
+
+ [Test]
+ public async Task Consumer_identity_is_case_sensitive()
+ {
+ await using var database = new Database(server.ConnectionString);
+ await database.Start();
+ await using var lower = new Consumer(database, "orders");
+ await using var upper = new Consumer(database, "Orders");
+ var id = Guid.CreateVersion7();
+ await lower.DeliverAsync(id);
+ await upper.DeliverAsync(id);
+ await Assert.That(await database.ReadStateAsync()).IsEqualTo(new DurableState(2, 2, 2));
+ }
+
+ [Test]
+ [Arguments("")]
+ [Arguments("not-a-uuid")]
+ [Arguments("00000000-0000-0000-0000-000000000000")]
+ [Arguments("00000000-0000-4000-8000-000000000001")]
+ public async Task Inbox_rejects_missing_or_nonversion7_identity(string id)
+ {
+ await using var database = new Database(server.ConnectionString);
+ await database.Start();
+ await using var consumer = new Consumer(database, "orders");
+ if (id.Length == 0)
+ await Assert.That(async () => await consumer.DeliverRawAsync(id)).Throws();
+ else
+ await Assert.That(async () => await consumer.DeliverRawAsync(id)).Throws();
+ await Assert.That(consumer.Invocations).IsEqualTo(0);
+ await Assert.That(await database.ReadStateAsync()).IsEqualTo(new DurableState(0, 0, 0));
+ }
+
+ [Test]
+ public async Task Cancellation_while_waiting_for_duplicate_lock_leaves_owner_commit_intact()
+ {
+ await using var database = new Database(server.ConnectionString);
+ await database.Start();
+ await using var first = new Consumer(database, "orders");
+ await using var second = new Consumer(database, "orders");
+ var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(30));
+ first.AfterSave = async _ => { entered.SetResult(); await release.Task.WaitAsync(deadline.Token); };
+ var id = Guid.CreateVersion7();
+ var owner = first.DeliverAsync(id, deadline.Token);
+ try
+ {
+ await entered.Task.WaitAsync(deadline.Token);
+ using var cancellation = CancellationTokenSource.CreateLinkedTokenSource(deadline.Token);
+ var blocked = second.DeliverAsync(id, cancellation.Token);
+ await database.WaitForContentionAsync();
+ cancellation.Cancel();
+ var cancelled = false;
+ try { await blocked; }
+ catch (OperationCanceledException) { cancelled = true; }
+ catch (SqlException error) when (cancellation.IsCancellationRequested &&
+ error.Message.Contains("Operation cancelled by user", StringComparison.Ordinal))
+ {
+ // SqlClient can return its native server-attention error for cancellation during a lock wait.
+ cancelled = true;
+ }
+ await Assert.That(cancelled).IsTrue();
+ await Assert.That(second.Invocations).IsEqualTo(0);
+ }
+ finally
+ {
+ release.TrySetResult();
+ await owner;
+ }
+ await second.DeliverAsync(id);
+ await Assert.That(second.Invocations).IsEqualTo(0);
+ await Assert.That(await database.ReadStateAsync()).IsEqualTo(new DurableState(1, 1, 1));
+ }
+
+ [Test]
+ public async Task Changed_schema_options_fail_before_beginning_delivery()
+ {
+ await using var database = new Database(server.ConnectionString);
+ await database.Start();
+ var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary
+ {
+ ["TablePrefix"] = database.Prefix
+ }).Build();
+ await using var consumer = new Consumer(database, "orders", configuration: configuration);
+ configuration["TablePrefix"] = "changed_";
+ configuration.Reload();
+ await Assert.That(async () => await consumer.DeliverAsync(Guid.CreateVersion7())).Throws();
+ await Assert.That(consumer.Invocations).IsEqualTo(0);
+ await Assert.That(await database.ReadStateAsync()).IsEqualTo(new DurableState(0, 0, 0));
+ }
+
+ [Test]
+ public async Task Registration_rejects_ambiguous_consumer_names_and_invalid_native_configuration()
+ {
+ using var provider = new ServiceCollection().BuildServiceProvider();
+ var builder = new ConsumePipelineBuilder(provider.GetRequiredService(),
+ new MessageTypeRegistry(), new Serializer(), static (_, error, _) => ValueTask.FromException(error));
+ foreach (var name in new[] { " ", "orders ", new string('x', 257) })
+ await Assert.That(() => builder.SqlServer(name, "Server=unused")).Throws();
+ await Assert.That(() => builder.SqlServer("orders", "NotANativeKeyword=value")).Throws();
+ await Assert.That(() => builder.SqlServer("orders", "Server=unused")).Throws();
+ }
+
+ [Test]
+ [Arguments("commit")]
+ [Arguments("commitAsync")]
+ [Arguments("rollback")]
+ [Arguments("rollbackAsync")]
+ [Arguments("dispose")]
+ [Arguments("disposeAsync")]
+ public async Task Handler_cannot_complete_consumer_transaction(string operation)
+ {
+ await using var database = new Database(server.ConnectionString);
+ await database.Start();
+ await using var consumer = new Consumer(database, "orders");
+ consumer.AfterSave = async context =>
+ {
+ var transaction = context.Services.GetRequiredService().CurrentTransaction!;
+ switch (operation)
+ {
+ case "commit": transaction.Commit(); break;
+ case "commitAsync": await transaction.CommitAsync(); break;
+ case "rollback": transaction.Rollback(); break;
+ case "rollbackAsync": await transaction.RollbackAsync(); break;
+ case "dispose": transaction.Dispose(); break;
+ case "disposeAsync": await transaction.DisposeAsync(); break;
+ }
+ };
+ await Assert.That(async () => await consumer.DeliverAsync(Guid.CreateVersion7())).Throws();
+ await Assert.That(await database.ReadStateAsync()).IsEqualTo(new DurableState(0, 0, 0));
+ }
+
+ [Test]
+ [Arguments(false)]
+ [Arguments(true)]
+ public async Task Scope_disposal_cannot_change_committed_outcome(bool duplicate)
+ {
+ await using var database = new Database(server.ConnectionString);
+ await database.Start();
+ await using var consumer = new Consumer(database, "orders");
+ var id = Guid.CreateVersion7();
+ if (duplicate) await consumer.DeliverAsync(id);
+ consumer.Control.OnDispose = () =>
+ {
+ // A committed Complete disposition is immutable even before broker settlement.
+ var settlement = consumer.Control.Context!.Features.GetRequired();
+ Assert.Throws(() => settlement.Retry(TimeSpan.Zero));
+ };
+ // Duplicate handling skips the handler, so capture the context in middleware too.
+ await consumer.DeliverAsync(id);
+ await Assert.That(await database.ReadStateAsync()).IsEqualTo(new DurableState(1, 1, 1));
+ }
+
+ [Test]
+ public async Task Outbox_insert_failure_rolls_back_business_and_inbox()
+ {
+ await using var database = new Database(server.ConnectionString);
+ await database.Start();
+ await database.Execute($"ALTER TABLE {database.Table("outbox")} ADD CONSTRAINT [reject_{database.Prefix}] CHECK (attempts < 0)");
+ await using var consumer = new Consumer(database, "orders");
+ await Assert.That(async () => await consumer.DeliverAsync(Guid.CreateVersion7())).Throws();
+ await Assert.That(await database.ReadStateAsync()).IsEqualTo(new DurableState(0, 0, 0));
+ }
+
+ private sealed class Database(string connectionString) : InboxFixture
+ {
+ internal string Prefix { get; } = "inbox_" + Guid.NewGuid().ToString("N") + "_";
+ internal string ConnectionString => connectionString;
+ internal SqlServerOutboxOptions Options => new() { TablePrefix = Prefix };
+ internal string Table(string name) => $"[dbo].[{Prefix}{name}]";
+ internal Task Start() => Execute(SqlServerOutboxSchema.CreateScript(Options) + $"CREATE TABLE {Table("business")} (id int NOT NULL)");
+ internal async Task Execute(string sql)
+ {
+ await using var connection = new SqlConnection(connectionString);
+ await connection.OpenAsync();
+ await connection.ExecuteAsync(sql);
+ }
+ public override InboxConsumer Consumer(string name = "orders") => new Consumer(this, name);
+ public override async Task ReadStateAsync()
+ {
+ await using var connection = new SqlConnection(connectionString);
+ await connection.OpenAsync();
+ return new(await connection.ExecuteScalarAsync($"SELECT COUNT_BIG(*) FROM {Table("business")} WITH (READPAST)"),
+ await connection.ExecuteScalarAsync($"SELECT COUNT_BIG(*) FROM {Table("inbox")} WITH (READPAST)"),
+ await connection.ExecuteScalarAsync($"SELECT COUNT_BIG(*) FROM {Table("outbox")} WITH (READPAST)"));
+ }
+ public override async Task WaitForContentionAsync()
+ {
+ using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(20));
+ await using var connection = new SqlConnection(connectionString);
+ await connection.OpenAsync(deadline.Token);
+ while (true)
+ {
+ var command = new CommandDefinition("SELECT COUNT_BIG(*) FROM sys.dm_exec_requests r CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) t WHERE r.wait_type LIKE 'LCK%' AND t.text LIKE @pattern",
+ new { pattern = "%" + Prefix + "inbox%" }, cancellationToken: deadline.Token);
+ if (await connection.ExecuteScalarAsync(command) > 0) return;
+ await Task.Delay(10, deadline.Token);
+ }
+ }
+ public override async ValueTask DisposeAsync() => await Execute($"DROP TABLE {Table("business")}, {Table("inbox")}, {Table("outbox")}");
+ }
+
+ private sealed class Consumer : InboxConsumer
+ {
+ private readonly ServiceProvider _provider;
+ private readonly ConsumePipeline _pipeline;
+ internal Control Control { get; } = new();
+ internal Consumer(Database database, string name, bool inbox = true, IConfiguration? configuration = null)
+ {
+ var services = new ServiceCollection();
+ services.AddSingleton(Control);
+ services.AddScoped();
+ services.AddSingleton();
+ services.AddSingleton(static sp => sp.GetRequiredService());
+ services.AddSingleton();
+ if (configuration is null) services.AddRelayerSqlServerOutbox(database.Options);
+ else services.AddRelayerSqlServerOutbox(configuration);
+ services.AddScoped(sp =>
+ {
+ _ = sp.GetRequiredService();
+ return new(sp.GetRequiredService>(), sp.GetRequiredService());
+ });
+ services.AddRelayer(r =>
+ {
+ r.MessageTypes.Add("inbox.probe");
+ r.Handler();
+ r.AddTransport("events", t => t.Send("destination"));
+ });
+ _provider = services.BuildServiceProvider(new ServiceProviderOptions { ValidateScopes = true });
+ Control.Business = database.Table("business");
+ Control.AfterSave = context => AfterSave?.Invoke(context) ?? default;
+ _pipeline = new ConsumePipelineBuilder(_provider.GetRequiredService(),
+ _provider.GetRequiredService(), new Serializer(), static (_, error, _) => ValueTask.FromException(error))
+ .SqlServer(name, database.ConnectionString, inbox)
+ .Handler(_provider.GetRequiredService().GetHandler())
+ .Settle(_ => Settlement?.Invoke() ?? default).Build();
+ }
+ public override RelayerInstrumentation Instrumentation => _provider.GetRequiredService();
+ public override int Invocations => Control.Invocations;
+ public override int DirectSends => _provider.GetRequiredService().Sends;
+ public override Task DeliverAsync(Guid messageId, CancellationToken cancellation = default) => DeliverRawAsync(messageId.ToString("D"), cancellation);
+ internal async Task DeliverRawAsync(string messageId, CancellationToken cancellation = default)
+ {
+ using var context = _pipeline.RentContext(new ConsumeMessage
+ {
+ MessageType = new("inbox.probe", 1), MessageId = messageId,
+ Body = new ReadOnlySequence(new byte[] { 1 })
+ }, cancellation);
+ Control.Context = context;
+ await _pipeline.ProcessAsync(context);
+ }
+ public override ValueTask DisposeAsync() => _provider.DisposeAsync();
+ }
+
+ public sealed class Control
+ {
+ public int Invocations;
+ public string Business = "";
+ public Func? AfterSave;
+ public Action? OnDispose;
+ public MessageContext? Context;
+ }
+ public sealed class Disposer(Control control) : IDisposable, IAsyncDisposable
+ {
+ public void Dispose() => control.OnDispose?.Invoke();
+ public ValueTask DisposeAsync() { Dispose(); return default; }
+ }
+ public sealed class Handler(SqlServerOutbox outbox, ISender sender, Control control) : IHandler
+ {
+ public async ValueTask HandleAsync(Probe message, MessageContext context, CancellationToken cancellationToken)
+ {
+ var invocation = Interlocked.Increment(ref control.Invocations);
+ var transaction = outbox.CurrentTransaction!;
+ await transaction.Connection!.ExecuteAsync(new CommandDefinition($"INSERT INTO {control.Business} VALUES (@id)",
+ new { id = invocation }, transaction, cancellationToken: cancellationToken));
+ await sender.SendAsync(new Probe(invocation), cancellationToken);
+ if (control.AfterSave is { } after) await after(context);
+ }
+ }
+ [Message("inbox.probe")]
+ public sealed record Probe(int Value);
+ public sealed class Empty;
+ private sealed class Serializer : IMessageSerializer
+ {
+ public string ContentType => "application/test";
+ public void Serialize(TMessage message, IBufferWriter destination)
+ { destination.GetSpan(1)[0] = 1; destination.Advance(1); }
+ public TMessage Deserialize(ReadOnlySequence source) => (TMessage)(object)new Probe(1);
+ }
+ private sealed class Transport : ITransport
+ {
+ public int Sends;
+ public string Name => "events";
+ public TransportCapabilities GetCapabilities(string endpoint) => new() { DeadLetter = true };
+ public ValueTask SendAsync(OutgoingMessage message, CancellationToken cancellationToken) { Interlocked.Increment(ref Sends); return default; }
+ public ValueTask SendBatchAsync(ReadOnlyMemory messages, CancellationToken cancellationToken) => throw new NotSupportedException();
+ public ValueTask ApplyTopologyAsync(TopologyMode mode, CancellationToken cancellationToken) => new(new TopologyReport([]));
+ public Task StartAsync(CancellationToken cancellationToken) => Task.CompletedTask;
+ public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
+ public ValueTask DisposeAsync() => default;
+ }
+}
diff --git a/tests/Relayer.Outbox.SqlServer.Tests/Relayer.Outbox.SqlServer.Tests.csproj b/tests/Relayer.Outbox.SqlServer.Tests/Relayer.Outbox.SqlServer.Tests.csproj
index 3cd20f7eb..b314b8128 100644
--- a/tests/Relayer.Outbox.SqlServer.Tests/Relayer.Outbox.SqlServer.Tests.csproj
+++ b/tests/Relayer.Outbox.SqlServer.Tests/Relayer.Outbox.SqlServer.Tests.csproj
@@ -5,11 +5,13 @@
+
+
diff --git a/website/docs/reference/sqlserver-store.md b/website/docs/reference/sqlserver-store.md
index ab296016e..7aae31399 100644
--- a/website/docs/reference/sqlserver-store.md
+++ b/website/docs/reference/sqlserver-store.md
@@ -6,7 +6,7 @@ description: "SQL Server ADO.NET/Dapper transactions, commit-triggered dispatch,
`Relayer.Outbox.SqlServer` implements the [durable store contract](outbox-stores.md) using
`Microsoft.Data.SqlClient` and SQL Server's native connection pooling. It supplies reads, atomic claims,
renewal, completion, failure persistence, eligible backlog counts and scoped ADO.NET/Dapper transaction
-enlistment and opt-in commit-triggered unordered dispatch. **EF Core, inbox deduplication, ordered workers, lane leases, poison-row movement and
+enlistment, opt-in consumer inbox deduplication and commit-triggered unordered dispatch. **EF Core, ordered workers, lane leases, poison-row movement and
maintenance remain planned for SQL Server.** PostgreSQL's worker registrations do not accept this provider.
Registering a durable store alone does not make `ISender` transactional.
@@ -20,7 +20,8 @@ Schema SQL/options remain AOT safe. This restriction is specific to this optiona
Write the initial schema with your application's deployment tooling. Initial creation is idempotent and
does not validate or upgrade an existing table. Schema evolution and rollback remain application-owned.
-This script creates only an outbox table and its pending index; it does not create inbox, dead or lease tables.
+This script creates the outbox table, pending index and inbox table. Re-run it when upgrading from
+a version without the inbox table; existing outbox definitions are unchanged. It does not create dead or lease tables.
```csharp
using Microsoft.Extensions.DependencyInjection;
@@ -101,6 +102,51 @@ for a future dispatcher. Cancellation is passed to SqlClient; some server-side b
only when the server responds or the native timeout expires ([SqlClient #4965](https://github.com/dotnet/SqlClient/issues/4965)). Cancellation before native commit still
rolls back the complete unit.
+## Atomic consumer inbox
+
+Register the scoped outbox above, deploy its schema, then register the SQL Server consumer boundary
+first in the single-message consume pipeline:
+
+```csharp
+pipeline.SqlServer("orders-v1", connectionString, inbox: true);
+
+// Inside a handler, inject SqlServerOutbox and ISender:
+var transaction = outbox.CurrentTransaction!;
+await transaction.Connection!.ExecuteAsync(
+ "INSERT INTO orders (id) VALUES (@Id)", new { Id = order.Id }, transaction);
+await sender.SendAsync(new OrderPlaced(order.Id));
+// Relayer owns commit, rollback and disposal.
+```
+
+`inbox` defaults to `false`; enable it explicitly to deduplicate. Use a stable consumer name across
+replicas and restarts, at most 256 UTF-16 code units with no trailing space. Names are case-sensitive.
+Deduplication requires the original nonempty UUIDv7 message ID and keys it by consumer. The inbox uses
+`uniqueidentifier` for equality only; the outbox's RFC byte ordering remains unchanged.
+
+The boundary opens one native read-committed transaction. SQL Server's `UPDLOCK, HOLDLOCK` key-range
+locks and primary-key uniqueness serialize competing deliveries of the same identity. A committed key
+skips handling and increments `relayer.inbox.duplicates`; rollback permits redelivery to run the handler.
+Business writes through `CurrentTransaction.Connection`, inbox identity and outgoing rows commit
+atomically before broker settlement. An acknowledgement failure can redeliver committed work safely.
+Handler failures, cancellation and requested retry/dead-letter outcomes roll back before existing failure
+handling and settlement. Cancellation during an inbox lock wait can surface SqlClient’s native
+`SqlException` server-attention error instead of `OperationCanceledException`; rollback still completes
+before the failure leaves the boundary. Completion is requested before commit when none is pending; scope disposal
+cannot change an already durable outcome.
+
+Do not commit, roll back, dispose or replace the consumer transaction inside the handler. Commit and
+rollback calls are rejected, while premature disposal rolls back and causes handling to fail. Business
+commands must use the borrowed connection, and must not issue SQL transaction-control commands or
+close its native connection. Nested boundaries and ambient transactions are unsupported. This integration
+supports ADO.NET/Dapper only, not SQL Server EF Core, saga persistence or batch consumers. There is no
+provider retry strategy or automatic conflict replay: existing failure handling receives native failures.
+The connection string selects one fixed database per pipeline; outbox options select its deployed schema and prefix at composition.
+Changing schema or prefix requires rebuilding the pipeline; a mismatching scope fails before opening its transaction. Native AOT/trimming restrictions above apply to this boundary too.
+
+Retain inbox keys for as long as messages can be redelivered. SQL Server inbox cleanup is application-owned;
+deleting a key allows that identity to execute again. Outgoing messages still require the separately registered
+dispatcher and recovery described below.
+
## Commit-triggered unordered dispatch
Deploy the schema first. Select a named worker explicitly in the scoped outbox options:
@@ -203,6 +249,10 @@ Set `RELAYER_SQLSERVER_BENCHMARK_CONNECTION` to an isolated database with schema
dotnet run -c Release --project benchmarks/Relayer.Benchmarks -- --filter '*SqlServerOutboxReadBenchmarks*'
```
+`SqlServerConsumerBenchmarks` compares native inbox transactions with the consume pipeline, including
+scoped enlistment, UUID parsing, native key-range locking and commit. It covers fresh and duplicate identities
+with `[MemoryDiagnoser]`; select it with the same connection variable and `--filter`.
+
`SqlServerOutboxBufferBenchmarks` attributes reusable copy/header/lane work at 256 and 4096 bytes without database I/O.
`SqlServerOutboxCommitBenchmarks` compares native bulk-copy commits with buffered commits at 1 and 64 rows.
`SqlServerOutboxDispatchBenchmarks` compares reusable envelope buffers with commit-to-worker ownership
diff --git a/website/docs/roadmap.md b/website/docs/roadmap.md
index 5dfbdb982..9b229c899 100644
--- a/website/docs/roadmap.md
+++ b/website/docs/roadmap.md
@@ -23,7 +23,7 @@ Relayer is in early development. Track progress in [GitHub issues](https://githu
- [Request/response](guides/request-response.md) with explicit endpoints, mandatory timeouts, bounded process-local correlation and ordinary reply durability. Arbitrary reply destinations and temporary queues remain unsupported.
- Provider-owned tracing and direct single/batch send tracing, integrated with the in-memory adapter's delivery and native settlement spans. PostgreSQL outbox enqueue, dispatch and consumer creation links are implemented.
- The [durable outbox store contract](reference/outbox-stores.md), with bounded reads, fenced claims and an optional keyed health adapter, plus the [PostgreSQL read/claim implementation](reference/postgres-store.md).
-- [SQL Server durable store primitives](reference/sqlserver-store.md): explicit schema, UUIDv7-ordered reads, atomic fenced mutations and eligible counts. SQL Server ADO.NET/Dapper transactional enqueue and commit-triggered unordered dispatch are implemented; EF Core, inbox, ordered workers, recovery and maintenance remain planned.
+- [SQL Server durable store primitives](reference/sqlserver-store.md): explicit schema, UUIDv7-ordered reads, atomic fenced mutations and eligible counts. SQL Server ADO.NET/Dapper transactional enqueue, opt-in atomic consumer inbox and commit-triggered unordered dispatch are implemented; EF Core, ordered workers, recovery and maintenance remain planned.
- [MySQL durable store, transactional enqueue and direct dispatch](reference/mysql-store.md), with InnoDB schema SQL, network-order UUIDs, shared store/dispatch contract suites and ADO.NET/Dapper transaction ownership. Opt-in atomic ADO.NET/Dapper consumer inbox is implemented; ordered dispatch and recovery/retention remain planned.
- [PostgreSQL schema scripts and database CLI](reference/postgres-schema.md), including an application-owned EF Core migration path.
- [EF Core transaction enlistment for PostgreSQL](reference/ef-core-outbox.md): implicit saves, explicit transactions, atomic rollback, multiple contexts and one batched insert per transaction.
@@ -32,7 +32,7 @@ Relayer is in early development. Track progress in [GitHub issues](https://githu
- [Native tenant store selection](reference/tenant-stores.md): database/schema isolation through application-owned scoped factories, including incoming single-message EF consumers without a fallback tenant. Durable tenant metadata binding and bounded tenant dispatch remain planned.
- [Saga state transitions](guides/sagas.md): explicit process state, PostgreSQL optimistic concurrency and atomic state/inbox/outbox commits using the existing EF Core boundary. [Durable saga timeouts](guides/saga-timeouts.md) compose typed messages, explicit wait correlation and existing transactional scheduled sends.
- [PostgreSQL ADO.NET and Dapper transactions](reference/postgres-outbox.md): scoped enlistment, owned message copies and one atomic batched insert on commit.
-- [SQL Server commit-triggered unordered dispatch](reference/sqlserver-store.md#commit-triggered-unordered-dispatch): bounded owned buffers, native batches and fenced outcomes. SQL Server recovery, ordered dispatch, inbox and maintenance remain planned.
+- [SQL Server commit-triggered unordered dispatch](reference/sqlserver-store.md#commit-triggered-unordered-dispatch): bounded owned buffers, native batches and fenced outcomes. SQL Server recovery, ordered dispatch and maintenance remain planned.
- [Unordered PostgreSQL direct dispatch](reference/direct-dispatch.md): background sends immediately after EF commit, fenced claims, native transport batches and fenced batch deletion. Register [leased recovery and cleanup](reference/postgres-maintenance.md) for unordered crash recovery and bounded dead/inbox retention. [Poison-row limits and key-scoped parking](reference/postgres-store.md#poison-rows-and-key-release) are implemented, with durable inspection, redrive and purge.
- The consume pipeline and the native receive SPI.
- [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`.
diff --git a/website/src/pages/index.js b/website/src/pages/index.js
index 1c9a17387..d3f7969ac 100644
--- a/website/src/pages/index.js
+++ b/website/src/pages/index.js
@@ -314,7 +314,7 @@ const status = [
['Durable outbox contracts and keyed health adapter', 'Implemented core seam', true],
['PostgreSQL schema scripts, CLI and EF migration path', 'Implemented schema tooling', true],
['PostgreSQL durable reads and fenced claims', 'Implemented store operations', true],
- ['SQL Server outbox transactions and durable stores', 'ADO.NET/Dapper enlistment, fenced claims and unordered commit dispatch implemented; inbox, recovery and ordered workers planned', true],
+ ['SQL Server outbox transactions and durable stores', 'ADO.NET/Dapper enlistment, atomic consumer inbox, fenced claims and unordered commit dispatch implemented; recovery and ordered workers planned', true],
['MySQL store, transactions and direct dispatch', 'Implemented ADO.NET/Dapper, atomic consumer inbox and unordered sends; ordered/recovery planned', true],
['EF Core transaction enlistment for PostgreSQL', 'Implemented enqueue path', true],
['PostgreSQL ADO.NET and Dapper transactions', 'Implemented enqueue path', true],
From b1f2a197c84e1e4bd8b65125c5f148081fcc1a30 Mon Sep 17 00:00:00 2001
From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com>
Date: Tue, 10 Nov 2026 04:45:08 +0000
Subject: [PATCH 2/4] Establish receiver readiness before outage conformance
for #332
---
src/Relayer.Testing/TransportConformanceSuite.cs | 4 ++++
website/docs/transports/conformance.md | 2 +-
2 files changed, 5 insertions(+), 1 deletion(-)
diff --git a/src/Relayer.Testing/TransportConformanceSuite.cs b/src/Relayer.Testing/TransportConformanceSuite.cs
index 87f4053b4..6b122fee7 100644
--- a/src/Relayer.Testing/TransportConformanceSuite.cs
+++ b/src/Relayer.Testing/TransportConformanceSuite.cs
@@ -316,6 +316,10 @@ await Send(1, key: fixture.Transport.GetCapabilities(fixture.Destination).Ordere
CheckBody(await Next().ConfigureAwait(false), 0);
await Stop().ConfigureAwait(false);
await Start().ConfigureAwait(false);
+ // Native Start may return before its stream is established. Observe a
+ // delivery after restart before testing an established connection outage.
+ await Send(0).ConfigureAwait(false);
+ CheckBody(await Next().ConfigureAwait(false), 0);
progress.Phase = "broker disconnect";
await fixture.DisconnectAsync(token).ConfigureAwait(false);
progress.Phase = "outage sends";
diff --git a/website/docs/transports/conformance.md b/website/docs/transports/conformance.md
index 8a1731335..a1cd3e305 100644
--- a/website/docs/transports/conformance.md
+++ b/website/docs/transports/conformance.md
@@ -82,6 +82,6 @@ Shared outbox shutdown contracts separately validate claims, database disposal a
Opt into `SendDuringOutage` by supplying `ITransportConformanceFixture.OutageSendTimeout` and, when needed, `IsExpectedOutageFailure` for native transient connectivity or deadline exceptions. Other exceptions fail the contract; caller/scenario cancellation is never treated as a successful outage. Fixtures without this fault-injection contract return an explicit skip. Kafka, Service Bus and Google Pub/Sub run this case against their broker or emulator; adapters whose receive paths remain planned do not claim this coverage.
-The fixture must return from `DisconnectAsync` only after connectivity is interrupted. With consumers already started, the suite attempts three concurrent sends and passes a deadline token to the adapter. Configure a native publish/retry deadline as well when the native API cannot cancel admitted sends: the Pub/Sub fixture uses the native API client's publish expiration. An independent watchdog fails a send that ignores its budget. The suite then requests offline shutdown with a ten-second token and a fifteen-second watchdog, restores the broker, restarts consumers and sends a recovery marker.
+The fixture must return from `DisconnectAsync` only after connectivity is interrupted. After restarting consumers, the suite observes a successful round trip before disconnecting so the outage interrupts an established receiver rather than racing its initial connection. The suite then attempts three concurrent sends and passes a deadline token to the adapter. Configure a native publish/retry deadline as well when the native API cannot cancel admitted sends: the Pub/Sub fixture uses the native API client's publish expiration. An independent watchdog fails a send that ignores its budget. The suite then requests offline shutdown with a ten-second token and a fifteen-second watchdog, restores the broker, restarts consumers and sends a recovery marker.
Successful send acknowledgements must result in delivery after recovery. Failed or cancelled sends can still have been accepted by a broker, so their arrival and duplicate deliveries are allowed. The test does not retract messages, replace native retry policies, impose cross-message ordering, or reinterpret native acknowledgements.
From c103f7f5afec4c49ca57570c2027a5c54e4f614e Mon Sep 17 00:00:00 2001
From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com>
Date: Tue, 10 Nov 2026 04:51:35 +0000
Subject: [PATCH 3/4] Allow outage warm-up redelivery during recovery (#332)
---
.../TransportConformanceSuite.cs | 4 +--
.../OutageConformanceTests.cs | 29 ++++++++++++++++++-
website/docs/transports/conformance.md | 2 +-
3 files changed, 31 insertions(+), 4 deletions(-)
diff --git a/src/Relayer.Testing/TransportConformanceSuite.cs b/src/Relayer.Testing/TransportConformanceSuite.cs
index 6b122fee7..7e360146e 100644
--- a/src/Relayer.Testing/TransportConformanceSuite.cs
+++ b/src/Relayer.Testing/TransportConformanceSuite.cs
@@ -341,7 +341,7 @@ await Send(1, key: fixture.Transport.GetCapabilities(fixture.Destination).Ordere
await fixture.ReconnectAsync(token).ConfigureAwait(false);
await Start().ConfigureAwait(false);
await Send(4).ConfigureAwait(false);
- // A failed/cancelled native send may still arrive. Duplicates are legal;
+ // A failed/cancelled native send or unsettled warm-up may still arrive. Duplicates are legal;
// every successfully acknowledged send and the recovery marker must arrive.
var required = new HashSet { 4 };
for (var i = 0; i < acknowledged.Length; i++)
@@ -352,7 +352,7 @@ await Send(1, key: fixture.Transport.GetCapabilities(fixture.Destination).Ordere
using var document = JsonDocument.Parse(message.Body);
var value = document.RootElement.GetProperty("Value").GetInt32();
CheckBody(message, value);
- Require(value is >= 1 and <= 4, "Unexpected outage delivery body.");
+ Require(value is >= 0 and <= 4, "Unexpected outage delivery body.");
required.Remove(value);
}
}
diff --git a/tests/Relayer.Conformance.Tests/OutageConformanceTests.cs b/tests/Relayer.Conformance.Tests/OutageConformanceTests.cs
index 6ff6f7153..3e13d2559 100644
--- a/tests/Relayer.Conformance.Tests/OutageConformanceTests.cs
+++ b/tests/Relayer.Conformance.Tests/OutageConformanceTests.cs
@@ -15,6 +15,12 @@ public async Task Outage_accepts_acknowledgements_and_ambiguous_cancelled_delive
await Assert.That((await suite.RunAsync(TransportConformanceCase.SendDuringOutage)).Skipped).IsFalse();
}
+ [Test]
+ public async Task Outage_accepts_warmup_redelivery_before_recovery_marker()
+ {
+ await Assert.That((await Suite("warmup-redelivery").RunAsync(TransportConformanceCase.SendDuringOutage)).Skipped).IsFalse();
+ }
+
[Test]
[Arguments("unexpected", "outage sends")]
[Arguments("lost", "receive completion")]
@@ -43,6 +49,8 @@ private sealed class OutageFixture(MessageTracing tracing, string mode) : ITrans
private readonly InMemoryFixture _inner = new(tracing);
private bool _offline;
private int _outageSends;
+ private int _warmupSettlements;
+ private readonly TaskCompletionSource _warmupRedelivered = new(TaskCreationOptions.RunContinuationsAsynchronously);
public ITransport Transport => this;
public string Name => _inner.Transport.Name;
public string Destination => _inner.Destination;
@@ -53,7 +61,22 @@ private sealed class OutageFixture(MessageTracing tracing, string mode) : ITrans
public bool IsExpectedOutageFailure(Exception error) => error is IOException;
public TransportCapabilities GetCapabilities(string endpoint) => _inner.Transport.GetCapabilities(endpoint);
public void RegisterConsumer(Func> receive) => _inner.RegisterConsumer(receive);
- public ValueTask SettleAsync(InMemoryDelivery incoming, Disposition disposition, CancellationToken token) => _inner.SettleAsync(incoming, disposition, token);
+ public ValueTask SettleAsync(InMemoryDelivery incoming, Disposition disposition, CancellationToken token)
+ {
+ // Requeue exactly the post-restart warm-up. Handler observation precedes
+ // settlement, so its next delivery may already be queued when outage recovery starts.
+ if (mode == "warmup-redelivery" && incoming.Message.Body.Span.SequenceEqual("{\"Value\":0}"u8))
+ {
+ var settlement = Interlocked.Increment(ref _warmupSettlements);
+ if (settlement == 2)
+ {
+ incoming.Redeliver(TimeSpan.Zero);
+ return default;
+ }
+ if (settlement == 3) _warmupRedelivered.TrySetResult();
+ }
+ return _inner.SettleAsync(incoming, disposition, token);
+ }
public ValueTask ReadDeadLetterAsync(CancellationToken token) => _inner.ReadDeadLetterAsync(token);
public Task StartAsync(CancellationToken token) => _inner.Transport.StartAsync(token);
public Task StopAsync(CancellationToken token) => _inner.Transport.StopAsync(token);
@@ -76,6 +99,10 @@ public async ValueTask SendAsync(OutgoingMessage message, CancellationToken toke
return;
}
}
+ // Queue the redelivered warm-up before the recovery marker, regardless
+ // of the in-memory endpoint's partition scheduling.
+ if (mode == "warmup-redelivery" && !_offline && Volatile.Read(ref _outageSends) != 0)
+ await _warmupRedelivered.Task.WaitAsync(token);
await _inner.Transport.SendAsync(message, token);
}
public ValueTask SendBatchAsync(ReadOnlyMemory messages, CancellationToken token) => _inner.Transport.SendBatchAsync(messages, token);
diff --git a/website/docs/transports/conformance.md b/website/docs/transports/conformance.md
index a1cd3e305..e9067dc64 100644
--- a/website/docs/transports/conformance.md
+++ b/website/docs/transports/conformance.md
@@ -84,4 +84,4 @@ Opt into `SendDuringOutage` by supplying `ITransportConformanceFixture.OutageSen
The fixture must return from `DisconnectAsync` only after connectivity is interrupted. After restarting consumers, the suite observes a successful round trip before disconnecting so the outage interrupts an established receiver rather than racing its initial connection. The suite then attempts three concurrent sends and passes a deadline token to the adapter. Configure a native publish/retry deadline as well when the native API cannot cancel admitted sends: the Pub/Sub fixture uses the native API client's publish expiration. An independent watchdog fails a send that ignores its budget. The suite then requests offline shutdown with a ten-second token and a fifteen-second watchdog, restores the broker, restarts consumers and sends a recovery marker.
-Successful send acknowledgements must result in delivery after recovery. Failed or cancelled sends can still have been accepted by a broker, so their arrival and duplicate deliveries are allowed. The test does not retract messages, replace native retry policies, impose cross-message ordering, or reinterpret native acknowledgements.
+Successful send acknowledgements must result in delivery after recovery. Failed or cancelled sends can still have been accepted by a broker, so their arrival and duplicate deliveries are allowed. The post-restart warm-up may also redeliver during recovery because observing its handler does not prove that native settlement finished before disconnect. The test does not retract messages, replace native retry policies, impose cross-message ordering, or reinterpret native acknowledgements.
From 80283d7288935d5b49fd561d1db6f93fe797e229 Mon Sep 17 00:00:00 2001
From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com>
Date: Tue, 10 Nov 2026 04:57:32 +0000
Subject: [PATCH 4/4] Fix SQL Server inbox deduplication under NOCOUNT (#332)
---
.../SqlServerConsumerBenchmarks.cs | 4 ++--
.../SqlServerConsumerExtensions.cs | 5 ++--
.../InboxTests.cs | 23 +++++++++++++++++++
website/docs/reference/sqlserver-store.md | 1 +
4 files changed, 29 insertions(+), 4 deletions(-)
diff --git a/benchmarks/Relayer.Benchmarks/SqlServerConsumerBenchmarks.cs b/benchmarks/Relayer.Benchmarks/SqlServerConsumerBenchmarks.cs
index 45f92947f..00f7397a9 100644
--- a/benchmarks/Relayer.Benchmarks/SqlServerConsumerBenchmarks.cs
+++ b/benchmarks/Relayer.Benchmarks/SqlServerConsumerBenchmarks.cs
@@ -29,7 +29,7 @@ public async Task Setup()
_connection = Environment.GetEnvironmentVariable("RELAYER_SQLSERVER_BENCHMARK_CONNECTION")
?? throw new InvalidOperationException("Set RELAYER_SQLSERVER_BENCHMARK_CONNECTION to an isolated SQL Server database.");
_table = $"[dbo].[{_options.TablePrefix}inbox]";
- _insert = $"INSERT INTO {_table} (consumer, message_id) SELECT @consumer, @id WHERE NOT EXISTS (SELECT 1 FROM {_table} WITH (UPDLOCK, HOLDLOCK) WHERE consumer = @consumer AND message_id = @id)";
+ _insert = $"INSERT INTO {_table} (consumer, message_id) SELECT @consumer, @id WHERE NOT EXISTS (SELECT 1 FROM {_table} WITH (UPDLOCK, HOLDLOCK) WHERE consumer = @consumer AND message_id = @id); SELECT @@ROWCOUNT";
_id = Guid.CreateVersion7().ToString("D");
var services = new ServiceCollection();
services.AddRelayerSqlServerOutbox(_options);
@@ -63,7 +63,7 @@ public async Task NativeInbox()
await using var command = new SqlCommand(_insert, connection, transaction);
command.Parameters.Add(new SqlParameter("@consumer", System.Data.SqlDbType.NVarChar, 256) { Value = "benchmark" });
command.Parameters.Add(new SqlParameter("@id", System.Data.SqlDbType.UniqueIdentifier) { Value = Guid.Parse(_id) });
- await command.ExecuteNonQueryAsync();
+ _ = (int)(await command.ExecuteScalarAsync())!;
await transaction.CommitAsync();
}
diff --git a/src/Relayer.Outbox.SqlServer/SqlServerConsumerExtensions.cs b/src/Relayer.Outbox.SqlServer/SqlServerConsumerExtensions.cs
index 83b5210d8..44a7bbcc9 100644
--- a/src/Relayer.Outbox.SqlServer/SqlServerConsumerExtensions.cs
+++ b/src/Relayer.Outbox.SqlServer/SqlServerConsumerExtensions.cs
@@ -33,7 +33,7 @@ public static ConsumePipelineBuilder SqlServer(this ConsumePipelineBuilder build
var outbox = services.GetRequiredService();
var options = services.GetRequiredService>().Value;
var table = SqlServerOutboxSchema.InboxTable(options);
- var insert = inbox ? $"INSERT INTO {table} (consumer, message_id) SELECT @consumer, @id WHERE NOT EXISTS (SELECT 1 FROM {table} WITH (UPDLOCK, HOLDLOCK) WHERE consumer = @consumer AND message_id = @id)" : null;
+ var insert = inbox ? $"INSERT INTO {table} (consumer, message_id) SELECT @consumer, @id WHERE NOT EXISTS (SELECT 1 FROM {table} WITH (UPDLOCK, HOLDLOCK) WHERE consumer = @consumer AND message_id = @id); SELECT @@ROWCOUNT" : null;
return new Boundary(consumer, connectionString, outbox.Table, insert, services.GetRequiredService());
});
}
@@ -71,7 +71,8 @@ public async ValueTask InvokeAsync(MessageContext context, ConsumeDelegate next)
idParameter.DbType = DbType.Guid;
idParameter.Value = id;
command.Parameters.Add(idParameter);
- if (await command.ExecuteNonQueryAsync(cancellation).ConfigureAwait(false) == 0)
+ // Explicit SQL result remains available when the session suppresses affected-row tokens with NOCOUNT.
+ if ((int)(await command.ExecuteScalarAsync(cancellation).ConfigureAwait(false))! == 0)
{
RequestCompletion(context);
transaction.ConsumerOwned = false;
diff --git a/tests/Relayer.Outbox.SqlServer.Tests/InboxTests.cs b/tests/Relayer.Outbox.SqlServer.Tests/InboxTests.cs
index aec35d399..fdcc7cbec 100644
--- a/tests/Relayer.Outbox.SqlServer.Tests/InboxTests.cs
+++ b/tests/Relayer.Outbox.SqlServer.Tests/InboxTests.cs
@@ -34,6 +34,29 @@ public async Task Inbox_is_opt_in()
await Assert.That(await database.ReadStateAsync()).IsEqualTo(new DurableState(2, 0, 2));
}
+ [Test]
+ public async Task Inbox_deduplicates_when_connections_inherit_nocount()
+ {
+ // Server user options affect every new session: use an owned server, isolated from parallel tests.
+ await using var isolated = new SqlServerFixture();
+ await isolated.InitializeAsync();
+ await using var database = new Database(isolated.ConnectionString);
+ await database.Start();
+ await database.Execute("EXEC sp_configure 'user options', 512; RECONFIGURE");
+ using (var pool = new SqlConnection(isolated.ConnectionString)) SqlConnection.ClearPool(pool);
+ await using (var connection = new SqlConnection(isolated.ConnectionString))
+ {
+ await connection.OpenAsync();
+ await Assert.That(await connection.ExecuteScalarAsync("SELECT @@OPTIONS & 512")).IsEqualTo(512);
+ }
+ await using var consumer = new Consumer(database, "orders");
+ var id = Guid.CreateVersion7();
+ await consumer.DeliverAsync(id);
+ await consumer.DeliverAsync(id);
+ await Assert.That(consumer.Invocations).IsEqualTo(1);
+ await Assert.That(await database.ReadStateAsync()).IsEqualTo(new DurableState(1, 1, 1));
+ }
+
[Test]
public async Task Consumer_identity_is_case_sensitive()
{
diff --git a/website/docs/reference/sqlserver-store.md b/website/docs/reference/sqlserver-store.md
index 7aae31399..f3b827803 100644
--- a/website/docs/reference/sqlserver-store.md
+++ b/website/docs/reference/sqlserver-store.md
@@ -126,6 +126,7 @@ Deduplication requires the original nonempty UUIDv7 message ID and keys it by co
The boundary opens one native read-committed transaction. SQL Server's `UPDLOCK, HOLDLOCK` key-range
locks and primary-key uniqueness serialize competing deliveries of the same identity. A committed key
skips handling and increments `relayer.inbox.duplicates`; rollback permits redelivery to run the handler.
+Duplicate detection uses an explicit SQL result and works when connections inherit `SET NOCOUNT ON`.
Business writes through `CurrentTransaction.Connection`, inbox identity and outgoing rows commit
atomically before broker settlement. An acknowledgement failure can redeliver committed work safely.
Handler failures, cancellation and requested retry/dead-letter outcomes roll back before existing failure