Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
106 changes: 106 additions & 0 deletions benchmarks/Relayer.Benchmarks/SqlServerConsumerBenchmarks.cs
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>Native inbox transaction versus scoped consumer boundary, including SqlClient I/O and allocations.</summary>
[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); SELECT @@ROWCOUNT";
_id = Guid.CreateVersion7().ToString("D");
var services = new ServiceCollection();
services.AddRelayerSqlServerOutbox(_options);
services.AddRelayer(r => { r.MessageTypes.Add<Probe>("benchmark.sql-consumer"); r.Handler<Handler>(); });
_provider = services.BuildServiceProvider();
_pipeline = new ConsumePipelineBuilder(_provider.GetRequiredService<IServiceScopeFactory>(),
_provider.GetRequiredService<MessageTypeRegistry>(), new Serializer(), static (_, error, _) => ValueTask.FromException(error))
.SqlServer("benchmark", _connection, inbox: true)
.Handler(_provider.GetRequiredService<HandlerRegistry>().GetHandler<Probe, Handler>()).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) });
_ = (int)(await command.ExecuteScalarAsync())!;
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<byte>.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<Probe>
{
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<TMessage>(ReadOnlySequence<byte> source) => (TMessage)(object)_probe;
public void Serialize<TMessage>(TMessage message, IBufferWriter<byte> destination) => throw new NotSupportedException();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
}
31 changes: 31 additions & 0 deletions docs/decisions.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |

---

Expand Down Expand Up @@ -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).
7 changes: 6 additions & 1 deletion docs/design.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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).
Expand Down
Loading
Loading