Table of Contents

Class RedisOutboxStore

Namespace
Excalibur.Outbox.Redis
Assembly
Excalibur.Outbox.Redis.dll

Redis-based implementation of IOutboxStore.

public sealed class RedisOutboxStore : IClaimScopedOutboxStore, IClaimScopedDeadLetterableOutboxStore, IOutboxStore, IServiceProvider, IOutboxStoreAdmin, IDeadLetterableOutboxStore, IBackoffSchedulableOutboxStore, IAsyncDisposable, ITenantPartitionedStore, IOutboxPayloadTransformStore
Inheritance
RedisOutboxStore
Implements
Inherited Members

Remarks

Uses Redis sorted sets for priority-based message retrieval and Lua scripts for atomic status transitions (critical for MarkSentAsync to prevent race conditions).

Key structure: - {prefix}:msg:{id} - Hash containing message data - {prefix}:idx:staged - Sorted set of staged messages (score = priority * 1e12 + timestamp) - {prefix}:idx:failed - Sorted set of failed messages (score = retryCount * 1e12 + timestamp) - {prefix}:idx:scheduled - Sorted set of scheduled messages (score = scheduledAt timestamp) - {prefix}:idx:sent - Sorted set of sent messages (score = sentAt timestamp) - {prefix}:idx:leased - Sorted set of claimed (in-flight) messages (score = lease expiry timestamp)

Concurrent delivery is made safe by an atomic Lua lease-claim (see GetUnsentMessagesAsync(int, CancellationToken)): claiming a message moves its id from the staged index to the leased index in a single indivisible step, so two concurrent pollers can never claim the same message (disjoint claim). A leased message stays hidden until it reaches a terminal state — which clears the lease — or its lease expires, at which point it is reclaimed back to the staged index (so a poller that crashes mid-delivery cannot strand a message). This mirrors the SQL Server outbox's LeasedAt/LeasedBy claim.

Constructors

RedisOutboxStore(IOptions<RedisOutboxOptions>, ILogger<RedisOutboxStore>, TimeProvider?)

Initializes a new instance of the RedisOutboxStore class.

public RedisOutboxStore(IOptions<RedisOutboxOptions> options, ILogger<RedisOutboxStore> logger, TimeProvider? timeProvider = null)

Parameters

options IOptions<RedisOutboxOptions>

The Redis outbox options.

logger ILogger<RedisOutboxStore>

The logger instance.

timeProvider TimeProvider

The time provider used for backoff/claim-gate decisions. Defaults to System.

RedisOutboxStore(IConnectionMultiplexer, IOptions<RedisOutboxOptions>, ILogger<RedisOutboxStore>, TimeProvider?)

Initializes a new instance of the RedisOutboxStore class with an existing connection.

public RedisOutboxStore(IConnectionMultiplexer connection, IOptions<RedisOutboxOptions> options, ILogger<RedisOutboxStore> logger, TimeProvider? timeProvider = null)

Parameters

connection IConnectionMultiplexer

An existing Redis connection multiplexer. Any StackExchange.Redis.IConnectionMultiplexer implementation is accepted, including a wrapper or proxy supplied by the host.

options IOptions<RedisOutboxOptions>

The Redis outbox options.

logger ILogger<RedisOutboxStore>

The logger instance.

timeProvider TimeProvider

The time provider used for backoff/claim-gate decisions. Defaults to System.

Methods

CleanupAllTenantsSentMessagesAsync(DateTimeOffset, int, CancellationToken)

Removes sent messages older than the specified age across every tenant.

public ValueTask<int> CleanupAllTenantsSentMessagesAsync(DateTimeOffset olderThan, int batchSize, CancellationToken cancellationToken)

Parameters

olderThan DateTimeOffset

Remove messages sent before this timestamp.

batchSize int

Maximum number of messages to remove in one operation.

cancellationToken CancellationToken

Token to monitor for cancellation requests.

Returns

ValueTask<int>

The number of messages removed, across all tenants.

Remarks

This is an estate-wide retention sweep and is deliberately unscoped: it matches rows by age, not by tenant, so it removes the qualifying messages of every tenant in the store. The name declares that scope so it cannot be reached by a caller who meant a single tenant.

An outbox store reads no ambient tenant context, so it cannot honor a tenant it never sees. Should tenant-scoped retention ever be required, it arrives as an explicit parameter — never by inferring a scope from ambient state.

DisposeAsync()

Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources asynchronously.

public ValueTask DisposeAsync()

Returns

ValueTask

A task that represents the asynchronous dispose operation.

EnqueueAsync(IDispatchMessage, IMessageContext, CancellationToken)

Enqueues a message in the outbox for later delivery with context.

[UnconditionalSuppressMessage("AOT", "IL3050:Using RequiresDynamicCode member in AOT", Justification = "Outbox payloads use runtime serialization for message types.")]
[UnconditionalSuppressMessage("Trimming", "IL2026:Members annotated with RequiresUnreferencedCode may break with trimming", Justification = "Outbox payloads use runtime serialization for message types.")]
[RequiresUnreferencedCode("Outbox stores serialize the message payload reflectively; supply JsonSerializerOptions with a source-generated resolver for trimming and AOT.")]
[RequiresDynamicCode("Outbox stores serialize the message payload reflectively; supply JsonSerializerOptions with a source-generated resolver for trimming and AOT.")]
public ValueTask EnqueueAsync(IDispatchMessage message, IMessageContext context, CancellationToken cancellationToken)

Parameters

message IDispatchMessage

The message to enqueue.

context IMessageContext

The message context.

cancellationToken CancellationToken

Token to monitor for cancellation requests.

Returns

ValueTask

A task representing the asynchronous enqueue operation.

Remarks

Postcondition on what is staged. The staged message's headers contain exactly the values marked on context with SetPropagatedItem(IMessageContext, string, string), plus whatever envelope keys this store supplies as its own framing. No other context state reaches them — in particular not Items, which is request-local.

This is stated here, on the interface, because it is the specification and not an implementation detail: while it lived only in the implementations, one store staged the whole Items collection, two staged their envelope keys and nothing else, and six staged neither — all three behaviours legal, none a subtyping violation, and a consumer unable to predict which they would get. Staging MORE than this is now as wrong as staging less, and a conformance derivation can check both directions.

Build the staged message with FromContext(string, byte[], string, IMessageContext, IDictionary<string, object>?), which satisfies the postcondition by construction. A store that assembles an OutboundMessage by hand is responsible for satisfying it itself.

Exceptions

ArgumentNullException

Thrown when message or context is null.

GetAllTenantsFailedMessagesAsync(int, DateTimeOffset?, int, CancellationToken)

Retrieves failed messages that are eligible for retry, across every tenant.

public ValueTask<IEnumerable<OutboundMessage>> GetAllTenantsFailedMessagesAsync(int maxRetries, DateTimeOffset? olderThan, int batchSize, CancellationToken cancellationToken)

Parameters

maxRetries int

Maximum number of retry attempts to consider.

olderThan DateTimeOffset?

Only return messages that failed before this timestamp.

batchSize int

Maximum number of messages to retrieve.

cancellationToken CancellationToken

Token to monitor for cancellation requests.

Returns

ValueTask<IEnumerable<OutboundMessage>>

Collection of failed messages eligible for retry, across all tenants.

Remarks

Observation only — the result MUST NOT be handed to a transport. This is a plain read: it matches rows without conditionally taking them, so two callers observe the same message and neither holds it. Publishing from this set is check-then-act and delivers the message twice. A drain claims through IOutboxStore.GetUnsentMessagesAsync, whose claim already admits a failed message once its next-attempt floor has elapsed; this read consults no floor, so a message deferred moments ago still appears here. Use it to report and diagnose, never to dispatch.

Scope: estate-wide. This read matches rows by status and age, not by tenant, so it observes the messages of every tenant in the store. It modifies nothing. Each returned OutboundMessage carries its own TenantId, so a caller can re-establish the owning tenant for each message it handles.

The name is the safety control. An unscoped read is reachable only by writing "AllTenants" at the call site — never by omitting a scope, and never by passing a value that happens to mean "everything". This discloses full message bodies, so a reviewer reading the call site sees the disclosure without tracing where a scope came from.

The outbox drain is cross-tenant by design: one dispatcher serves every tenant, so scoping this read to an ambient tenant would stall delivery for all the others. An outbox store reads no ambient tenant context; should a tenant-scoped read ever be required, it arrives as an explicit parameter on a distinct operation — never by inferring a scope from ambient state.

GetAllTenantsScheduledMessagesAsync(DateTimeOffset, int, CancellationToken)

Retrieves messages scheduled for future delivery, across every tenant.

public ValueTask<IEnumerable<OutboundMessage>> GetAllTenantsScheduledMessagesAsync(DateTimeOffset scheduledBefore, int batchSize, CancellationToken cancellationToken)

Parameters

scheduledBefore DateTimeOffset

Only return messages scheduled before this timestamp.

batchSize int

Maximum number of messages to retrieve.

cancellationToken CancellationToken

Token to monitor for cancellation requests.

Returns

ValueTask<IEnumerable<OutboundMessage>>

Collection of scheduled messages ready for delivery, across all tenants.

Remarks

Observation only — the result MUST NOT be handed to a transport. This is a plain read: it matches rows without conditionally taking them, so two callers observe the same message and neither holds it. Publishing from this set is check-then-act and delivers the message twice — a filter on an unset dispatcher column does not make it a claim, because the value it tests is never conditionally written. A drain claims through IOutboxStore.GetUnsentMessagesAsync, whose claim already admits a scheduled message once its time has arrived. Use it to report and diagnose, never to dispatch.

Scope: estate-wide. This read matches rows by status and age, not by tenant, so it observes the messages of every tenant in the store. It modifies nothing. Each returned OutboundMessage carries its own TenantId, so a caller can re-establish the owning tenant for each message it handles.

The name is the safety control. An unscoped read is reachable only by writing "AllTenants" at the call site — never by omitting a scope, and never by passing a value that happens to mean "everything". This discloses full message bodies, so a reviewer reading the call site sees the disclosure without tracing where a scope came from.

The outbox drain is cross-tenant by design: one dispatcher serves every tenant, so scoping this read to an ambient tenant would stall delivery for all the others. An outbox store reads no ambient tenant context; should a tenant-scoped read ever be required, it arrives as an explicit parameter on a distinct operation — never by inferring a scope from ambient state.

GetAllTenantsStatisticsAsync(CancellationToken)

Gets statistics about the outbox store, across every tenant.

public ValueTask<OutboxStatistics> GetAllTenantsStatisticsAsync(CancellationToken cancellationToken)

Parameters

cancellationToken CancellationToken

Token to monitor for cancellation requests.

Returns

ValueTask<OutboxStatistics>

Statistics including message counts by status and oldest unsent message age, across all tenants.

Remarks

Scope: estate-wide. The name is the safety control: estate-wide counters are reachable only by writing "AllTenants" at the call site, never by omitting a scope. Aggregate counts disclose no message identifiers, bodies, or tenant names — only totals — so this is a weaker disclosure than GetAllTenantsFailedMessagesAsync(int, DateTimeOffset?, int, CancellationToken), which returns whole messages.

These are estate-wide counters reported to an operator, not to a tenant. The figures describe the whole table: the call takes no tenant argument, and OutboxStatistics carries no tenant field, so a confined result could not say which partition it described even if one were produced.

An outbox store reads no ambient tenant context, so it cannot honor a tenant it never sees. Should per-tenant counters ever be required, they arrive as an explicit parameter on a distinct operation — never by inferring a scope from ambient state.

GetUnsentMessagesAsync(int, CancellationToken)

Retrieves unsent messages from the outbox for publishing.

public ValueTask<IEnumerable<OutboundMessage>> GetUnsentMessagesAsync(int batchSize, CancellationToken cancellationToken)

Parameters

batchSize int

Maximum number of messages to retrieve.

cancellationToken CancellationToken

Token to monitor for cancellation requests.

Returns

ValueTask<IEnumerable<OutboundMessage>>

Collection of unsent messages ready for delivery.

Remarks

This operation returns persisted payload bytes and closed routing/header data; it does not discover or deserialize consumer payload types. Payload decoding belongs to the configured worker codec and its explicit metadata. Provider construction may impose separate runtime requirements. This claim is unfenced. A store that can enforce leadership fencing implements IFencedOutboxStore, whose overloads take the leadership token; a store that cannot is never handed one.

Exceptions

ArgumentOutOfRangeException

Thrown when batchSize is less than 1.

MarkDeadLetteredAsync(string, string, int, string, CancellationToken)

Dead-letters a message only while the caller holds its current acquisition.

public ValueTask<OutboxCompletionOutcome> MarkDeadLetteredAsync(string messageId, string reason, int attemptCount, string claimIdentity, CancellationToken cancellationToken)

Parameters

messageId string

The persisted identifier captured at acquisition.

reason string

The reason for the terminal disposition.

attemptCount int

Nonnegative logical attempt count; applied transitions retain its maximum.

claimIdentity string

The nonblank identity captured from the acquisition, never a process ID.

cancellationToken CancellationToken

Token to monitor for cancellation requests.

Returns

ValueTask<OutboxCompletionOutcome>

The outcome decided atomically with the guarded transition.

Remarks

Validate arguments before mutation. Missing/released/different leases return ClaimLost, retained terminal rows AlreadyTerminal and absent rows MessageNotFound. Refusals are returned, not thrown. No completion may classify its outcome by rereading after a separate mutation.

MarkDeadLetteredAsync(string, string, int, CancellationToken)

Durably transitions the specified message to the terminal DeadLettered status after its retry policy is exhausted.

public ValueTask<OutboxCompletionOutcome> MarkDeadLetteredAsync(string messageId, string reason, int attemptCount, CancellationToken cancellationToken)

Parameters

messageId string

The unique identifier of the message to dead-letter.

reason string

A human-readable reason describing why the message was dead-lettered.

attemptCount int

Observed logical delivery attempts. Nonnegative; an applied transition atomically records the maximum of this value and the stored count.

cancellationToken CancellationToken

Token to monitor for cancellation requests.

Returns

ValueTask<OutboxCompletionOutcome>

The outcome of the transition. Only Applied means the row was mutated.

Remarks

The count describes logical attempts already observed by the caller, not physical transport requests. Only an applied transition may change it: the same atomic operation records max(stored, supplied). Missing and already-terminal messages retain their count; zero is valid for a pre-dispatch poison message.

After this transition the message MUST NOT be returned by any claim predicate (GetUnsentMessagesAsync(int, CancellationToken) or IOutboxStoreAdmin.GetAllTenantsFailedMessagesAsync), preventing re-delivery.

Whether the row is also REMOVED depends on the store's idiom, and the difference is visible to an operator. A store that treats the terminal transition as a move copies the message to a dedicated dead-letter table and deletes the outbox row, so the outbox does not grow. A store that records the terminal state in a status column leaves the row in place; re-delivery is still prevented, but the row remains and this interface offers nothing that enumerates or removes it. Plan retention for that case rather than assuming the transition bounds the table.

This member marks the row. It does NOT put the message anywhere a consumer can read it back. The readable dead-letter surface is a separate contract with its own enumerate, count and replay members, and the framework's own drain writes to BOTH: it enqueues the message there and then calls this member. A caller invoking this member directly gets only the second half, so the message is buried and unreadable even on a store whose idiom moves the row. The same gap opens when the composition resolves a no-op dead-letter queue, which discards the message and logs, while this member still records the terminal state.

So: if the message must remain recoverable, write it to the dead-letter queue before calling this, exactly as the drain does. Nothing here does it for you, and nothing reports that it was not done.

A TERMINAL message is never reopened by this member either, whoever reports it. The same obligation the base completion carries applies here and has to be restated, because this interface is composition rather than inheritance: nothing an implementor reads on IOutboxStore reaches this member. A store MUST NOT dead-letter a message that is already sent or already dead-lettered, and that binds a report from the CURRENT claim holder exactly as it binds a stale one. Dead-lettering a delivered message records a delivery failure that did not happen; repeating it writes a second dead-letter row for one message, and either redrive then produces a duplicate.

Clearing the delivery lease is not hygiene — it is load-bearing and it cuts both ways. It stops a stale sweep resurrecting the message, and it also removes the only evidence a LATER completion could be judged against, so an ownership guard alone cannot protect this row afterwards. The terminal-status obligation above is what remains, which is why it is stated and not implied.

THE REFUSAL IS REPORTED, NEVER THROWN, AND THE CALLER MUST TEST FOR Applied BY NAME. Every guard an implementation runs here — the row is gone, the row is already terminal, the lease belongs to someone else — ends in a write that did not happen, and the caller has already written the dead-letter entry by the time it asks. A refusal it cannot see leaves the message simultaneously delivered by the live claimant and sitting unreplayed in the dead-letter queue, where a redrive re-executes a message that already succeeded. Deciding success by excluding the refusals instead makes every member added later a success, which is the direction this contract must never fail.

Reachable outcomes. Applied when the row was mutated; MessageNotFound when no row matched; AlreadyTerminal when the row was already sent or already dead-lettered; ClaimLost when the store holds a delivery lease for a different owner. FenceRefused is NOT reachable — this member carries no fencing token, so an implementation returning it would report a judgement it was given no means to make. Unknown must never be returned by a store; it exists so that a default or unset value cannot read as success.

Exceptions

ArgumentException

Thrown when messageId is null or empty.

ArgumentOutOfRangeException

Thrown before mutation when attemptCount is negative.

MarkFailedAsync(string, string, int, string, CancellationToken)

Records a delivery failure reported by the claim identified by claimIdentity.

public ValueTask<OutboxCompletionOutcome> MarkFailedAsync(string messageId, string errorMessage, int retryCount, string claimIdentity, CancellationToken cancellationToken)

Parameters

messageId string

The unique identifier of the message that failed.

errorMessage string

The error describing the failure.

retryCount int

The absolute attempt count for this message.

claimIdentity string

The claim under which the caller received this message, from DispatcherId.

cancellationToken CancellationToken

Token to monitor for cancellation requests.

Returns

ValueTask<OutboxCompletionOutcome>

What the store did, decided by the same atomic action that performed the mutation.

Remarks

Implementations MUST evaluate the claim and the mutation in ONE atomic action, and MUST decide whether to refuse from that same action. A store that reconstructs the decision from a separate read compares a value captured before the window it must describe, which is false exactly when the refusal is real.

A refusal is REPORTED, not thrown, and the reason is the caller's control flow rather than style. The drain reports a delivery failure from inside its own exception handler; an exception raised there is not caught by a sibling catch on the same try, so it escapes the whole cycle and abandons every message the caller still holds. The refusal must cost one message, so it travels in the return value where the caller reads it without unwinding.

A refusal here is ROW-LEVEL, and the distinction decides how much work is abandoned. A fence refusal means a NEWER TENURE exists and the whole drain cycle must stop, whereas ClaimLost means only that this message was re-claimed — the caller stops writing for THIS message and continues with the others it still holds. A caller that aborts its cycle on a lost claim abandons messages a live tenure owns.

Exceptions

ArgumentException

Thrown when messageId is null or empty.

MarkFailedAsync(string, string, int, CancellationToken)

Marks a message as failed during delivery.

public ValueTask MarkFailedAsync(string messageId, string errorMessage, int retryCount, CancellationToken cancellationToken)

Parameters

messageId string

The unique identifier of the message that failed.

errorMessage string

The error description or exception message.

retryCount int

The current retry attempt count.

cancellationToken CancellationToken

Token to monitor for cancellation requests.

Returns

ValueTask

A task representing the asynchronous mark-failed operation.

Remarks

A failure is a delay, not an ending. The message stays owed delivery, and three conditions hold together to keep that true without turning it into a retry loop. Each is stated because a store can satisfy the other two and still be wrong.

The message is withheld, then returned. It does not become claimable again immediately -- an immediate re-claim is a zero-backoff loop that saturates the transport against a destination that is failing anyway -- and it does become claimable once the store's failure-backoff floor has elapsed. The floor is measured from the recorded failure, not from a claim lease: a message that failed without ever being claimed has no lease, and a floor derived from one would yield nothing for it. Withholding it permanently satisfies the first half and silently drops the message, so both halves are required.

A report from a dispatcher that no longer holds the claim is a no-op rather than an error -- it is stale, not invalid. Honouring it would release a claim its successor is still delivering under, and both would then send the same message. A message that was never claimed has no owner and is reported freely. The guard must not be satisfied by refusing everybody -- the owner's own report still has to land, or the store cannot record failures at all.

HOW FINELY "no longer holds the claim" IS JUDGED VARIES BY STORE, AND THIS MEMBER DOES NOT PROMISE PER-CLAIM PRECISION. An earlier wording here said only the claim's owner may report against it, which reads as a per-claim guarantee that no shipped store keeps through this member. What the shipped stores actually compare is a per-PROCESS identity, so two successive claims by the same process are indistinguishable to it: a report from an expired claim of a still-running dispatcher is accepted, and it releases a reservation a live successor of that same process still holds.

THE FLOOR A CALLER MAY RELY ON, stated because "varies by store" is not a contract. Every shipped store that offers this member refuses a report against a message currently held by a DIFFERENT dispatcher process, and admits one against a message nobody holds. That is the floor, and it is uniform: what varies above it is only whether a store can also distinguish two claim cycles of the SAME process, and none of them can through this member. An implementor of this interface is required to meet the floor; a store that matches on the message identifier alone does not implement this member's contract, however well it records the identity elsewhere.

The floor is expressed differently by different data models -- a prefix of a stored claim token, an equality against a configured processor identity, a conditional script, an in-process comparison -- and the obligation is the property, not the mechanism. Note what the floor deliberately does NOT require: an "ownership term" a caller can satisfy by omitting the value it guards is not a guard, so a store whose only option would be such a predicate must instead offer the claim-scoped member below and refuse here, rather than carry a predicate with a hole in it.

For a completion judged against the specific claim the caller holds, use IClaimScopedOutboxStore. It takes the claim identity as an argument and returns an outcome saying whether the store applied the completion or refused it, so a caller whose claim has lapsed is told rather than silently succeeding. Discover it with GetService(Type) rather than a cast: a cast sees only the outermost type and is lossy through any decorator. Not every store implements it; a caller that needs the guarantee should check, because the fallback to this member is the weaker comparison described above.

The recorded attempt count never decreases. Implementations record the greater of the stored count and retryCount. The ceiling that eventually gives up on a message is driven by that count, so a late report carrying a lower number would push the ceiling further away each time one arrived, and the message would be retried without end.

Marking a message that does not exist is a silent no-op. A message in a terminal state is never reopened by a late failure report, and terminal means delivered or dead-lettered -- in both, the decision to stop delivering has already been taken and recorded. Guarding only the delivered state is the error this wording exists to prevent: a reopened dead-lettered message re-enters the retry population it was deliberately removed from. A message merely in flight is not terminal, and a failure report against one must land -- that is the ordinary path this method exists to serve.

The ownership condition above cannot carry this guarantee, and a store that relies on it will be wrong. Dead-lettering releases the delivery lease, so a dead-lettered message presents as never-claimed and is therefore reported freely by that rule. The terminal-state check is required in its own right and applies unconditionally.

The obligation is the property, not the mechanism. A store satisfies it however its data model allows: a status term in the mutation's own predicate, a terminal transition that removes the row so no later report can match it, a claim record stamped with an identity no caller can present, or a claimable predicate keyed on a field the failure path never writes. What is required is that a late report cannot reopen a terminal message -- not that any particular column be tested.

Exceptions

ArgumentException

Thrown when messageId is null or empty.

ArgumentNullException

Thrown when errorMessage is null.

MarkFailedWithBackoffAsync(string, string, int, DateTimeOffset, string, CancellationToken)

Records a delivery failure reported by the claim identified by claimIdentity, applying the per-message backoff schedule.

public ValueTask<OutboxCompletionOutcome> MarkFailedWithBackoffAsync(string messageId, string errorMessage, int retryCount, DateTimeOffset nextAttemptAt, string claimIdentity, CancellationToken cancellationToken)

Parameters

messageId string

The unique identifier of the message that failed.

errorMessage string

The error describing the failure.

retryCount int

The absolute attempt count for this message.

nextAttemptAt DateTimeOffset

The time before which the message must NOT be re-claimed.

claimIdentity string

The claim under which the caller received this message, from DispatcherId.

cancellationToken CancellationToken

Token to monitor for cancellation requests.

Returns

ValueTask<OutboxCompletionOutcome>

What the store did, decided by the same atomic action that performed the mutation.

Remarks

This member exists because the backoff route is the one a genuine delivery failure takes when automatic retry is enabled. Scoping only the plain completion would leave the dominant failure path unscoped while the capability appeared to close it. The same atomicity and reported-refusal requirements as MarkFailedAsync(string, string, int, string, CancellationToken) apply here in full.

Exceptions

ArgumentException

Thrown when messageId is null or empty.

MarkFailedWithBackoffAsync(string, string, int, DateTimeOffset, CancellationToken)

Marks a message as failed and records the time before which it must NOT be re-claimed for retry, applying the per-message backoff schedule.

public ValueTask MarkFailedWithBackoffAsync(string messageId, string errorMessage, int retryCount, DateTimeOffset nextAttemptAt, CancellationToken cancellationToken)

Parameters

messageId string

The unique identifier of the message that failed.

errorMessage string

The error description or exception message.

retryCount int

The current retry attempt count.

nextAttemptAt DateTimeOffset

The caller-computed earliest next attempt, typically now + IBackoffCalculator.CalculateDelay(attempt). A LOWER bound requested by the caller, not the final schedule: the store composes it with its own floor F and persists whichever is later, so this value can defer the next attempt beyond F but can never bring it inside F.

cancellationToken CancellationToken

Token to monitor for cancellation requests.

Returns

ValueTask

A task that represents the asynchronous mark-failed-with-backoff operation.

Remarks

After this call, the message MUST NOT be returned by the claim predicate (GetUnsentMessagesAsync(int, CancellationToken)) until nextAttemptAt has elapsed, so the computed backoff delay genuinely throttles re-delivery.

Implementors: compose, do not substitute. The persisted next-attempt time MUST be the LATER of nextAttemptAt and the store's own configured failure-backoff floor F — the same floor the plain MarkFailedAsync(string, string, int, CancellationToken) path applies. Binding the caller's instant verbatim is a defect, not a permitted simplification: the default backoff calculator yields on the order of a second at the first attempt, so a store that substitutes rather than composes makes this capability WEAKEN the guarantee it exists to strengthen — the identical failure waits F without the capability and about a second with it.

Compose with a maximum rather than a conditional, so relaxing the floor below F is not something ordinary use can express. Compute the floor term on whichever clock the store's own claim predicate compares against — the database server's where the store has one, the injected TimeProvider where the store is deliberately client-clocked — so the composition introduces no clock the provider was not already trusting.

Exceptions

ArgumentException

Thrown when messageId is null or empty.

ArgumentNullException

Thrown when errorMessage is null.

MarkSentAsync(string, string, CancellationToken)

Marks a message sent only while the caller holds the current claim.

public ValueTask<OutboxCompletionOutcome> MarkSentAsync(string messageId, string claimIdentity, CancellationToken cancellationToken)

Parameters

messageId string

The persisted message identifier captured at acquisition.

claimIdentity string

The immutable acquisition evidence captured before delivery.

cancellationToken CancellationToken

Token to monitor for cancellation requests.

Returns

ValueTask<OutboxCompletionOutcome>

The outcome decided atomically with the guarded terminal transition.

Remarks

Missing or released leases return ClaimLost. Validate nonblank identifiers before mutation. A fenced authority additionally requires a positive tenure; evaluate its fence before row-level outcomes. Retained terminal rows return AlreadyTerminal. Never infer the outcome from a later read.

MarkSentAsync(string, CancellationToken)

Marks a message as successfully sent.

public ValueTask MarkSentAsync(string messageId, CancellationToken cancellationToken)

Parameters

messageId string

The unique identifier of the message to mark as sent.

cancellationToken CancellationToken

Token to monitor for cancellation requests.

Returns

ValueTask

A task representing the asynchronous mark-sent operation.

Remarks

This mutation is unfenced. A store that can enforce leadership fencing implements IFencedOutboxStore.

Exceptions

ArgumentException

Thrown when messageId is null or empty.

InvalidOperationException

Thrown when the message does not exist or is already marked as sent.

StageMessageAsync(OutboundMessage, CancellationToken)

Stages a message in the outbox for later delivery.

public ValueTask StageMessageAsync(OutboundMessage message, CancellationToken cancellationToken)

Parameters

message OutboundMessage

The outbound message to stage.

cancellationToken CancellationToken

Token to monitor for cancellation requests.

Returns

ValueTask

A task representing the asynchronous stage operation.

Exceptions

ArgumentNullException

Thrown when message is null.

InvalidOperationException

Thrown when a message with the same ID already exists.