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
32 changes: 32 additions & 0 deletions docs/decisions.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |

---

Expand Down Expand Up @@ -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).
2 changes: 1 addition & 1 deletion src/Relayer.Outbox.MySql/MySqlDirectDispatcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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); }
Expand Down
2 changes: 1 addition & 1 deletion src/Relayer.Outbox.MySql/MySqlMaintenanceOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ public sealed class MySqlMaintenanceOptions
{
/// <summary>Table prefix, identical to every writer and dispatcher.</summary>
public string TablePrefix { get; init; } = "relayer_";
/// <summary>Failed sends before a row is dead-lettered. Must match other dispatchers for this store.</summary>
/// <summary>Preparation failures before dead-lettering; native send failures retry 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
2 changes: 1 addition & 1 deletion src/Relayer.Outbox.MySql/MySqlOrderedDispatchOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ public sealed class MySqlOrderedDispatchOptions
public TimeSpan LeaseDuration { get; init; } = TimeSpan.FromSeconds(30);
/// <summary>Delay between scans, less than one third of the lease duration.</summary>
public TimeSpan PollInterval { get; init; } = TimeSpan.FromSeconds(1);
/// <summary>Failed sends before a row is parked for operator recovery. Must match other dispatchers for this store.</summary>
/// <summary>Preparation failures before parking a row; native send failures retry with durable backoff. Must match other dispatchers for this store.</summary>
public int MaxDispatchAttempts { get; init; } = 10;
/// <summary>Maximum sequential sends in one bounded lane transaction.</summary>
public int BatchSize { get; init; } = 100;
Expand Down
9 changes: 7 additions & 2 deletions src/Relayer.Outbox.MySql/MySqlOrderedDispatcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -136,18 +136,23 @@ internal async ValueTask<int> 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;
}
Expand Down
7 changes: 6 additions & 1 deletion src/Relayer.Outbox.MySql/MySqlOrderedLane.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
{
Expand All @@ -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);
}
Expand Down Expand Up @@ -73,6 +75,9 @@ internal ValueTask<bool> CompleteAsync(MySqlConnection connection, MySqlTransact
internal ValueTask<bool> FailAsync(MySqlConnection connection, MySqlTransaction transaction, OutboxClaim claim,
string error, CancellationToken cancellationToken) => MutateAsync(connection, transaction, _fail, claim, error, cancellationToken);

internal ValueTask<bool> 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<bool> MutateAsync(MySqlConnection connection, MySqlTransaction transaction,
Expand All @@ -90,6 +95,6 @@ private static async ValueTask<bool> 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();
}
}
2 changes: 1 addition & 1 deletion src/Relayer.Outbox.MySql/MySqlOutboxOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ namespace Relayer.Outbox.MySql;
/// <summary>Names for MySQL durable outbox storage in the data source's selected database.</summary>
public sealed class MySqlOutboxOptions
{
/// <summary>Failed sends before dead-lettering. Match across dispatchers for the same tables.</summary>
/// <summary>Explicit poison failures before dead-lettering; native send failures retry with durable backoff. Match across dispatchers for the same tables.</summary>
public int MaxDispatchAttempts { get; init; } = 10;

/// <summary>Stable lane count for ordering keys. All writers and ordered workers must agree.</summary>
Expand Down
13 changes: 13 additions & 0 deletions src/Relayer.Outbox.MySql/MySqlOutboxStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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)
Expand Down Expand Up @@ -173,6 +175,16 @@ public async ValueTask<bool> RecordFailureAsync(OutboxClaim claim, string error,
internal ValueTask<FailureOutcome> 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<bool> 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)
{
Expand Down Expand Up @@ -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();
Expand Down
12 changes: 12 additions & 0 deletions src/Relayer.Outbox.MySql/MySqlRetrySql.cs
Original file line number Diff line number Diff line change
@@ -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}
""";
}
Loading
Loading