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
52 changes: 52 additions & 0 deletions docs/decisions.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ To change a decision, add a new entry that supersedes it rather than editing his
| [D70](#d70-mysql-send-failures-retain-durable-retry-eligibility) | MySQL send failures retain durable retry eligibility | Accepted |
| [D71](#d71-sql-server-outbox-send-failures-retain-durable-eligibility) | SQL Server outbox send failures retain durable eligibility | Accepted |
| [D72](#d72-handler-registration-belongs-to-the-consumer) | Handler registration belongs to the consumer | Accepted |
| [D73](#d73-postgresql-retryable-outbox-sends-retain-durable-eligibility) | PostgreSQL retryable outbox sends retain durable eligibility | Accepted |

---

Expand Down Expand Up @@ -1702,3 +1703,54 @@ classification. See [SQL Server recovery](https://relayer.tomlonghurst.dev/docs/
**Decision.** Generate `Handler<THandler>()` only for `IConsumerBuilder`. Remove the root builder overload and `AddHandlersFromThisAssembly()`. Applications explicitly select each handler inside its consumer callback. RLY003 points to that call. Source generation continues to discover contracts at compile time; it does not register discovered handlers automatically. Manual pipeline composers use descriptors registered by their consumer declaration.

**Consequences.** One application call selects dispatch and registers DI, preserving explicit topology, typed native options, AOT safety and existing handler lifetimes. Existing applications move builder-level registrations into consumer callbacks. Dispatch and native broker behavior are unchanged, with no additional steady-state work or allocation.

## D73. PostgreSQL retryable outbox sends retain durable eligibility

**Context.** Native sends already retry within their operation: Azure.Messaging.ServiceBus 7.21.0
[`ServiceBusRetryPolicy.RunOperation`](https://github.com/Azure/azure-sdk-for-net/blob/Azure.Messaging.ServiceBus_7.21.0/sdk/servicebus/Azure.Messaging.ServiceBus/src/Primitives/ServiceBusRetryPolicy.cs)
keeps its attempt count in memory and throws after exhaustion. Dekaf 1.27.0's
[`OutboxRelayService`](https://github.com/thomhurst/Dekaf/blob/v1.27.0/src/Dekaf.Outbox/OutboxRelayService.cs)
also backs off a failed head, but belongs to the separate Kafka-specific Dekaf.Outbox package and
tracks bucket backoff in memory. Neither can persist eligibility for Relayer's multi-transport
PostgreSQL rows across worker replacement. Existing dispatch used its poison budget for broker outages.

**Decision.** After a native send fails, reuse the fenced PostgreSQL mutation and `deliver_at`
column to persist exponential delays from one second to five minutes. Do not add native send
retry loops or replace broker retry policies. Retryable sends never enter the poison-budget
transition; their diagnostic attempt counter saturates at 30. Explicit permanent classifications
retain immediate poison handling, and discard completes the fenced row without a dead copy. Preparation failures and explicit low-level
RecordFailureAsync retain their existing attempt budget. Ordered heads retain their existing
due-time lane barrier. No new schema or broker scheduling feature is introduced.

**Consequences.** PostgreSQL outages recover automatically without manual redrive. Native send
failures reuse the registered `IFailureClassifier` in a fresh DI scope, with the original row identity,
wire type, headers, attempt and tenant context. Local consume failures retain their existing classified
action. The PostgreSQL package does not reference native broker packages: applications can use native
signals such as Azure.Messaging.ServiceBus 7.21.0's
[`ServiceBusException.IsTransient`](https://github.com/Azure/azure-sdk-for-net/blob/4e4c19469fe598b9f28a73d065514106985e7560/sdk/servicebus/Azure.Messaging.ServiceBus/src/Primitives/ServiceBusException.cs),
verified from the pinned package's checksum-matched source. Unclassified native failures still use the
existing default classifier, so non-contract errors retry indefinitely until repaired or covered by a
permanent rule. `MaxDispatchAttempts` still bounds local-handler `Retry` failures, including ordered poison barriers.
It does not bound native-send `Retry`; applications must configure native
permanent-error rules and monitor pending rows. A retrying ordered head blocks its key until recovery.

Existing native batch behavior was checked in ServiceBusSendTransport, KafkaProducerTransport,
SqsSendTransport and RabbitMqNativeTransport.Send. SQS exposes partial failures in its native response;
other native batches can reject before sending or partially send. `ITransport.SendBatchAsync` exposes
one exception rather than a portable per-row receipt. After failure, use each existing native `SendAsync`
once under its original live claim to isolate rows, and apply the same classifier per failed row. The
first single-send `Retry` ends isolation: remaining claims receive fenced durable backoff using that
error, without further native sends or classification. This bounds a full outage to one batch and one
single send, while `DeadLetter`/`Discard` decisions allow isolation to continue. This
is a bounded isolation pass, not a retry scheduler or replacement for native client retries. It may
duplicate a row that the batch already sent, as allowed by at-least-once delivery. Successful batches
are unchanged, and cancellation or known claim expiry stops isolation. No broker outcome is inferred
from an aggregate exception and no native client API is reimplemented.

Classifier contexts, scopes and the isolation pass exist only on failure; successful dispatch adds no
work or allocation. SQL Server and MySQL follow-ups are tracked independently under #646. The low-level
store mutation contract remains unchanged; callers using it directly own their failure classification.

Preparation failures retain the existing diagnostic attempt count, including previous retryable sends.
If routing becomes invalid after an extended outage, its first preparation failure can exhaust that
budget. Repair such configuration through the existing dead-letter redrive workflow.
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public sealed class PostgreSqlChangeCaptureOptions
/// <summary>Retain sent IDs, destinations and completion times. Disabled by default; enable on every dispatcher and maintenance worker for this store.</summary>
public bool RetainSentMessages { get; init; }

/// <summary>Failed sends before a row is dead-lettered. Must match other dispatchers for this store.</summary>
/// <summary>Failure budget for local-handler failures, preparation errors and explicit store failure recording. Classified retryable native-send failures retry indefinitely with durable backoff. Must match other dispatchers for this store.</summary>
public int MaxDispatchAttempts { get; init; } = 10;
/// <summary>Maximum rows read per database transaction.</summary>
public int BatchSize { get; init; } = 100;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public static IServiceCollection AddRelayerPostgreSqlChangeCapture(this IService
provider.GetRequiredService<IOptionsMonitor<PostgreSqlChangeCaptureOptions>>().Get(name),
provider.GetServices<ITransport>(), provider.GetRequiredService<ILogger<PostgreSqlChangeCaptureWorker>>(),
provider.GetRequiredService<ILogger<PostgreSqlMaintenanceWorker>>(), provider.GetRequiredService<ILogger<PostgreSqlDirectDispatcher>>(),
provider.GetService<RelayerInstrumentation>()));
provider.GetService<RelayerInstrumentation>(), scopes: provider.GetRequiredService<IServiceScopeFactory>()));
services.AddSingleton<IHostedService>(provider => provider.GetRequiredKeyedService<PostgreSqlChangeCaptureWorker>(name));
return services;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Npgsql;
Expand All @@ -20,15 +21,15 @@ internal sealed partial class PostgreSqlChangeCaptureWorker : BackgroundService
internal PostgreSqlChangeCaptureWorker(NpgsqlDataSource source, Func<LogicalReplicationConnection> connectionFactory,
PostgreSqlChangeCaptureOptions options, IEnumerable<ITransport> transports,
ILogger<PostgreSqlChangeCaptureWorker> logger, ILogger<PostgreSqlMaintenanceWorker> recoveryLogger,
ILogger<PostgreSqlDirectDispatcher> dispatchLogger, RelayerInstrumentation? instrumentation = null)
ILogger<PostgreSqlDirectDispatcher> dispatchLogger, RelayerInstrumentation? instrumentation = null, IServiceScopeFactory? scopes = null)
{
_source = source;
_connectionFactory = connectionFactory;
_options = options;
_logger = logger;
_schema = options.Schema ?? "public";
_table = options.TablePrefix + "outbox";
_recovery = new(source, options.Validate(), transports, recoveryLogger, dispatchLogger, instrumentation);
_recovery = new(source, options.Validate(), transports, recoveryLogger, dispatchLogger, instrumentation, scopes: scopes);
}

public override async Task StartAsync(CancellationToken cancellationToken)
Expand Down
65 changes: 61 additions & 4 deletions src/Relayer.Outbox.PostgreSql/PostgreSqlDirectDispatcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Threading.Channels;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Relayer.Transports;
Expand All @@ -11,6 +12,7 @@ namespace Relayer.Outbox.PostgreSql;
internal sealed class PostgreSqlDirectDispatcher : BackgroundService
{
private readonly PostgreSqlOutboxStore _store;
private readonly PostgreSqlDispatchFailures _failures;
private readonly PostgreSqlDirectDispatchOptions _options;
private readonly ILogger<PostgreSqlDirectDispatcher> _logger;
private readonly Channel<OutboxDispatchBatch> _queue;
Expand Down Expand Up @@ -43,8 +45,9 @@ internal void RecoveryCommitted()

internal PostgreSqlDirectDispatcher(Npgsql.NpgsqlDataSource dataSource, PostgreSqlOutboxOptions storeOptions,
PostgreSqlDirectDispatchOptions options, IEnumerable<ITransport> transports, ILogger<PostgreSqlDirectDispatcher> logger,
PostgreSqlOutboxStore? store = null, RelayerInstrumentation? instrumentation = null)
PostgreSqlOutboxStore? store = null, RelayerInstrumentation? instrumentation = null, IServiceScopeFactory? scopes = null)
{
_failures = new(scopes);
_source = dataSource;
_retainSentMessages = storeOptions.RetainSentMessages;
_maxDispatchAttempts = storeOptions.MaxDispatchAttempts;
Expand Down Expand Up @@ -238,15 +241,43 @@ private async ValueTask DispatchAsync(OutboxDispatchBatch batch, CancellationTok
catch (Exception error)
{
DirectDispatchLog.Failed(_logger, error);
Exception? retryError = null;
for (var i = 0; i < live; i++)
{
try
{
if (await _store.RecordDispatchFailureAsync(_claims[i], error.Message, DateTimeOffset.UtcNow, cancellationToken, error is PostgreSqlLocalFailure { Action: FailureAction.DeadLetter }).ConfigureAwait(false) == 2)
// Native batches may reject every row because one row is invalid. Retry each
// individually under the same live claim; at-least-once delivery permits duplicates.
if (retryError is not null)
{
if (propagateDatabaseFailures) _recoveredPoison++;
else _instrumentation?.RecordOutboxPoison();
await RecordSendFailureAsync(batch, i, retryError, cancellationToken, propagateDatabaseFailures, FailureAction.Retry).ConfigureAwait(false);
}
else if (live > 1 && PostgreSqlLocalTransport.Find(transport) is null)
{
if (expires <= DateTimeOffset.UtcNow)
{
// Stop native sends, but still attempt fenced backoff for every remaining
// claim. Expired or replaced ownership remains protected by the store.
retryError = error;
await RecordSendFailureAsync(batch, i, error, cancellationToken, propagateDatabaseFailures, FailureAction.Retry).ConfigureAwait(false);
continue;
}
Exception? singleError = null;
try { await transport.SendAsync(_messages[i], cancellationToken).ConfigureAwait(false); }
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { throw; }
catch (Exception failure) { singleError = failure; }
if (singleError is null)
{
// Completion failures must never be classified as failed sends.
if (await _store.CompleteBatchAsync(_claims.AsMemory(i, 1), DateTimeOffset.UtcNow, cancellationToken).ConfigureAwait(false) == 1)
_instrumentation?.AddOutboxPending(-1);
continue;
}
if (await RecordSendFailureAsync(batch, i, singleError, cancellationToken, propagateDatabaseFailures).ConfigureAwait(false) == FailureAction.Retry)
retryError = singleError; // A retryable failure ends this isolation pass.
}
else await RecordSendFailureAsync(batch, i, error, cancellationToken, propagateDatabaseFailures,
retryable: PostgreSqlLocalTransport.Find(transport) is null).ConfigureAwait(false);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { throw; }
catch (Exception failure) when (!propagateDatabaseFailures) { DirectDispatchLog.Failed(_logger, failure); }
Expand Down Expand Up @@ -274,6 +305,32 @@ private async ValueTask DispatchAsync(OutboxDispatchBatch batch, CancellationTok
}
}

private async ValueTask<FailureAction> RecordSendFailureAsync(OutboxDispatchBatch batch, int index, Exception error,
CancellationToken cancellationToken, bool propagateDatabaseFailures, FailureAction? knownAction = null, bool retryable = true)
{
BufferedOutboxMessage? row = null;
for (var i = 0; i < batch.Count; i++)
if (batch.Rows[i].Id == _claims[index].MessageId) { row = batch.Rows[i]; break; }
if (row is null) throw new InvalidOperationException("The failed claim has no dispatch row.");
var action = knownAction ?? await _failures.ClassifyAsync(error, row.Id, row.MessageType, row.Attempts + 1,
row.TenantId, _messages[index], cancellationToken).ConfigureAwait(false);
if (action == FailureAction.Discard)
{
var completed = await _store.CompleteBatchAsync(_claims.AsMemory(index, 1), DateTimeOffset.UtcNow, cancellationToken).ConfigureAwait(false);
_instrumentation?.AddOutboxPending(-completed);
return action;
}
if (action is not (FailureAction.Retry or FailureAction.DeadLetter))
throw new InvalidOperationException("The dispatch failure classifier returned an unknown action.");
if (await _store.RecordDispatchFailureAsync(_claims[index], error.Message, DateTimeOffset.UtcNow,
cancellationToken, permanent: action == FailureAction.DeadLetter, retryable: retryable).ConfigureAwait(false) == 2)
{
if (propagateDatabaseFailures) _recoveredPoison++;
else _instrumentation?.RecordOutboxPoison();
}
return action;
}

// Recovery owns a separate dispatcher instance, so these buffers never overlap the commit queue.
[RuntimeAsyncMethodGeneration(false)]
[AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder))]
Expand Down
53 changes: 53 additions & 0 deletions src/Relayer.Outbox.PostgreSql/PostgreSqlDispatchFailures.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
using System.Globalization;
using Microsoft.Extensions.DependencyInjection;

namespace Relayer.Outbox.PostgreSql;

// Classifier scopes and context views exist only on the failed-send path.
internal sealed class PostgreSqlDispatchFailures(IServiceScopeFactory? scopes)
{
private readonly DefaultFailureClassifier _fallback = new();

internal async ValueTask<FailureAction> ClassifyAsync(Exception error, Guid id, string wireType,
int attempt, string? tenantId, OutgoingMessage message, CancellationToken cancellationToken)
{
if (error is PostgreSqlLocalFailure local) return local.Action;
if (scopes is null) return _fallback.Classify(error, new Context(id, wireType, attempt, message, null, cancellationToken));
await using var scope = scopes.CreateAsyncScope();
var services = scope.ServiceProvider;
if (tenantId is not null && services.GetService<TenantContext>() is { } tenant) tenant.Id = new(tenantId);
var classifier = services.GetService<IFailureClassifier>() ?? _fallback;
return classifier.Classify(error, new Context(id, wireType, attempt, message, services, cancellationToken));
}

private sealed class Context(Guid id, string wireType, int attempt, OutgoingMessage message,
IServiceProvider? services, CancellationToken cancellationToken) : MessageContext
{
public override string MessageId => id.ToString();
public override MessageType MessageType
{
get
{
var separator = wireType.LastIndexOf(";v=", StringComparison.Ordinal);
return separator >= 0 && int.TryParse(wireType.AsSpan(separator + 3), NumberStyles.None, CultureInfo.InvariantCulture, out var version)
? new(wireType[..separator], version) : new(wireType, 1);
}
}
public override MessageHeaders Headers { get; } = new HeadersView(message.Headers);
public override int Attempt => attempt;
public override IServiceProvider Services => services ?? throw new InvalidOperationException("Dispatch classifier services require a registered IServiceScopeFactory.");
public override MessageFeatures Features { get; } = new();
public override CancellationToken CancellationToken => cancellationToken;
}

private sealed class HeadersView(ReadOnlyMemory<KeyValuePair<string, WireString>> headers) : MessageHeaders
{
public override bool TryGetValue(string name, out WireString value)
{
foreach (var header in headers.Span)
if (header.Key == name) { value = header.Value; return true; }
value = default;
return false;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ public sealed class PostgreSqlMaintenanceOptions
/// <summary>Retain sent IDs, destinations and completion times. Disabled by default; enable on every dispatcher and maintenance worker for this store.</summary>
public bool RetainSentMessages { get; init; }

/// <summary>Failed sends before a row is dead-lettered. Must match other dispatchers for this store.</summary>
/// <summary>Failure budget for local-handler failures, preparation errors and explicit store failure recording. Classified retryable native-send failures retry indefinitely with durable backoff. Must match other dispatchers for this store.</summary>
public int MaxDispatchAttempts { get; init; } = 10;
/// <summary>Maximum rows scanned or deleted per pass.</summary>
public int BatchSize { get; init; } = 100;
Expand Down
Loading
Loading