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
29 changes: 28 additions & 1 deletion benchmarks/Relayer.Benchmarks/OutboxEnlistmentBenchmarks.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public void Setup()
];
_record = new(Guid.CreateVersion7(), "events", "benchmark.order;v=1",
new OutgoingMessage("orders", new byte[BodySize], headers, new WireString("customer-42")), DateTimeOffset.UtcNow);
_state.Add(_record);
_state.Add(_record, 1);
_state.Clear();
}

Expand All @@ -63,3 +63,30 @@ public void Cleanup()
_provider.Dispose();
}
}

/// <summary>Measures reusable row ordering when EF contexts interleave sends in one transaction.</summary>
[MemoryDiagnoser]
public class SharedTransactionSendOrderBenchmarks
{
private BufferedOutboxMessage[] _rows = null!;

[Params(2, 32, 256)]
public int Count { get; set; }

[GlobalSetup]
public void Setup()
{
_rows = new BufferedOutboxMessage[Count];
for (var i = 0; i < Count; i++) _rows[i] = new();
OrderInterleavedRows();
}

[Benchmark]
public long OrderInterleavedRows()
{
// Two contexts each append in send order; concatenating them groups even and odd positions.
for (var i = 0; i < Count; i++) _rows[i].EnqueueOrder = i < Count / 2 ? i * 2 : (i - Count / 2) * 2 + 1;
EntityFrameworkCoreOutbox.SortSendOrder(_rows);
return _rows[^1].EnqueueOrder;
}
}
12 changes: 6 additions & 6 deletions docs/decisions.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ To change a decision, add a new entry that supersedes it rather than editing his
| [D47](#d47-sql-server-outbox-transactions-reuse-native-bulk-copy) | SQL Server outbox transactions reuse native bulk copy | Accepted |
| [D48](#d48-mysql-enqueue-owns-native-transactions-and-reuses-mysqlbatch) | MySQL enqueue owns native transactions and reuses MySqlBatch | Accepted |
| [D49](#d49-sql-server-commit-dispatch-reuses-native-rpc-batches) | SQL Server commit dispatch reuses native RPC batches | Accepted |
| [D50](#d50-ordered-lanes-follow-a-database-assigned-insert-sequence) | Ordered lanes follow a database-assigned insert sequence | Proposed |
| [D50](#d50-ordered-lanes-follow-a-database-assigned-insert-sequence) | Ordered lanes follow a database-assigned insert sequence | Accepted |
| [D51](#d51-the-ef-core-consumer-boundary-takes-an-isolation-level-and-replays-conflicts) | The EF Core consumer boundary takes an isolation level and replays conflicts | Proposed |
| [D52](#d52-allocations-a-native-api-requires-count-as-native-client-cost) | Allocations a native API requires count as native-client cost | Accepted |

Expand Down Expand Up @@ -641,7 +641,7 @@ allocations without weakening that boundary. Native execution, materialization a
outside the managed command-binding benchmark.

**Consequences.** Database failure or uncertain completion rolls back the batch, so accepted sends can replay.
Ordering describes ascending visible UUIDs, not concurrent writers' commit order. When a database connection
Ordering follows the database-assigned insert sequence among visible rows (D50), not concurrent writers' commit order. When a database connection
fails while a native request is in flight, that request can arrive late: neither cancellation nor the lease can
retract it. Native ordering semantics and the at-least-once contract remain unchanged. Strict fencing of native
requests requires broker support and is not emulated. Idempotent consumers remain necessary.
Expand Down Expand Up @@ -984,7 +984,7 @@ benchmarks isolate Relayer's reusable copy/swap/group work; database and native

## D50. Ordered lanes follow a database-assigned insert sequence

**Status.** Proposed; not implemented. Tracked by [#353](https://github.com/thomhurst/Relayer/issues/353).
**Status.** Accepted. Implemented for PostgreSQL; SQL Server and MySQL ordered dispatch must adopt the same rule in #330 and #344.

**Context.** D34 reads each lane in ascending `id` order. The `id` is a UUIDv7 created on the application
host when the message is sent, while its row is inserted at flush, immediately before commit (D31, D32).
Expand All @@ -995,8 +995,8 @@ only concurrent writers from its ordering guarantee; these transactions are not

**Decision.** Refine D34's read order while retaining its lane leases, locks, deadlines and fencing.
- The outbox table gains `seq`, a database-assigned identity value set when the row is inserted.
- Ordered lanes read and index pending rows by `(lane, seq)`. The parked-key anti-join compares `seq`.
- One transaction's rows are inserted in send order, so their `seq` values keep that order.
- Ordered lanes read and index pending rows by `(lane, seq)`. The parked-key anti-join compares `seq`. Unordered pending rows keep a partial UUID index and their existing read/recovery cursors.
- One transaction's rows are inserted in send order, so their `seq` values keep that order. PostgreSQL uses `UNNEST WITH ORDINALITY ORDER BY position`; shared EF contexts merge their reusable rows by a scope-local enqueue position before insertion.
- `id` remains the stable message identity for the inbox, native message IDs and fenced claims.
- Other database stores adopt the same rule with their native identity or sequence feature.

Expand All @@ -1006,7 +1006,7 @@ their `seq` values also follow commit order. A sequence is non-transactional: it
business transaction can wait on, and it cannot raise a serialization failure. Transactions that are
genuinely concurrent still have no defined order, and a row committed late can still be dispatched after
a higher `seq`; idempotent, version-guarded consumers remain necessary. Existing tables need an explicit
SQL migration (D30). Identity values can have gaps.
SQL migration (D30). The upgrade preserves existing rows' former UUID order because historical insertion order is unavailable; it must run with writers and dispatchers stopped, in one application-owned transaction. Identity values can have gaps; keep the sequence's default cache of one and do not reset it.

**Alternatives rejected.**
- A per-key advisory lock held from flush to commit gives strict commit order, but makes same-key writers queue
Expand Down
11 changes: 7 additions & 4 deletions docs/design.md
Original file line number Diff line number Diff line change
Expand Up @@ -451,7 +451,7 @@ The outbox is the area where every existing library has had correctness bugs, so

- A message is written in the **same database transaction** as your business data. It is dispatched if and only if that transaction commits.
- Delivery is at-least-once. The message ID (UUIDv7) is stable across retries and dispatches, so the consumer-side inbox deduplicates.
- Ordering is preserved per ordering key when the route declares it (Kafka key, ASB session, SQS FIFO message group). Lanes currently follow send-time UUIDv7 order, so instances with different clocks can reorder sequential commits; D50 proposes a database-assigned insert sequence ([#353](https://github.com/thomhurst/Relayer/issues/353)).
- Ordering is preserved per ordering key when the route declares it (Kafka key, ASB session, SQS FIFO message group). Lanes follow a database-assigned insert sequence (D50), preserving sequential transactions' commit order independently of host clocks. Genuinely concurrent transactions have no defined order.
- A poison outbox row never blocks unrelated messages.
- The design is safe with any number of instances. There is no double dispatch under normal operation, no cleanup race between instances, and no per-replica background-job storms.

Expand All @@ -466,6 +466,7 @@ The outbox is the area where every existing library has had correctness bugs, so
```
relayer_outbox
id uuid (v7) primary key
seq bigint database-assigned insert identity (outbox only)
lane integer hash(ordering_key) % lanes, or null when unordered
ordering_key text nullable
transport text
Expand All @@ -482,7 +483,9 @@ relayer_outbox
claim_token uuid nullable, unique per dispatch attempt
claim_expires_at timestamptz nullable

index (lane, id) where status is pending -- partial/filtered where the database supports it
index (lane, seq) where status is pending and lane is not null -- partial/filtered where the database supports it
index (id) where status is pending and lane is null
index (lane, ordering_key, seq) where status is parked
index (deliver_at) where deliver_at is not null

relayer_leases
Expand All @@ -492,7 +495,7 @@ relayer_leases
```

PostgreSQL ships one embedded SQL creation script, exposed by the database CLI and an application-owned
EF Core migration operation (D30). Other database scripts remain planned. Indexes are created by default
EF Core migration operation (D30). D50 adds an explicit insert-sequence SQL upgrade for existing PostgreSQL tables; creation does not upgrade them. Existing rows keep their former UUID order because historical insertion order cannot be recovered. Other database stores' ordered workers adopt native identity/sequence ordering when implemented. Indexes are created by default
(CAP #1599). Tables can be prefixed and given a schema (NSB.Persistence.Sql #2093). See
[schema deployment and migration usage](../website/docs/reference/postgres-schema.md).

Expand All @@ -513,7 +516,7 @@ live token, so a stale dispatcher cannot mutate a reclaimed row. PostgreSQL sche
There are two paths, each chosen per message based on whether its route is ordered:

1. **Unordered messages — direct dispatch.** After commit, the instance that committed dispatches immediately, in the background, without waiting for a poll. It claims an eligible row with a conditional update that sets a fresh claim token and expiry only when no live claim exists. Completion, renewal and failure updates require that token and an unexpired claim. This prevents concurrent claims and stale database mutations; a crash or a broker send that outlives its claim can still duplicate delivery, as allowed by the at-least-once guarantee. Latency equals the broker round trip (fixes the latency of polling designs, SlimMessageBus #275).
2. **Ordered messages — lane leases.** Rows are hashed into N lanes (default 32). Instances lease lanes through `relayer_leases` with heartbeats and fair-share rebalancing as instances join and leave. A lane owner reads its lane in `id` order with a simple indexed range scan. There are no `SKIP LOCKED` scans across the whole table, and connected owners do not overlap. D34 specifies transaction locks, deadlines and the at-least-once/native-send failure boundary; ordering follows visible UUID order rather than concurrent transaction commit order. D50 (proposed) replaces UUID order with an insert sequence. Each ordered worker retains at most 256 successful endpoint capability lookups with FIFO eviction. An evicted endpoint is resolved and validated again before its next native send; failed lookups never displace valid entries.
2. **Ordered messages — lane leases.** Rows are hashed into N lanes (default 32). Instances lease lanes through `relayer_leases` with heartbeats and fair-share rebalancing as instances join and leave. A lane owner reads its lane in database-assigned `seq` order with a simple indexed range scan. There are no `SKIP LOCKED` scans across the whole table, and connected owners do not overlap. D34 specifies transaction locks, deadlines and the at-least-once/native-send failure boundary; D50 preserves sequential commit order using insertion sequence, while genuinely concurrent transactions have no defined order. Each ordered worker retains at most 256 successful endpoint capability lookups with FIFO eviction. An evicted endpoint is resolved and validated again before its next native send; failed lookups never displace valid entries.

The implemented PostgreSQL direct path transfers reusable buffers after EF commit to an explicitly named
hosted worker (D33). It claims each native group of due unordered rows with one conditional statement,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Data.Common;
using System.Runtime.InteropServices;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using Relayer.Outbox.PostgreSql;
Expand All @@ -12,6 +13,9 @@ internal sealed class EntityFrameworkCoreOutbox(bool supportsScheduling = false,
private readonly List<OutboxContext> _contexts = [];
private readonly PostgreSqlOutboxBatch _batch = new();
private Selection? _selection;
private long _enqueueOrder;
private readonly List<BufferedOutboxMessage> _sharedRows = [];
private static readonly Comparison<BufferedOutboxMessage> SendOrder = static (left, right) => left.EnqueueOrder.CompareTo(right.EnqueueOrder);

private OutboxConfiguration? _activeConfiguration;
public bool SupportsScheduling => _activeConfiguration?.SupportsScheduling ?? supportsScheduling;
Expand All @@ -32,7 +36,7 @@ public ValueTask EnlistAsync(OutboxRecord record, CancellationToken cancellation
{
cancellationToken.ThrowIfCancellationRequested();
var target = Target() ?? throw new InvalidOperationException("Select an EF Core outbox context or begin an EF Core transaction before sending.");
target.Add(record);
target.Add(record, checked(++_enqueueOrder));
return ValueTask.CompletedTask;
}

Expand Down Expand Up @@ -120,6 +124,7 @@ internal void Invalidate(DbTransaction transaction)
{
OutboxConfiguration? configuration = null;
var count = 0;
var participants = 0;
foreach (var state in _contexts)
{
if (!ReferenceEquals(state.Transaction, transaction)) continue;
Expand All @@ -128,15 +133,31 @@ internal void Invalidate(DbTransaction transaction)
throw new InvalidOperationException("DbContexts sharing a transaction must use identical outbox schema, prefix and lane settings.");
configuration = state.Configuration;
count = checked(count + state.Count);
if (state.Count != 0) participants++;
}
if (count == 0) return null;
_batch.Prepare(transaction, configuration!.InsertSql);
// A single context already buffers in send order. Shared transactions can interleave
// sends across contexts; merge their reusable rows before the database assigns seq.
foreach (var state in _contexts)
if (ReferenceEquals(state.Transaction, transaction))
for (var i = 0; i < state.Count; i++) _batch.Add(state.Rows[i]);
for (var i = 0; i < state.Count; i++)
if (participants == 1) _batch.Add(state.Rows[i]);
else _sharedRows.Add(state.Rows[i]);
if (participants > 1)
{
try
{
SortSendOrder(CollectionsMarshal.AsSpan(_sharedRows));
for (var i = 0; i < _sharedRows.Count; i++) _batch.Add(_sharedRows[i]);
}
finally { _sharedRows.Clear(); }
}
return _batch;
}

internal static void SortSendOrder(Span<BufferedOutboxMessage> rows) => rows.Sort(SendOrder);

public void Dispose()
{
foreach (var state in _contexts) state.Clear();
Expand Down Expand Up @@ -204,7 +225,7 @@ internal void EnsureTransactionAvailable()
throw new InvalidOperationException("This DbContext no longer participates in its live shared transaction. Complete that transaction before reusing the context.");
}

internal void Add(OutboxRecord record)
internal void Add(OutboxRecord record, long enqueueOrder)
{
if (Failed) throw new InvalidOperationException("Roll back the failed outbox transaction before sending again.");
if (record.Message.DeliverAt is not null && !(record.Message.OrderingKey is not null
Expand All @@ -213,6 +234,7 @@ internal void Add(OutboxRecord record)
BufferedOutboxMessage.Validate(record);
if (Count == Rows.Count) Rows.Add(new());
Rows[Count].Copy(record, Configuration.Lanes);
Rows[Count].EnqueueOrder = enqueueOrder;
Count++;
}

Expand Down
15 changes: 15 additions & 0 deletions src/Relayer.Outbox.PostgreSql/InsertSequenceMigration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
-- Run once, in one transaction, with application writers and dispatchers stopped.
-- Preserve the old UUID order for existing rows; historical insert order is unavailable.
LOCK TABLE {{schema}}.{{outbox}} IN ACCESS EXCLUSIVE MODE;
ALTER TABLE {{schema}}.{{outbox}} ADD COLUMN seq bigint;
WITH numbered AS (SELECT id, row_number() OVER (ORDER BY id) AS position FROM {{schema}}.{{outbox}})
UPDATE {{schema}}.{{outbox}} AS target SET seq = numbered.position FROM numbered WHERE target.id = numbered.id;
ALTER TABLE {{schema}}.{{outbox}} ALTER COLUMN seq SET NOT NULL;
ALTER TABLE {{schema}}.{{outbox}} ALTER COLUMN seq ADD GENERATED ALWAYS AS IDENTITY;
SELECT setval(pg_get_serial_sequence({{outbox_literal}}, 'seq'), COALESCE(max(seq), 1), count(*) > 0)
FROM {{schema}}.{{outbox}};
DROP INDEX {{schema}}.{{outbox_pending_idx}};
DROP INDEX {{schema}}.{{outbox_parked_idx}};
CREATE INDEX {{outbox_pending_idx}} ON {{schema}}.{{outbox}} (lane, seq) WHERE status = 'pending' AND lane IS NOT NULL;
CREATE INDEX {{outbox_unordered_idx}} ON {{schema}}.{{outbox}} (id) WHERE status = 'pending' AND lane IS NULL;
CREATE INDEX {{outbox_parked_idx}} ON {{schema}}.{{outbox}} (lane, ordering_key, seq) WHERE status = 'parked';
4 changes: 2 additions & 2 deletions src/Relayer.Outbox.PostgreSql/PostgreSqlOrderedLane.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@ internal PostgreSqlOrderedLane(NpgsqlDataSource source, PostgreSqlOutboxOptions
var table = PostgreSqlOutboxSchema.QuoteIdentifier(options.Schema ?? "public") + "." +
PostgreSqlOutboxSchema.QuoteIdentifier(options.TablePrefix + "outbox");
// Read scheduled and claimed heads too. Parked keys are excluded without parking the rest of the lane.
_read = $"SELECT id, transport, message_type, destination, body, headers, ordering_key, deliver_at, created_at, lane, attempts, last_error, tenant_id FROM {table} AS pending WHERE lane = @lane AND status = 'pending' AND NOT EXISTS (SELECT 1 FROM {table} AS parked WHERE parked.lane = @lane AND parked.status = 'parked' AND parked.ordering_key = pending.ordering_key AND parked.id < pending.id) ORDER BY id LIMIT @limit";
_read = $"SELECT id, transport, message_type, destination, body, headers, ordering_key, deliver_at, created_at, lane, attempts, last_error, tenant_id FROM {table} AS pending WHERE lane = @lane AND status = 'pending' AND NOT EXISTS (SELECT 1 FROM {table} AS parked WHERE parked.lane = @lane AND parked.status = 'parked' AND parked.ordering_key = pending.ordering_key AND parked.seq < pending.seq) ORDER BY seq LIMIT @limit";
// Probe only each assigned lane's first non-parked head. Re-read under the lease lock before sending.
_ready = $"SELECT requested.lane FROM unnest(@lanes) AS requested(lane) CROSS JOIN LATERAL (SELECT deliver_at, claim_expires_at FROM {table} AS pending WHERE pending.lane = requested.lane AND status = 'pending' AND NOT EXISTS (SELECT 1 FROM {table} AS parked WHERE parked.lane = requested.lane AND parked.status = 'parked' AND parked.ordering_key = pending.ordering_key AND parked.id < pending.id) ORDER BY id LIMIT 1) AS head WHERE (head.deliver_at IS NULL OR head.deliver_at <= clock_timestamp()) AND (head.claim_expires_at IS NULL OR head.claim_expires_at <= clock_timestamp())";
_ready = $"SELECT requested.lane FROM unnest(@lanes) AS requested(lane) CROSS JOIN LATERAL (SELECT deliver_at, claim_expires_at FROM {table} AS pending WHERE pending.lane = requested.lane AND status = 'pending' AND NOT EXISTS (SELECT 1 FROM {table} AS parked WHERE parked.lane = requested.lane AND parked.status = 'parked' AND parked.ordering_key = pending.ordering_key AND parked.seq < pending.seq) ORDER BY seq LIMIT 1) AS head WHERE (head.deliver_at IS NULL OR head.deliver_at <= clock_timestamp()) AND (head.claim_expires_at IS NULL OR head.claim_expires_at <= clock_timestamp())";
var fenced = "id = @id AND claim_token = @token AND claim_expires_at > clock_timestamp()";
_claim = CreateMutation($"UPDATE {table} SET claim_token = @token, claim_expires_at = clock_timestamp() + @duration WHERE id = @id AND status = 'pending' AND (deliver_at IS NULL OR deliver_at <= clock_timestamp()) AND (claim_expires_at IS NULL OR claim_expires_at <= clock_timestamp())");
_claim.Parameters.Add(new NpgsqlParameter<TimeSpan>("duration", NpgsqlDbType.Interval) { TypedValue = duration });
Expand Down
Loading
Loading