diff --git a/docs/decisions.md b/docs/decisions.md
index b46dcfc0b..6937b8c93 100644
--- a/docs/decisions.md
+++ b/docs/decisions.md
@@ -78,6 +78,9 @@ To change a decision, add a new entry that supersedes it rather than editing his
| [D65](#d65-mysql-maintenance-uses-native-session-admission-and-existing-dispatch) | MySQL maintenance uses native session admission and existing dispatch | Accepted |
| [D66](#d66-durable-local-work-reuses-outbox-rows-and-native-postgresql-transactions) | Durable local work reuses outbox rows and native PostgreSQL transactions | Accepted |
| [D67](#d67-sqs-visibility-retries-retain-native-receive-semantics) | SQS visibility retries retain native receive semantics | Accepted |
+| [D68](#d68-offline-cli-export-loads-an-explicit-application-declaration-factory) | Offline CLI export loads an explicit application declaration factory | Accepted |
+| [D69](#d69-retryable-handler-failures-get-three-in-process-retries-by-default) | Retryable handler failures get three in-process retries by default | Accepted |
+| [D70](#d70-mysql-send-failures-retain-durable-retry-eligibility) | MySQL send failures retain durable retry eligibility | Accepted |
---
@@ -1630,3 +1633,32 @@ that same transaction, not exactly-once external effects. Existing broker dispat
**Decision.** A new `FailureOptions`, including the policy constructed by default for each transport consumer, permits three additional in-process attempts at 100 ms, 500 ms and 1 s. Existing jitter shortens each delay by up to 20%. Durable redelivery remains opt-in. Permanent classification still bypasses retries. `FailureOptions.None` creates an explicit policy with empty retry and redelivery lists; setting `RetryDelays` to empty also disables in-process retries without losing custom dead-letter or redelivery settings. Configuring any retry sequence replaces the default, while configuring only redelivery retains it.
**Consequences.** A retryable delivery has at most four attempts before its configured durable redelivery or dead-letter path. Backoff adds up to 1.6 seconds to an exhausted delivery, within the same native lock/acknowledgement lifetime; applications must account for their handler duration and broker deadlines. Successful deliveries do no additional per-message work or allocation. The default arrays are owned by each options instance, avoiding mutable shared policy storage.
+
+
+## D70. MySQL send failures retain durable retry eligibility
+
+**Context.** #668 found that broker outages consumed MySQL outbox poison budgets, parking ordered
+keys or dead-lettering unordered work. Native retries already run inside each send: Azure Service Bus
+7.21.0's [AmqpSender](https://github.com/Azure/azure-sdk-for-net/blob/Azure.Messaging.ServiceBus_7.21.0/sdk/servicebus/Azure.Messaging.ServiceBus/src/Amqp/AmqpSender.cs)
+uses `ServiceBusRetryPolicy.RunOperation`. Dekaf 1.27.0's Kafka-specific
+[OutboxRelayService](https://github.com/thomhurst/Dekaf/blob/v1.27.0/src/Dekaf.Outbox/OutboxRelayService.cs)
+has in-memory bucket backoff, not durable eligibility for Relayer's multi-transport MySQL rows.
+MySqlConnector 3.0.0 supplies conditional updates and native transactions, not application send scheduling.
+The existing `deliver_at` checks, fenced mutations, direct dispatcher and ordered head barrier already
+provide the required durable mechanism; MySQL Event Scheduler cannot invoke application transports.
+
+**Decision.** After a failed native send, reuse a fenced update to retain the row and persist exponential
+backoff in `deliver_at` (1 second to 5 minutes), clearing its claim. Calculate the delay before incrementing
+`attempts` because MySQL single-table UPDATE assignments are evaluated left to right; cap diagnostic
+attempts at 30 to avoid overflow. No in-process send retry loop, extra table or broker scheduler is added.
+All native send exceptions, including permanent broker rejections and batch failures, retain eligibility:
+`ITransport` has no portable per-row permanent classification for native batch errors. Explicit store
+failure calls and preparation failures retain their poison transitions. Success and completion uncertainty
+retain their existing fenced behavior.
+
+**Consequences.** Broker outages no longer poison durable work. Retry deadlines survive worker replacement;
+a delayed ordered head blocks its lane until eligible, preserving order. Operators must inspect persistent
+native rejections and repair their cause. A failed batch backs off every claimed row, preserving at-least-once
+semantics after partial acceptance. Preparation failures still count previous diagnostic attempts toward
+the poison budget; repair can require resetting attempts. Success does no additional database work or
+allocation. See the [MySQL reference](../website/docs/reference/mysql-store.md#recovery-poison-rows-and-retention).
diff --git a/src/Relayer.Outbox.MySql/MySqlDirectDispatcher.cs b/src/Relayer.Outbox.MySql/MySqlDirectDispatcher.cs
index ebc430111..ff2088108 100644
--- a/src/Relayer.Outbox.MySql/MySqlDirectDispatcher.cs
+++ b/src/Relayer.Outbox.MySql/MySqlDirectDispatcher.cs
@@ -196,7 +196,7 @@ private async ValueTask DispatchAsync(OutboxDispatchBatch batch, CancellationTok
{
try
{
- (await _store.RecordDispatchFailureAsync(_claims[i], error.Message, DateTimeOffset.UtcNow, cancellationToken).ConfigureAwait(false)).RecordTelemetry(_instrumentation);
+ await _store.RecordRetryAsync(_claims[i], error.Message, DateTimeOffset.UtcNow, cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { throw; }
catch (Exception failure) { DirectDispatchLog.Failed(_logger, failure); }
diff --git a/src/Relayer.Outbox.MySql/MySqlMaintenanceOptions.cs b/src/Relayer.Outbox.MySql/MySqlMaintenanceOptions.cs
index f4d9fed4a..e3f594fba 100644
--- a/src/Relayer.Outbox.MySql/MySqlMaintenanceOptions.cs
+++ b/src/Relayer.Outbox.MySql/MySqlMaintenanceOptions.cs
@@ -5,7 +5,7 @@ public sealed class MySqlMaintenanceOptions
{
/// Table prefix, identical to every writer and dispatcher.
public string TablePrefix { get; init; } = "relayer_";
- /// Failed sends before a row is dead-lettered. Must match other dispatchers for this store.
+ /// Preparation failures before dead-lettering; native send failures retry with durable backoff. Must match other dispatchers for this store.
public int MaxDispatchAttempts { get; init; } = 10;
/// Maximum rows scanned or deleted per pass.
public int BatchSize { get; init; } = 100;
diff --git a/src/Relayer.Outbox.MySql/MySqlOrderedDispatchOptions.cs b/src/Relayer.Outbox.MySql/MySqlOrderedDispatchOptions.cs
index 6937082ae..406de68d6 100644
--- a/src/Relayer.Outbox.MySql/MySqlOrderedDispatchOptions.cs
+++ b/src/Relayer.Outbox.MySql/MySqlOrderedDispatchOptions.cs
@@ -11,7 +11,7 @@ public sealed class MySqlOrderedDispatchOptions
public TimeSpan LeaseDuration { get; init; } = TimeSpan.FromSeconds(30);
/// Delay between scans, less than one third of the lease duration.
public TimeSpan PollInterval { get; init; } = TimeSpan.FromSeconds(1);
- /// Failed sends before a row is parked for operator recovery. Must match other dispatchers for this store.
+ /// Preparation failures before parking a row; native send failures retry with durable backoff. Must match other dispatchers for this store.
public int MaxDispatchAttempts { get; init; } = 10;
/// Maximum sequential sends in one bounded lane transaction.
public int BatchSize { get; init; } = 100;
diff --git a/src/Relayer.Outbox.MySql/MySqlOrderedDispatcher.cs b/src/Relayer.Outbox.MySql/MySqlOrderedDispatcher.cs
index 3487903d8..f20e91080 100644
--- a/src/Relayer.Outbox.MySql/MySqlOrderedDispatcher.cs
+++ b/src/Relayer.Outbox.MySql/MySqlOrderedDispatcher.cs
@@ -136,18 +136,23 @@ internal async ValueTask DispatchLaneAsync(int lane, CancellationToken canc
var row = _rows[index];
var claim = new OutboxClaim(row.Id, Guid.NewGuid());
if (!await _lane.ClaimAsync(connection, transaction, claim, cancellationToken).ConfigureAwait(false)) break;
+ var sending = false;
try
{
if (row.TransportName.Length == 0) throw new InvalidDataException(row.LastError);
var prepared = Prepare(row, _transports, _capabilities);
_instrumentation?.RecordOutboxDispatchLag(_timeProvider.GetUtcNow() - row.CreatedAt);
+ sending = true;
await prepared.Transport.SendAsync(prepared.Message, cancellationToken).ConfigureAwait(false);
}
catch (Exception error) when (!cancellationToken.IsCancellationRequested)
{
- if (!await _lane.FailAsync(connection, transaction, claim, error.Message, cancellationToken).ConfigureAwait(false))
+ var recorded = sending
+ ? await _lane.RetryAsync(connection, transaction, claim, error.Message, cancellationToken).ConfigureAwait(false)
+ : await _lane.FailAsync(connection, transaction, claim, error.Message, cancellationToken).ConfigureAwait(false);
+ if (!recorded)
throw new InvalidOperationException("Ordered outbox claim expired while recording a dispatch failure.", error);
- poisoned = row.Attempts + 1 >= _options.MaxDispatchAttempts;
+ poisoned = !sending && row.Attempts + 1 >= _options.MaxDispatchAttempts;
DispatchFailed(_logger, error);
break;
}
diff --git a/src/Relayer.Outbox.MySql/MySqlOrderedLane.cs b/src/Relayer.Outbox.MySql/MySqlOrderedLane.cs
index d47ce649a..0ec43acdd 100644
--- a/src/Relayer.Outbox.MySql/MySqlOrderedLane.cs
+++ b/src/Relayer.Outbox.MySql/MySqlOrderedLane.cs
@@ -12,6 +12,7 @@ internal sealed class MySqlOrderedLane : IDisposable
private readonly MySqlStoreParameters _claim;
private readonly MySqlStoreParameters _complete;
private readonly MySqlStoreParameters _fail;
+ private readonly MySqlStoreParameters _retry;
internal MySqlOrderedLane(MySqlDataSource source, MySqlOutboxOptions options, TimeSpan duration, int maxAttempts)
{
@@ -25,6 +26,7 @@ internal MySqlOrderedLane(MySqlDataSource source, MySqlOutboxOptions options, Ti
_claim = new($"UPDATE {table} SET claim_token = @token, claim_expires_at = TIMESTAMPADD(MICROSECOND, @duration, UTC_TIMESTAMP(6)) WHERE id = @id AND status = 'pending' AND (deliver_at IS NULL OR deliver_at <= UTC_TIMESTAMP(6)) AND (claim_expires_at IS NULL OR claim_expires_at <= UTC_TIMESTAMP(6))");
_claim.Command.Parameters.AddWithValue("duration", duration.Ticks / 10);
_complete = new($"DELETE FROM {table} WHERE {fenced}");
+ _retry = new(MySqlRetrySql.Update(table, fenced, "UTC_TIMESTAMP(6)"));
_fail = new($"UPDATE {table} SET status = IF(attempts + 1 >= @maximum, 'parked', 'pending'), attempts = attempts + 1, last_error = @error, claim_token = NULL, claim_expires_at = NULL WHERE {fenced}");
_fail.Command.Parameters.AddWithValue("maximum", maxAttempts);
}
@@ -73,6 +75,9 @@ internal ValueTask CompleteAsync(MySqlConnection connection, MySqlTransact
internal ValueTask FailAsync(MySqlConnection connection, MySqlTransaction transaction, OutboxClaim claim,
string error, CancellationToken cancellationToken) => MutateAsync(connection, transaction, _fail, claim, error, cancellationToken);
+ internal ValueTask RetryAsync(MySqlConnection connection, MySqlTransaction transaction, OutboxClaim claim,
+ string error, CancellationToken cancellationToken) => MutateAsync(connection, transaction, _retry, claim, error, cancellationToken);
+
[RuntimeAsyncMethodGeneration(false)]
[AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder<>))]
private static async ValueTask MutateAsync(MySqlConnection connection, MySqlTransaction transaction,
@@ -90,6 +95,6 @@ private static async ValueTask MutateAsync(MySqlConnection connection, MyS
public void Dispose()
{
_reader.Dispose(); _read.Command.Dispose(); _ready.Command.Dispose();
- _claim.Command.Dispose(); _complete.Command.Dispose(); _fail.Command.Dispose();
+ _claim.Command.Dispose(); _complete.Command.Dispose(); _fail.Command.Dispose(); _retry.Command.Dispose();
}
}
diff --git a/src/Relayer.Outbox.MySql/MySqlOutboxOptions.cs b/src/Relayer.Outbox.MySql/MySqlOutboxOptions.cs
index f742135b2..3481c9ea3 100644
--- a/src/Relayer.Outbox.MySql/MySqlOutboxOptions.cs
+++ b/src/Relayer.Outbox.MySql/MySqlOutboxOptions.cs
@@ -3,7 +3,7 @@ namespace Relayer.Outbox.MySql;
/// Names for MySQL durable outbox storage in the data source's selected database.
public sealed class MySqlOutboxOptions
{
- /// Failed sends before dead-lettering. Match across dispatchers for the same tables.
+ /// Explicit poison failures before dead-lettering; native send failures retry with durable backoff. Match across dispatchers for the same tables.
public int MaxDispatchAttempts { get; init; } = 10;
/// Stable lane count for ordering keys. All writers and ordered workers must agree.
diff --git a/src/Relayer.Outbox.MySql/MySqlOutboxStore.cs b/src/Relayer.Outbox.MySql/MySqlOutboxStore.cs
index 1ea6243da..6670e2820 100644
--- a/src/Relayer.Outbox.MySql/MySqlOutboxStore.cs
+++ b/src/Relayer.Outbox.MySql/MySqlOutboxStore.cs
@@ -20,6 +20,7 @@ public sealed class MySqlOutboxStore : IOutboxStore, IDisposable
private readonly MySqlStoreParameters _renew;
private readonly MySqlStoreParameters _complete;
private readonly MySqlStoreParameters _fail;
+ private readonly MySqlStoreParameters _retry;
private readonly MySqlStoreParameters _count;
private readonly MySqlDispatchMutations _claimBatch;
private readonly MySqlDispatchMutations _completeBatch;
@@ -43,6 +44,7 @@ public MySqlOutboxStore(MySqlDataSource dataSource, MySqlOutboxOptions? options
_claim = new($"UPDATE {table} SET claim_token = @token, claim_expires_at = @expires WHERE id = @id AND {eligible}");
_renew = new($"UPDATE {table} SET claim_expires_at = GREATEST(claim_expires_at, @expires) WHERE {fenced}");
_complete = new($"DELETE FROM {table} WHERE {fenced}");
+ _retry = new(MySqlRetrySql.Update(table, fenced, "@now"));
_fail = new($"UPDATE {table} SET attempts=attempts+1,last_error=@error WHERE {fenced}");
_failureSql = $"""
REPLACE INTO {dead} (id,lane,ordering_key,transport,destination,message_type,headers,body,created_at,deliver_at,attempts,last_error,tenant_id,failed_at)
@@ -173,6 +175,16 @@ public async ValueTask RecordFailureAsync(OutboxClaim claim, string error,
internal ValueTask RecordDispatchFailureAsync(OutboxClaim claim, string error, DateTimeOffset now,
CancellationToken cancellationToken) => FailAsync(claim, error, now, _failureLimit, cancellationToken);
+ // Native send failures remain pending, independently of the explicit poison budget.
+ internal ValueTask RecordRetryAsync(OutboxClaim claim, string error, DateTimeOffset now,
+ CancellationToken cancellationToken)
+ {
+ Validate(claim);
+ ArgumentNullException.ThrowIfNull(error);
+ _retry.Command.Parameters["error"].Value = error;
+ return MutateAsync(_retry, claim, now, cancellationToken);
+ }
+
// Only returned after the native transaction commits; stale claims and rollback have no terminal outcome.
internal readonly record struct FailureOutcome(bool Accepted, bool Removed)
{
@@ -317,6 +329,7 @@ public void Dispose()
_renew.Command.Dispose();
_complete.Command.Dispose();
_fail.Command.Dispose();
+ _retry.Command.Dispose();
_count.Command.Dispose();
_claimBatch.Dispose();
_completeBatch.Dispose();
diff --git a/src/Relayer.Outbox.MySql/MySqlRetrySql.cs b/src/Relayer.Outbox.MySql/MySqlRetrySql.cs
new file mode 100644
index 000000000..eae6d416b
--- /dev/null
+++ b/src/Relayer.Outbox.MySql/MySqlRetrySql.cs
@@ -0,0 +1,12 @@
+namespace Relayer.Outbox.MySql;
+
+// Native send retries finish before this durable transition. MySQL evaluates single-table
+// UPDATE assignments left to right: calculate the delay from the previous attempt count first.
+internal static class MySqlRetrySql
+{
+ internal static string Update(string table, string fenced, string now) => $"""
+ UPDATE {table} SET deliver_at = TIMESTAMPADD(SECOND, LEAST(300, POW(2, LEAST(attempts, 9))), {now}),
+ attempts = LEAST(attempts, 29) + 1, last_error = @error,
+ claim_token = NULL, claim_expires_at = NULL WHERE {fenced}
+ """;
+}
diff --git a/tests/Relayer.Outbox.MySql.Tests/DispatchBackoffTests.cs b/tests/Relayer.Outbox.MySql.Tests/DispatchBackoffTests.cs
new file mode 100644
index 000000000..886423a9d
--- /dev/null
+++ b/tests/Relayer.Outbox.MySql.Tests/DispatchBackoffTests.cs
@@ -0,0 +1,192 @@
+using System.Data;
+using System.Diagnostics.Metrics;
+using Microsoft.Extensions.Logging.Abstractions;
+using MySqlConnector;
+using Relayer.Transports;
+
+namespace Relayer.Outbox.MySql.Tests;
+
+public sealed class DispatchBackoffTests
+{
+ [Test]
+ [Arguments("direct")]
+ [Arguments("maintenance")]
+ [Arguments("ordered")]
+ public async Task Outage_beyond_poison_budget_persists_bounded_backoff_and_recovers_after_restart(string mode)
+ {
+ await using var database = new MySqlFixture();
+ await database.StartAsync();
+ var ordered = mode == "ordered";
+ var id = Guid.CreateVersion7();
+ await database.Insert(id, DateTimeOffset.UtcNow.AddDays(-1), lane: ordered ? 0 : null);
+ if (!ordered) await database.Execute("UPDATE relayer_outbox SET ordering_key=NULL");
+ var options = new MySqlOutboxOptions { Lanes = 1, MaxDispatchAttempts = 1 };
+ var transport = new OutageTransport();
+ using var instrumentation = new RelayerInstrumentation();
+ long pending = 0, poison = 0;
+ using var listener = new MeterListener();
+ listener.InstrumentPublished = (instrument, meterListener) =>
+ {
+ if (instrument == instrumentation.OutboxPending || instrument == instrumentation.OutboxPoison)
+ meterListener.EnableMeasurementEvents(instrument);
+ };
+ listener.SetMeasurementEventCallback((instrument, count, _, _) =>
+ {
+ if (instrument == instrumentation.OutboxPending) Interlocked.Add(ref pending, count);
+ else Interlocked.Add(ref poison, count);
+ });
+ listener.Start();
+ instrumentation.AddOutboxPending(1);
+ var rows = new OutboxRecord[1];
+ using (var store = new MySqlOutboxStore(database.Source, options))
+ await store.ReadPendingAsync(new(ordered ? 0 : null, DateTimeOffset.UtcNow), rows, default);
+ for (var attempt = 0; attempt < 12; attempt++)
+ {
+ await MakeReady();
+ var before = await Clock();
+ await Dispatch();
+ await using var state = database.Source.CreateCommand("SELECT attempts, status, deliver_at, UTC_TIMESTAMP(6), claim_token IS NULL AND claim_expires_at IS NULL, (SELECT COUNT(*) FROM relayer_dead) FROM relayer_outbox");
+ await using var reader = await state.ExecuteReaderAsync();
+ await Assert.That(await reader.ReadAsync()).IsTrue();
+ await Assert.That(reader.GetInt32(0)).IsEqualTo(attempt + 1);
+ await Assert.That(reader.GetString(1)).IsEqualTo("pending");
+ var due = reader.GetDateTime(2);
+ var after = reader.GetDateTime(3);
+ var delay = Math.Min(300, Math.Pow(2, Math.Min(attempt, 9)));
+ await Assert.That(due >= before.AddSeconds(delay) && due <= after.AddSeconds(delay)).IsTrue();
+ await Assert.That(reader.GetBoolean(4)).IsTrue();
+ await Assert.That(reader.GetInt64(5)).IsEqualTo(0L);
+ await Assert.That(poison).IsEqualTo(0L);
+ await Assert.That(pending).IsEqualTo(1L);
+ await reader.DisposeAsync();
+ // Independent of scheduler pauses: a stale notification and a new worker must obey eligibility.
+ await database.Execute("UPDATE relayer_outbox SET deliver_at=TIMESTAMPADD(DAY,1,UTC_TIMESTAMP(6)); UPDATE relayer_leases SET expires_at=TIMESTAMPADD(SECOND,-1,UTC_TIMESTAMP(6))");
+ await Dispatch();
+ await Assert.That(transport.Attempts).IsEqualTo(attempt + 1);
+ }
+ transport.Failing = false;
+ await MakeReady();
+ await Dispatch();
+ await Assert.That(await Scalar(database, "SELECT COUNT(*) FROM relayer_outbox")).IsEqualTo(0L);
+ await Assert.That(transport.Attempts).IsEqualTo(13);
+ await Assert.That(poison).IsEqualTo(0L);
+ await Assert.That(pending).IsEqualTo(0L);
+
+ Task MakeReady() => database.Execute("UPDATE relayer_outbox SET deliver_at=UTC_TIMESTAMP(6); UPDATE relayer_leases SET expires_at=TIMESTAMPADD(SECOND,-1,UTC_TIMESTAMP(6))");
+ async Task Clock()
+ {
+ await using var command = database.Source.CreateCommand("SELECT UTC_TIMESTAMP(6)");
+ return (DateTime)(await command.ExecuteScalarAsync())!;
+ }
+ async Task Dispatch()
+ {
+ // Fresh instances prove that backoff does not depend on process memory.
+ if (ordered)
+ {
+ using var worker = new MySqlOrderedDispatcher(database.Source, new() { Lanes = 1, MaxDispatchAttempts = 1 }, [transport], NullLogger.Instance, instrumentation: instrumentation);
+ await worker.DispatchLaneAsync(0, default);
+ }
+ else if (mode == "maintenance")
+ {
+ using var worker = new MySqlMaintenanceWorker(database.Source, new() { MaxDispatchAttempts = 1, RecoveryDelay = TimeSpan.Zero }, [transport], NullLogger.Instance, instrumentation: instrumentation);
+ await worker.SweepAsync();
+ }
+ else
+ {
+ using var worker = new MySqlDirectDispatcher(database.Source, options, new(), [transport], NullLogger.Instance, instrumentation: instrumentation);
+ var buffered = new BufferedOutboxMessage();
+ buffered.Copy(rows[0], 1);
+ worker.Committed([buffered], 1);
+ await worker.StartAsync(default);
+ using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30));
+ await worker.StopAsync(timeout.Token);
+ }
+ }
+ }
+
+ [Test]
+ public async Task Unordered_retry_is_fenced_atomic_and_saturates_without_dead_lettering()
+ {
+ await using var database = new MySqlFixture();
+ await database.StartAsync();
+ var id = Guid.CreateVersion7();
+ await database.Insert(id, DateTimeOffset.UtcNow);
+ await database.Execute("UPDATE relayer_outbox SET attempts=2147483647");
+ using var store = new MySqlOutboxStore(database.Source, new() { MaxDispatchAttempts = 1 });
+ var now = DateTimeOffset.UtcNow;
+ var claim = new OutboxClaim(id, Guid.NewGuid());
+ await Assert.That(await store.TryClaimAsync(claim, now, now.AddMinutes(1), default)).IsTrue();
+ await Assert.That(await store.RecordRetryAsync(new(id, Guid.NewGuid()), "stale", now, default)).IsFalse();
+ await Assert.That(await store.RecordRetryAsync(claim, "expired", now.AddMinutes(2), default)).IsFalse();
+ await database.Execute("CREATE TRIGGER reject_retry BEFORE UPDATE ON relayer_outbox FOR EACH ROW SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT='write unavailable'");
+ await Assert.That(async () => await store.RecordRetryAsync(claim, "rollback", now, default)).Throws();
+ await Assert.That(await Scalar(database, "SELECT COUNT(*) FROM relayer_outbox WHERE attempts=2147483647 AND claim_token IS NOT NULL AND deliver_at IS NULL AND last_error IS NULL")).IsEqualTo(1L);
+ await database.Execute("DROP TRIGGER reject_retry");
+ await Assert.That(await store.RecordRetryAsync(claim, "retry", now, default)).IsTrue();
+ await Assert.That(await store.RecordRetryAsync(claim, "replay", now, default)).IsFalse();
+ var rows = new OutboxRecord[1];
+ await Assert.That(await store.ReadPendingAsync(new(null, now.AddSeconds(299)), rows, default)).IsEqualTo(0);
+ await Assert.That(await store.ReadPendingAsync(new(null, now.AddSeconds(301)), rows, default)).IsEqualTo(1);
+ await Assert.That(rows[0].Attempts).IsEqualTo(30);
+ await Assert.That(rows[0].LastError).IsEqualTo("retry");
+ await Assert.That(await Scalar(database, "SELECT COUNT(*) FROM relayer_dead")).IsEqualTo(0L);
+ }
+
+ [Test]
+ [Arguments(false)]
+ [Arguments(true)]
+ public async Task Ordered_retry_rejects_stale_claims_and_rolls_back_with_lane_transaction(bool replace)
+ {
+ await using var database = new MySqlFixture();
+ await database.StartAsync();
+ var id = Guid.CreateVersion7();
+ await database.Insert(id, DateTimeOffset.UtcNow, lane: 0);
+ using var lane = new MySqlOrderedLane(database.Source, new(), TimeSpan.FromMinutes(1), 1);
+ await using var connection = await database.Source.OpenConnectionAsync();
+ await using (var transaction = await connection.BeginTransactionAsync(IsolationLevel.ReadCommitted))
+ {
+ var claim = new OutboxClaim(id, Guid.NewGuid());
+ await Assert.That(await lane.ClaimAsync(connection, transaction, claim, default)).IsTrue();
+ await using var change = connection.CreateCommand();
+ change.Transaction = transaction;
+ change.CommandText = replace ? "UPDATE relayer_outbox SET claim_token=UUID_TO_BIN(UUID())" : "UPDATE relayer_outbox SET claim_expires_at=TIMESTAMPADD(SECOND,-1,UTC_TIMESTAMP(6))";
+ await change.ExecuteNonQueryAsync();
+ await Assert.That(await lane.RetryAsync(connection, transaction, claim, "stale", default)).IsFalse();
+ await transaction.RollbackAsync();
+ }
+ await using (var transaction = await connection.BeginTransactionAsync(IsolationLevel.ReadCommitted))
+ {
+ var claim = new OutboxClaim(id, Guid.NewGuid());
+ await Assert.That(await lane.ClaimAsync(connection, transaction, claim, default)).IsTrue();
+ await Assert.That(await lane.RetryAsync(connection, transaction, claim, "rollback", default)).IsTrue();
+ await Assert.That(await lane.RetryAsync(connection, transaction, claim, "replay", default)).IsFalse();
+ await transaction.RollbackAsync();
+ }
+ await Assert.That(await Scalar(database, "SELECT COUNT(*) FROM relayer_outbox WHERE attempts=0 AND claim_token IS NULL AND deliver_at IS NULL AND last_error IS NULL AND status='pending'")).IsEqualTo(1L);
+ }
+
+ private static async Task Scalar(MySqlFixture database, string sql)
+ {
+ await using var command = database.Source.CreateCommand(sql);
+ return Convert.ToInt64(await command.ExecuteScalarAsync());
+ }
+
+ private sealed class OutageTransport : ITransport
+ {
+ internal bool Failing { get; set; } = true;
+ internal int Attempts { get; private set; }
+ public string Name => "events";
+ public TransportCapabilities GetCapabilities(string endpoint) => new() { OrderedByKey = true };
+ public ValueTask SendAsync(OutgoingMessage message, CancellationToken cancellationToken)
+ {
+ Attempts++;
+ if (Failing) throw new IOException("broker unavailable");
+ return ValueTask.CompletedTask;
+ }
+ public ValueTask SendBatchAsync(ReadOnlyMemory messages, CancellationToken cancellationToken) => SendAsync(messages.Span[0], cancellationToken);
+ 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() => ValueTask.CompletedTask;
+ }
+}
diff --git a/tests/Relayer.Outbox.MySql.Tests/MaintenanceTests.cs b/tests/Relayer.Outbox.MySql.Tests/MaintenanceTests.cs
index 603ee830a..de3bdbdc2 100644
--- a/tests/Relayer.Outbox.MySql.Tests/MaintenanceTests.cs
+++ b/tests/Relayer.Outbox.MySql.Tests/MaintenanceTests.cs
@@ -14,7 +14,6 @@ public sealed class MaintenanceTests
[Test]
[Arguments("malformed")]
[Arguments("transport")]
- [Arguments("send")]
public async Task Unordered_poison_metrics_follow_committed_deletions_once(string failure)
{
await using var data = new MySqlFixture();
@@ -37,7 +36,7 @@ public async Task Unordered_poison_metrics_follow_committed_deletions_once(strin
});
listener.Start();
instrumentation.AddOutboxPending(1);
- var transport = failure == "send" ? new Transport(_ => throw new InvalidOperationException("native send failed")) : new Transport();
+ var transport = new Transport();
using var worker = new MySqlMaintenanceWorker(data.Source,
new() { BatchSize = 4, RecoveryDelay = TimeSpan.Zero, MaxDispatchAttempts = 2 },
[transport], NullLogger.Instance, instrumentation: instrumentation);
diff --git a/tests/Relayer.Outbox.MySql.Tests/OrderedDispatchTests.cs b/tests/Relayer.Outbox.MySql.Tests/OrderedDispatchTests.cs
index 7edd395df..e4c8e3cc0 100644
--- a/tests/Relayer.Outbox.MySql.Tests/OrderedDispatchTests.cs
+++ b/tests/Relayer.Outbox.MySql.Tests/OrderedDispatchTests.cs
@@ -160,15 +160,13 @@ public async Task Exhaustion_parks_original_sequence_and_does_not_block_another_
await using var database = new MySqlFixture();
await database.StartAsync();
await Insert(database, Id(3)); await Insert(database, Id(2)); await Insert(database, Id(1), "other");
- var fail = true;
- var transport = new RecordingTransport((message, _) => fail && message.OrderingKey!.Value.ToString() == "key"
- ? ValueTask.FromException(new InvalidOperationException("poison")) : ValueTask.CompletedTask);
+ await database.Execute($"UPDATE relayer_outbox SET transport='missing' WHERE id=UNHEX('{Id(3):N}')");
+ var transport = new RecordingTransport();
using var worker = new MySqlOrderedDispatcher(database.Source, new() { Lanes = 1, MaxDispatchAttempts = 1 }, [transport], NullLogger.Instance);
await Assert.That(await worker.DispatchLaneAsync(0, default)).IsEqualTo(0);
await Assert.That(await worker.DispatchLaneAsync(0, default)).IsEqualTo(1);
await Assert.That(transport.Ids.SequenceEqual([Id(1)])).IsTrue();
- fail = false;
- await database.Execute("UPDATE relayer_outbox SET status = 'pending', attempts = 0 WHERE status = 'parked'");
+ await database.Execute("UPDATE relayer_outbox SET status = 'pending', attempts = 0, transport = 'events' WHERE status = 'parked'");
await Assert.That(await worker.DispatchLaneAsync(0, default)).IsEqualTo(2);
await Assert.That(transport.Ids.SequenceEqual([Id(1), Id(3), Id(2)])).IsTrue();
}
diff --git a/tests/Shared/OutboxOrderedDispatchContractTests.cs b/tests/Shared/OutboxOrderedDispatchContractTests.cs
index c3875edbd..01d842801 100644
--- a/tests/Shared/OutboxOrderedDispatchContractTests.cs
+++ b/tests/Shared/OutboxOrderedDispatchContractTests.cs
@@ -46,6 +46,7 @@ public async Task Failed_head_blocks_later_rows_and_retries_preserve_native_payl
await Assert.That(rows[0]).IsEqualTo(new Row(Id(1), 0, null, false, false));
await Assert.That(rows[1]).IsEqualTo(new Row(Id(2), 1, "broker offline", false, false));
fail = false;
+ await fixture.MakeReady(Id(2)); // Retry eligibility may include a durable backoff.
await Assert.That(await worker.DispatchLaneAsync(0)).IsEqualTo(2);
await Assert.That(transport.Ids.SequenceEqual([Id(2), Id(1)])).IsTrue();
await Assert.That(transport.LastBody).IsEquivalentTo(new byte[] { 7, 8, 9 });
diff --git a/website/docs/reference/mysql-store.md b/website/docs/reference/mysql-store.md
index dd67d68d7..29e94cc72 100644
--- a/website/docs/reference/mysql-store.md
+++ b/website/docs/reference/mysql-store.md
@@ -224,8 +224,11 @@ It uses native `SendAsync`/`SendBatchAsync`, preserving message identity, bytes
Each due unordered row receives a fresh expiring claim token through native conditional updates.
Claim and completion commands use `MySqlBatch`, including native `ROW_COUNT()` results for exact
per-command outcomes. A successful broker send deletes only rows whose token still matches and
-whose claim has not expired. A broker failure records the error and increments attempts; a
-completion error after a successful send leaves attempts unchanged. An expired or interrupted
+whose claim has not expired. After the native client finishes its own send retries, a broker failure
+records the error and a durable exponential retry deadline in `deliver_at`: 1 second, 2 seconds,
+4 seconds, up to 5 minutes. The diagnostic attempt count saturates at 30. Native send errors do
+not exhaust `MaxDispatchAttempts` or move rows to dead storage. A completion error after a successful
+send leaves attempts unchanged. An expired or interrupted
send may be delivered again: this is at-least-once delivery, not an atomic broker/database commit.
Size `ClaimDuration` for the slowest expected database and broker operation.
@@ -272,8 +275,11 @@ lease and request cancellation after half a lease; native completion is awaited
ownership, including shutdown. Size leases for expected send and database latency.
A future-due or live-claimed head blocks later rows. Database due checks remove `deliver_at`
-from the native send. Failures persist attempts and errors, commit a successful prefix and retry
-on later scans. At `MaxDispatchAttempts`, the original row parks with its sequence intact;
+from the native send. Native send failures persist attempts, errors and the same exponential retry
+deadline as direct dispatch, and commit a successful prefix. They never park a row. Until its deadline,
+a retrying head stalls its lane, including other keys. Preparation failures such as missing transports,
+unsupported ordering and malformed rows retain the poison budget. At `MaxDispatchAttempts`,
+the original row parks with its sequence intact;
only later rows for that exact key are blocked, while other keys continue. Malformed headers and
empty required routing fields also consume attempts and park the original raw row. Inspect and repair
parked rows through application-owned SQL. Resume by updating the original row to
@@ -345,7 +351,8 @@ Each bounded recovery pass selects due, old-enough **unordered** pending rows wi
A fixed upper UUID boundary ensures failed, scheduled and previously claimed rows are revisited
while new rows keep arriving. Ordered lanes and parked barriers stay untouched. The existing
direct dispatcher performs native sends and fenced completion; there is no second sender.
-Native send failures consume attempts; failed completion after a successful send does not.
+Native send failures use the durable backoff above and remain pending regardless of
+`MaxDispatchAttempts`; failed completion after a successful send does not consume attempts.
Expired claims and an unknown broker outcome can duplicate delivery, as with direct dispatch.
Malformed headers or empty routing fields are copied **raw** to dead storage under a live claim,
@@ -357,8 +364,17 @@ limit records the outbox poison counter once.
Unordered recovery records `relayer.outbox.dead_lettered` and decrements
`relayer.outbox.pending` only after the fenced transaction commits a poison deletion.
-This includes exhausted native sends, invalid transport destinations and malformed-row
-quarantine. Retries, stale claims and rolled-back transitions do not change these counters.
+This includes invalid transport destinations and malformed-row quarantine. Retries, stale claims and
+rolled-back transitions do not change these counters.
+
+All native send exceptions are retried indefinitely, including a permanent broker rejection, because
+native batch errors do not supply a portable per-row permanent classification. A failed native batch
+applies backoff to every claimed row in that batch; partial acceptance can duplicate delivery on retry.
+Inspect persistent errors and repair routing, payloads or broker configuration through application-owned
+SQL. `MaxDispatchAttempts` governs explicit `RecordFailureAsync` calls and preparation failures,
+including prior diagnostic send attempts: a preparation error after a long outage may exhaust that
+budget immediately. Reset `attempts` when repairing such a row. Clearing `deliver_at` makes a repaired
+row eligible immediately; otherwise its persisted deadline survives process restarts and worker changes.
Cleanup deletes at most `BatchSize` expired dead rows and `BatchSize` expired inbox keys per pass,
using database UTC time and the `failed_at` / `processed_at` indexes. Pending rows, parked ordered