Skip to content
Closed
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
3 changes: 2 additions & 1 deletion src/Relayer.Outbox.PostgreSql/PostgreSqlOrderedDispatcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,8 @@ internal async ValueTask<int> DispatchLaneAsync(int lane, CancellationToken canc
if (action is not (FailureAction.Retry or FailureAction.DeadLetter))
throw new InvalidOperationException("The dispatch failure classifier returned an unknown action.");
var permanent = action == FailureAction.DeadLetter;
if (!await _lane.FailAsync(connection, transaction, claim, error.Message, cancellationToken, permanent, retryable: nativeSend).ConfigureAwait(false))
if (!await _lane.FailAsync(connection, transaction, claim, error.Message, cancellationToken, permanent, retryable: nativeSend,
local: preparedForSend && !nativeSend).ConfigureAwait(false))
throw new InvalidOperationException("Ordered outbox claim expired while recording a dispatch failure.", error);
poisoned = permanent || (!nativeSend && row.Attempts + 1 >= _options.MaxDispatchAttempts);
DispatchFailed(_logger, error);
Expand Down
7 changes: 6 additions & 1 deletion src/Relayer.Outbox.PostgreSql/PostgreSqlOrderedLane.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ internal sealed class PostgreSqlOrderedLane : IDisposable
private readonly NpgsqlCommand _complete;
private readonly NpgsqlCommand _retry;
private readonly NpgsqlCommand _fail;
private readonly NpgsqlCommand _failLocal;
private readonly NpgsqlCommand _failImmediately;

internal PostgreSqlOrderedLane(NpgsqlDataSource source, PostgreSqlOutboxOptions options, TimeSpan duration)
Expand Down Expand Up @@ -44,6 +45,8 @@ internal PostgreSqlOrderedLane(NpgsqlDataSource source, PostgreSqlOutboxOptions
PostgreSqlOutboxSchema.QuoteIdentifier(options.TablePrefix + "outbox_dead");
_fail = CreateMutation(PostgreSqlPoisonSql.Failure(table, dead, fenced, options.MaxDispatchAttempts));
_fail.Parameters.Add(new NpgsqlParameter<string>("error", NpgsqlDbType.Text));
_failLocal = CreateMutation(PostgreSqlPoisonSql.Failure(table, dead, fenced, options.MaxDispatchAttempts, "clock_timestamp()"));
_failLocal.Parameters.Add(new NpgsqlParameter<string>("error", NpgsqlDbType.Text));
_retry = CreateMutation(PostgreSqlPoisonSql.Retry(table, fenced, "clock_timestamp()"));
_retry.Parameters.Add(new NpgsqlParameter<string>("error", NpgsqlDbType.Text));
_failImmediately = CreateMutation(PostgreSqlPoisonSql.Failure(table, dead, fenced, 1));
Expand Down Expand Up @@ -83,7 +86,8 @@ internal ValueTask<bool> CompleteAsync(NpgsqlConnection connection, NpgsqlTransa
OutboxClaim claim, CancellationToken cancellationToken) => MutateAsync(connection, transaction, _complete, claim, null, cancellationToken);

internal ValueTask<bool> FailAsync(NpgsqlConnection connection, NpgsqlTransaction transaction,
OutboxClaim claim, string error, CancellationToken cancellationToken, bool permanent = false, bool retryable = false) => MutateAsync(connection, transaction, permanent ? _failImmediately : retryable ? _retry : _fail, claim, error, cancellationToken);
OutboxClaim claim, string error, CancellationToken cancellationToken, bool permanent = false, bool retryable = false, bool local = false) =>
MutateAsync(connection, transaction, permanent ? _failImmediately : retryable ? _retry : local ? _failLocal : _fail, claim, error, cancellationToken);

[RuntimeAsyncMethodGeneration(false)]
[AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder<>))]
Expand Down Expand Up @@ -129,6 +133,7 @@ public void Dispose()
_complete.Dispose();
_retry.Dispose();
_fail.Dispose();
_failLocal.Dispose();
_failImmediately.Dispose();
}
}
3 changes: 2 additions & 1 deletion src/Relayer.Outbox.PostgreSql/PostgreSqlOutboxStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,8 @@ public PostgreSqlOutboxStore(NpgsqlDataSource dataSource, PostgreSqlOutboxOption
// Internal dispatch follows the same database clock as maintenance and ordered lanes.
// Public explicit-time operations retain their caller-controlled clock contract.
var directFence = Fenced("clock_timestamp()");
_failDirect = PostgreSqlPoisonSql.Failure(table, dead, directFence, options.MaxDispatchAttempts);
// Direct dispatch counts failures only for local handlers; they back off like native retries.
_failDirect = PostgreSqlPoisonSql.Failure(table, dead, directFence, options.MaxDispatchAttempts, "clock_timestamp()");
_retryDirect = PostgreSqlPoisonSql.Retry(table, directFence, "clock_timestamp()");
_failDirectImmediately = PostgreSqlPoisonSql.Failure(table, dead, directFence, 1);
_count = $"SELECT count(*) FROM {table} WHERE {eligible}";
Expand Down
11 changes: 8 additions & 3 deletions src/Relayer.Outbox.PostgreSql/PostgreSqlPoisonSql.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,25 @@ internal static class PostgreSqlPoisonSql
internal static string Retry(string table, string fenced, string now) => $"""
WITH retried AS (
UPDATE {table} SET attempts = LEAST(attempts, 29) + 1, last_error = @error,
deliver_at = {now} + LEAST(300, power(2, LEAST(attempts, 9))) * interval '1 second',
deliver_at = {Backoff(now)},
claim_token = NULL, claim_expires_at = NULL
WHERE {fenced} RETURNING id
) SELECT CASE WHEN EXISTS (SELECT 1 FROM retried) THEN 1 ELSE 0 END
""";

internal static string Failure(string table, string dead, string fenced, int limit) => $"""
// One to 300 seconds, doubling per recorded attempt.
private static string Backoff(string now) => $"{now} + LEAST(300, power(2, LEAST(attempts, 9))) * interval '1 second'";

// Counted failures. With backoffFrom, a row that stays pending persists the same backoff as Retry,
// so local handler retries cannot run hot on any dispatch path before they exhaust the limit.
internal static string Failure(string table, string dead, string fenced, int limit, string? backoffFrom = null) => $"""
WITH exhausted AS (
DELETE FROM {table} WHERE {fenced} AND lane IS NULL AND attempts + 1 >= {limit}
RETURNING *
), failed AS (
UPDATE {table} SET attempts = attempts + 1, last_error = @error,
status = CASE WHEN lane IS NOT NULL AND attempts + 1 >= {limit} THEN 'parked' ELSE status END,
claim_token = NULL, claim_expires_at = NULL
{(backoffFrom is null ? "" : $"deliver_at = CASE WHEN attempts + 1 >= {limit} THEN deliver_at ELSE {Backoff(backoffFrom)} END, ")}claim_token = NULL, claim_expires_at = NULL
WHERE {fenced} AND (lane IS NOT NULL OR attempts + 1 < {limit}) RETURNING *
), copied AS (
INSERT INTO {dead} (id, lane, ordering_key, transport, destination, message_type, headers, body,
Expand Down
69 changes: 69 additions & 0 deletions tests/Relayer.Outbox.PostgreSql.Tests/LocalTransportTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,75 @@ public async Task Failed_business_changes_roll_back_and_poison_does_not_block_ot
await Assert.That((int)(await check.ExecuteScalarAsync())!).IsEqualTo(9);
}

[Test]
[Arguments("direct")]
[Arguments("recovery")]
[Arguments("ordered")]
public async Task Retry_failures_back_off_and_dead_letter_at_the_limit_on_every_dispatch_path(string path)
{
await using var database = server.CreateDatabase();
await database.StartAsync();
await using var source = NpgsqlDataSource.Create(database.ConnectionString);
await PostgreSqlOutboxStoreTests.CreateSchema(source);
await using (var command = source.CreateCommand("CREATE TABLE local_business (value integer PRIMARY KEY)")) await command.ExecuteNonQueryAsync();
var ordered = path == "ordered";
await using var provider = Provider(source, ordered, maxAttempts: 2, failureAction: FailureAction.Retry);
foreach (var starter in provider.GetServices<IHostedService>()) if (starter is not PostgreSqlDirectDispatcher) await starter.StartAsync(default);
var transport = provider.GetServices<ITransport>().Single();
await Enqueue(provider, source, new(-1), true);
// One ordered worker keeps the lane lease across both attempts.
using var lane = new PostgreSqlOrderedDispatcher(source, new() { Lanes = 1, MaxDispatchAttempts = 2 }, [transport], provider.GetRequiredService<ILogger<PostgreSqlOrderedDispatcher>>());

async Task DispatchAsync()
{
if (ordered)
{
await lane.DispatchLaneAsync(0, default);
return;
}
var store = new PostgreSqlOutboxStore(source, new() { MaxDispatchAttempts = 2 });
var rows = new OutboxRecord[1];
var count = await store.ReadPendingAsync(new(null, DateTimeOffset.UtcNow), rows, default);
await Assert.That(count).IsEqualTo(1);
if (path == "direct")
{
using var direct = new PostgreSqlDirectDispatcher(source, new() { MaxDispatchAttempts = 2 }, new(), [transport], provider.GetRequiredService<ILogger<PostgreSqlDirectDispatcher>>());
await direct.DispatchRecoveredAsync(rows.AsMemory(0, count), default);
return;
}
await using var connection = await source.OpenConnectionAsync();
await using var transaction = await connection.BeginTransactionAsync();
store.UseDispatchTransaction(connection, transaction);
using var recovery = new PostgreSqlDirectDispatcher(source, new() { MaxDispatchAttempts = 2 }, new(), [transport], provider.GetRequiredService<ILogger<PostgreSqlDirectDispatcher>>(), store);
await recovery.DispatchRecoveredAsync(rows.AsMemory(0, count), default, propagateDatabaseFailures: true);
await transaction.CommitAsync();
}

async Task<DateTime> DatabaseNow()
{
await using var now = source.CreateCommand("SELECT clock_timestamp()");
return (DateTime)(await now.ExecuteScalarAsync())!;
}

var before = await DatabaseNow();
await DispatchAsync();
var after = await DatabaseNow();
await using (var check = source.CreateCommand("SELECT attempts, deliver_at FROM relayer_outbox"))
await using (var reader = await check.ExecuteReaderAsync())
{
await Assert.That(await reader.ReadAsync()).IsTrue();
await Assert.That(reader.GetInt32(0)).IsEqualTo(1);
// The first retry is persisted one second after the failure, so no path retries the handler hot.
await Assert.That(reader.GetDateTime(1)).IsGreaterThan(before.AddSeconds(1)).And.IsLessThan(after.AddSeconds(1));
}
await Assert.That(await Count(source, "relayer_outbox_dead")).IsEqualTo(0L);

await using (var due = source.CreateCommand("UPDATE relayer_outbox SET deliver_at = clock_timestamp() - interval '1 second'")) await due.ExecuteNonQueryAsync();
await DispatchAsync();
await Assert.That(await Count(source, "relayer_outbox_dead")).IsEqualTo(1L);
await Assert.That(await Count(source, "local_business")).IsEqualTo(0L);
}

[Test]
public async Task Killed_consumer_rolls_back_business_work_and_another_process_completes_once()
{
Expand Down
2 changes: 1 addition & 1 deletion website/docs/reference/direct-dispatch.md
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ queue and drains it within the host's shutdown deadline; cancellation leaves unf
[Ordered lane dispatch](ordered-dispatch.md) handles rows with ordering keys separately.
[Leased recovery and cleanup](postgres-maintenance.md) handles due unordered rows left by failure,
overflow, cancellation, process death or a future `DeliverAt`. Register it explicitly alongside this worker.
Local-handler retries retain the `storeOptions.MaxDispatchAttempts` poison budget (default 10).
Local-handler retries persist the same backoff and retain the `storeOptions.MaxDispatchAttempts` poison budget (default 10).
This worker handles immediate commit-triggered sends; maintenance revisits native retries when their
persisted deadline becomes due.

Expand Down
2 changes: 1 addition & 1 deletion website/docs/reference/postgres-maintenance.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ Choose `ClaimDuration` longer than expected broker and database latency and keep
Delivery is at-least-once. A crash after native acceptance and before deletion replays the same identity.
Database fencing cannot retract an accepted native request, and connection loss or a native send that outlives
its claim can still duplicate delivery. Connected leadership does not provide broker-side fencing.
Native-send failures use [durable backoff and failure classification](postgres-store.md#poison-rows-and-key-release). Local-handler failures classified as `Retry` retain the `MaxDispatchAttempts` budget (default 10), then atomically move to dead storage.
Native-send failures use [durable backoff and failure classification](postgres-store.md#poison-rows-and-key-release). Local-handler failures classified as `Retry` persist the same backoff and retain the `MaxDispatchAttempts` budget (default 10), then atomically move to dead storage.

## Retention

Expand Down
2 changes: 1 addition & 1 deletion website/docs/reference/postgres-store.md
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ claims remain for recovery. Successful batches retain the existing batch send an

Local-handler failures classified as `Retry`, ordered preparation errors (missing transport, key or ordering capability) and explicit low-level
`RecordFailureAsync` calls retain the positive `MaxDispatchAttempts` budget (default **10**).
Configure that limit consistently on store and worker options; classified retryable native sends never exhaust it. Local-handler retries dead-letter at the limit and park their ordered key.
Configure that limit consistently on store and worker options; classified retryable native sends never exhaust it. Local-handler retries also persist the same 1 second to 5 minute backoff in `deliver_at` on every dispatch path, then dead-letter at the limit and park their ordered key.
Broker success followed by database completion failure does not consume an attempt.

One fenced statement persists the final error and attempt count and copies the original identity,
Expand Down
2 changes: 1 addition & 1 deletion website/docs/transports/postgresql-local.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ Atomic completion covers only writes in that transaction and database. HTTP call

## Failures and capabilities

The shared consume pipeline runs generated handlers, deserialization, tracing and the registered `IFailureClassifier`. Retry failures persist exponential backoff (1 second to 5 minutes) and use recovery passes without exhausting a poison budget. Permanent failures use the same fenced poison transition immediately. Discard rolls back failed business changes before deletion. Configure `MaxDispatchAttempts` consistently on the store and workers. Inspect, redrive and purge with the existing [dead-letter manager](../reference/postgres-store.md#poison-rows-and-key-release).
The shared consume pipeline runs generated handlers, deserialization, tracing and the registered `IFailureClassifier`. A `Retry` failure counts against `MaxDispatchAttempts` and persists exponential backoff (1 second to 5 minutes) in `deliver_at`, whether commit-triggered dispatch, a recovery pass or an ordered lane ran the attempt. At the limit the row moves to dead storage, and an ordered row parks its key. Permanent failures use the same fenced poison transition immediately. Discard rolls back failed business changes before deletion. Configure `MaxDispatchAttempts` consistently on the store and workers. Inspect, redrive and purge with the existing [dead-letter manager](../reference/postgres-store.md#poison-rows-and-key-release).

Send and completion state pools grow to retain peak concurrent usage, including beyond their initial 16 send and 64 completion slots. After warm-up, higher concurrency reuses those states; native Npgsql and serializer allocations still apply. Retained send resources are disposed with the transport.

Expand Down
Loading