Interface IInboxStore
Provides persistent storage for incoming messages to ensure at-most-once processing semantics.
public interface IInboxStore
- Extension Methods
Remarks
The inbox store implements the Idempotent Consumer pattern by persistently tracking processed messages
before handler execution. Within one tenant scope, messages are keyed by a composite of
(messageId, handlerType), allowing the same message to be processed independently by multiple
handlers.
This ensures:
- Duplicate detection - each handler processes a message at most once
- Resilience - processing state survives application restarts
- Consistency - messages are marked processed only after successful handling
- Audit trail - complete processing history is maintained
- Multi-handler support - different handlers can process the same message independently
Durability fault model. Every mutating operation is fail-loud: a successful (non-faulted) return guarantees the corresponding state change was durably recorded before the returned task completed, and a persistence failure is surfaced as a thrown exception — never swallowed as a silent no-op. Callers may therefore treat a completed MarkProcessedAsync(string, string, CancellationToken) / TryMarkAsProcessedAsync(string, string, CancellationToken) as proof that the dedup record is persisted, so at-least-once redelivery combined with an idempotent handler yields at-most-once effects even across a process crash.
Ownership. Every member here resolves (messageId, handlerType) within the caller's
current tenant scope. That scope is ambient rather than a parameter — no method on this interface
takes a tenant argument — so the logical dedup identity is (tenant scope, messageId, handlerType).
An implementation MUST NOT let one scope observe, claim, or mutate another scope's record: a record owned
by a different tenant is invisible to every member of this interface, exactly as if it did not exist.
Reporting an existing record on the strength of another tenant's row would make the host acknowledge a
message it never handled — a silent loss, not a duplicate.
Two registrations satisfy that requirement. Registered without multi-tenancy, the store is the
scope: one untenanted namespace keyed by (messageId, handlerType). Registered with multi-tenancy,
the tenant is part of the store's unique key and is never absent. A provider that cannot apply the ambient
tenant is refused when multi-tenancy is registered, rather than degrading silently at runtime, so a caller
may rely on the guarantee above without knowing which provider is wired.
Interface uses ValueTask for synchronous completion optimization. In-memory implementations complete synchronously without allocation overhead.
The tenant obligation above is declared at this contract, not only named in the composition-time gate. The order-independent startup re-assertion selects its subjects by that declaration, so a contract covered only by a sweep of the service collection taken at the instant multi-tenancy is registered is not covered against a store registered afterwards -- an ordinary arrangement when persistence is added by a later feature module.
Methods
CreateEntryAsync(string, string, string, byte[], IDictionary<string, object>, CancellationToken)
Creates a new inbox entry for an incoming message and handler combination.
ValueTask<InboxEntry> CreateEntryAsync(string messageId, string handlerType, string messageType, byte[] payload, IDictionary<string, object> metadata, CancellationToken cancellationToken)
Parameters
messageIdstringThe unique identifier of the message.
handlerTypestringThe deduplication scope the entry is keyed under, together with
messageId. See HandlerType.messageTypestringA type name for the message that the message type registry can resolve. See MessageType.
payloadbyte[]The serialized message payload.
metadataIDictionary<string, object>Additional message metadata including headers and context.
cancellationTokenCancellationTokenToken to monitor for cancellation requests.
Returns
- ValueTask<InboxEntry>
The created inbox entry with generated timestamps and initial status.
Exceptions
- ArgumentException
Thrown when messageId, handlerType, or messageType is null or empty.
- ArgumentNullException
Thrown when payload or metadata is null.
- InvalidOperationException
Thrown when an entry with the same (messageId, handlerType) already exists.
GetEntryAsync(string, string, CancellationToken)
Retrieves an inbox entry by message identifier and handler type.
ValueTask<InboxEntry?> GetEntryAsync(string messageId, string handlerType, CancellationToken cancellationToken)
Parameters
messageIdstringThe unique identifier of the message to retrieve.
handlerTypestringThe deduplication scope the entry is keyed under, together with
messageId. See HandlerType.cancellationTokenCancellationTokenToken to monitor for cancellation requests.
Returns
- ValueTask<InboxEntry>
The inbox entry if found; otherwise,
null.
Exceptions
- ArgumentException
Thrown when messageId or handlerType is null or empty.
IsProcessedAsync(string, string, CancellationToken)
Checks if a message has already been processed by a specific handler.
ValueTask<bool> IsProcessedAsync(string messageId, string handlerType, CancellationToken cancellationToken)
Parameters
messageIdstringThe unique identifier of the message to check.
handlerTypestringThe deduplication scope the entry is keyed under, together with
messageId. See HandlerType.cancellationTokenCancellationTokenToken to monitor for cancellation requests.
Returns
- ValueTask<bool>
trueif the message has been processed by this handler in the caller's tenant scope; otherwise,false. A record owned by another tenant never yieldstrue.
Exceptions
- ArgumentException
Thrown when messageId or handlerType is null or empty.
MarkFailedAsync(string, string, string, CancellationToken)
Marks a message as failed during processing for a specific handler, and reports whether the entry was actually mutated.
ValueTask<InboxMarkFailedOutcome> MarkFailedAsync(string messageId, string handlerType, string errorMessage, CancellationToken cancellationToken)
Parameters
messageIdstringThe unique identifier of the message that failed.
handlerTypestringThe deduplication scope the entry is keyed under, together with
messageId. See HandlerType.errorMessagestringThe error description or exception message.
cancellationTokenCancellationTokenToken to monitor for cancellation requests.
Returns
- ValueTask<InboxMarkFailedOutcome>
Applied when the entry was mutated; EntryNotFound when no such entry exists in the caller's tenant scope; AlreadyProcessed when the entry is present but terminal and the transition was refused; Undecided when the store was asked, wrote nothing, and could not reach a decision — characteristically an exhausted optimistic-concurrency loop. Treat anything other than Applied as not applied.
Remarks
The transition can be refused, so it is reported rather than thrown. Processed is absorbing: an entry that already completed must not be demoted to failed, because that would re-admit it to the drain and run its handler again over side effects already committed. A refusal is therefore an ordinary and expected answer on this path, not a fault.
An absent entry returns EntryNotFound and MUST NOT throw. A store that throws here cannot be substituted for one that does not: a caller written to catch is broken against the silent stores and a caller written not to is broken against the throwing ones, so no caller can be correct against the interface.
THROW ONLY WHEN THE STORE COULD NOT BE ASKED. That is the rule, and it is stated as a rule rather than as a list of examples because a list invites the next case to be fitted into the nearest entry. If the store answered — including answering that it could not decide — the answer is a return value. If the store could not be reached, or the statement could not be issued, that is an exception.
The case that makes the distinction concrete is contention. A store whose transition needs an optimistic-concurrency loop can lose every attempt to a competing writer. It was asked, it answered, and nothing was written, so it returns Undecided and does not throw — the entry is exactly as it was found and the call is safe to re-drive. Throwing there is actively harmful: this member is normally called while the caller is already handling a failure, so an exception raised here replaces the consumer's original error with one about the store.
The outcome is decided by the statement that performs the write, never by a read taken afterwards. Classifying from a follow-up read reintroduces the very race the outcome exists to remove: between the write and the read another worker can complete the entry, and the caller is then told a refusal that did not happen, or an application that did not.
Exceptions
- ArgumentException
Thrown when messageId or handlerType is null or empty.
- ArgumentNullException
Thrown when errorMessage is null.
MarkProcessedAsync(string, string, CancellationToken)
Marks a message as successfully processed for a specific handler.
ValueTask MarkProcessedAsync(string messageId, string handlerType, CancellationToken cancellationToken)
Parameters
messageIdstringThe unique identifier of the message to mark as processed.
handlerTypestringThe deduplication scope the entry is keyed under, together with
messageId. See HandlerType.cancellationTokenCancellationTokenToken to monitor for cancellation requests.
Returns
- ValueTask
A task that represents the asynchronous mark-processed operation.
Remarks
When this operation completes without faulting, the processed marker is guaranteed to be durably persisted. A persistence failure MUST propagate as a thrown exception; the operation MUST NOT return successfully while leaving the marker unrecorded (a silent no-op would break dedup across a crash).
Exceptions
- ArgumentException
Thrown when messageId or handlerType is null or empty.
- InvalidOperationException
Thrown when the entry does not exist or is already processed.
TryMarkAsProcessedAsync(string, string, CancellationToken)
Atomically attempts to mark a message as processed for a specific handler.
ValueTask<bool> TryMarkAsProcessedAsync(string messageId, string handlerType, CancellationToken cancellationToken)
Parameters
messageIdstringThe unique identifier of the message.
handlerTypestringThe deduplication scope the entry is keyed under, together with
messageId. See HandlerType.cancellationTokenCancellationTokenToken to monitor for cancellation requests.
Returns
- ValueTask<bool>
trueif this call created the entry and is therefore the recorded first writer for this message and handler in the caller's tenant scope;falseif a durable record already exists in that same scope, in which case the caller MUST NOT treat itself as the first writer.falsedoes not identify who wrote the record. It may have been another delivery, or it may have been an earlier attempt by this same caller whose commit succeeded but whose response was lost and which the provider then retried. The record carries no writer identity, so the two cases are indistinguishable here. Readfalseas "a record exists — do not claim first-writer status", never as "someone else has already done the work, so this caller may skip it".
Remarks
This method provides atomic "first writer wins" semantics for idempotent message processing.
If no record exists for this message and handler, it creates the entry and returns true.
If one already exists, it returns false without throwing.
This is the preferred method for idempotent message handling as it combines the check-and-mark operation atomically, preventing race conditions in concurrent processing scenarios.
The bool result is only returned once the atomic claim has been durably persisted:
a true result guarantees this caller is the recorded first writer, and a false result
guarantees an existing durable record for this handler in the caller's own tenant scope —
never a record owned by another tenant. A persistence failure MUST throw rather than return a value, so
the boolean decision is never backed by unpersisted state.
Exceptions
- ArgumentException
Thrown when messageId or handlerType is null or empty.