Table of Contents

Class SqlServerDeadLetterQueue

Namespace
Excalibur.Outbox.SqlServer
Assembly
Excalibur.Outbox.SqlServer.dll

SQL Server implementation of IDeadLetterQueue for production scenarios.

public sealed class SqlServerDeadLetterQueue : IDeadLetterQueue, IDeadLetterQueueAdmin
Inheritance
SqlServerDeadLetterQueue
Implements
Inherited Members

Remarks

This implementation stores dead letter entries in SQL Server with full support for filtering, replay, and purge operations. Uses Dapper for data access.

This class supports two constructor patterns:

  • Simple: Options-based for most users
  • Advanced: Connection factory for multi-database, pooling, or IDb integration

Tenancy. This type implements two interfaces and they are scoped differently, so "the dead-letter queue is estate-wide" is true of only one of them. The tenant-facing surface is IDeadLetterQueue — reading entries, counting them, and replaying a single entry — and each of those operations is narrowed to the ambient tenant whenever a tenant context is registered, so an entry belonging to another tenant is not merely hidden from them but unaddressable by them. The operator surface is IDeadLetterQueueAdmin — batch replay, entry purge, and the age-based retention sweep — and each of those operations is deliberately estate-wide, because a platform operator must be able to reach a failed message in whichever tenant holds it. Which reach a caller gets is therefore a registration decision, not an ambient one: a host that does not want estate-wide reach must not inject the admin interface into tenant-facing code.

Each entry carries its originating tenant as provenance: EnqueueAsync<T>(T, DeadLetterReason, CancellationToken, Exception?, IDictionary<string, string>?) stamps the ambient tenant (or the reserved untenanted sentinel when no tenant is in scope) into the TenantId column, and ReplayAsync(Guid, CancellationToken) re-enters that stored tenant — never the caller's — so an operator replaying tenant A's dead letter cannot inject it into a different tenant. The tenant term is retained in storage and used for scoping and for restoring the correct tenant on replay; it is not projected onto DeadLetterEntry, so a caller cannot read an entry's tenant from the returned value and a tenant-facing view cannot be built from what this surface returns.

Constructors

SqlServerDeadLetterQueue(IOptions<SqlServerDeadLetterQueueOptions>, ILogger<SqlServerDeadLetterQueue>, ITenantContext, Func<object, Task>?)

Initializes a new instance of the SqlServerDeadLetterQueue class.

[ActivatorUtilitiesConstructor]
public SqlServerDeadLetterQueue(IOptions<SqlServerDeadLetterQueueOptions> options, ILogger<SqlServerDeadLetterQueue> logger, ITenantContext tenantContext, Func<object, Task>? replayHandler = null)

Parameters

options IOptions<SqlServerDeadLetterQueueOptions>

The configuration options.

logger ILogger<SqlServerDeadLetterQueue>

The logger instance.

tenantContext ITenantContext

The ambient tenant context. Required: this store partitions rows by tenant, and it resolves that partition from here, so there is no state in which the partition is undecided. A single-tenant host receives the framework default context and operates as the one canonical tenant.

replayHandler Func<object, Task>

Optional handler for replaying messages.

Remarks

This is the simple constructor for most users. Use SqlServerDeadLetterQueue(Func<SqlConnection>, SqlServerDeadLetterQueueOptions, ILogger<SqlServerDeadLetterQueue>, ITenantContext, Func<object, Task>?) for advanced scenarios like multi-database setups or custom connection pooling.

SqlServerDeadLetterQueue(Func<SqlConnection>, SqlServerDeadLetterQueueOptions, ILogger<SqlServerDeadLetterQueue>, ITenantContext, Func<object, Task>?)

Initializes a new instance of the SqlServerDeadLetterQueue class with a connection factory.

public SqlServerDeadLetterQueue(Func<SqlConnection> connectionFactory, SqlServerDeadLetterQueueOptions options, ILogger<SqlServerDeadLetterQueue> logger, ITenantContext tenantContext, Func<object, Task>? replayHandler = null)

Parameters

connectionFactory Func<SqlConnection>

A factory function that creates SqlConnection instances. The caller is responsible for ensuring the factory returns properly configured connections.

options SqlServerDeadLetterQueueOptions

The configuration options (used for table names, timeouts, etc.).

logger ILogger<SqlServerDeadLetterQueue>

The logger instance.

tenantContext ITenantContext

The ambient tenant context. Required: this store partitions rows by tenant, and it resolves that partition from here, so there is no state in which the partition is undecided. A single-tenant host receives the framework default context and operates as the one canonical tenant.

replayHandler Func<object, Task>

Optional handler for replaying messages.

Remarks

This is the advanced constructor for scenarios that need custom connection management:

  • Multi-database setups with marker interfaces (e.g., IDomainDb, IDlqDb)
  • Custom connection pooling
  • Integration with IDb abstraction

Methods

EnqueueAsync<T>(T, DeadLetterReason, CancellationToken, Exception?, IDictionary<string, string>?)

Enqueues a message to the dead letter queue.

public Task<Guid> EnqueueAsync<T>(T message, DeadLetterReason reason, CancellationToken cancellationToken, Exception? exception = null, IDictionary<string, string>? metadata = null)

Parameters

message T

The message that failed processing.

reason DeadLetterReason

The reason for dead lettering.

cancellationToken CancellationToken

Cancellation token.

exception Exception

Optional exception that caused the failure.

metadata IDictionary<string, string>

Optional additional metadata. A nonblank MessageType supplies the original identity; otherwise the runtime type's declared name is used, or an empty identity when unknown.

Returns

Task<Guid>

The ID of the created dead letter entry.

Type Parameters

T

The type of message being dead lettered.

Remarks

Tenant-scoped: the entry is stored under the ambient tenant. When there is no ambient tenant the entry is stored untenanted and remains addressable only through IDeadLetterQueueAdmin. Missing message-name declarations do not prevent failure capture. An unknown identity is not reconstructed from a CLR type name; replay remains the configured handler's responsibility.

GetAllTenantsEntriesAsync(DeadLetterQueryFilter?, CancellationToken)

Retrieves dead letter entries belonging to every tenant.

public Task<IReadOnlyList<DeadLetterEntry>> GetAllTenantsEntriesAsync(DeadLetterQueryFilter? filter, CancellationToken cancellationToken)

Parameters

filter DeadLetterQueryFilter

Selects the entries to return, and carries the page size through Take. The selection is not narrowed by the ambient tenant. Pass null for the defaults.

cancellationToken CancellationToken

Cancellation token.

Returns

Task<IReadOnlyList<DeadLetterEntry>>

The matching entries, drawn from every tenant partition.

Remarks

The operator counterpart to GetEntriesAsync(CancellationToken, DeadLetterQueryFilter?, int), which is confined to the caller's own partition. Entries carry the failed message body and DeadLetterEntry exposes no tenant discriminator, so results from different tenants cannot be told apart by the caller: treat anything obtained here as privileged and never surface it to a tenant-facing view.

The name is the safety control. Estate-wide reach is spelled at the call site, never inferred from a scope nobody established — the same discipline as PurgeAllTenantsEntriesOlderThanAsync(TimeSpan, CancellationToken). A caller cannot arrive here by forgetting to set a tenant, which is the shape that fails open.

An optional capability whose default implementation throws. A store that supports it overrides this method; a decorator must override it to forward to its inner store, or a decorated store reports the capability as missing even though the store underneath supports it.

Exceptions

NotSupportedException

Thrown by stores that do not support estate-wide inspection.

GetAllTenantsEntryAsync(Guid, CancellationToken)

Retrieves a single dead letter entry from whichever tenant holds it.

public Task<DeadLetterEntry?> GetAllTenantsEntryAsync(Guid entryId, CancellationToken cancellationToken)

Parameters

entryId Guid

The unique identifier of the entry.

cancellationToken CancellationToken

Cancellation token.

Returns

Task<DeadLetterEntry>

The entry, or null when no tenant holds one with that identifier.

Remarks

The operator counterpart to GetEntryAsync(Guid, CancellationToken), which resolves the entry only within the caller's own partition and reports not-found for another tenant's. Identifiers are allocated per entry and are not reused across tenants, so at most one row can match.

The same privilege and naming notes as GetAllTenantsEntriesAsync(DeadLetterQueryFilter?, CancellationToken) apply, and this is likewise an optional capability whose default implementation throws.

Exceptions

NotSupportedException

Thrown by stores that do not support estate-wide inspection.

GetCountAsync(CancellationToken, DeadLetterQueryFilter?)

Gets the current count of entries in the dead letter queue.

public Task<long> GetCountAsync(CancellationToken cancellationToken, DeadLetterQueryFilter? filter = null)

Parameters

cancellationToken CancellationToken

Cancellation token.

filter DeadLetterQueryFilter

Optional filter to count specific entries.

Returns

Task<long>

The number of entries matching the filter criteria.

Remarks

Tenant-scoped: counts none of another tenant's entries, and every one of the caller's own that matches filter, so the number does not disclose another tenant's failure volume nor undercount the caller's own. The tenant term is taken from the registered tenant context, never from filter.

Fails closed: when multi-tenancy is registered but resolves no tenant, this raises TenantRequiredException rather than counting across tenants. With no tenant context registered at all, the count binds the reserved untenanted partition.

GetEntriesAsync(CancellationToken, DeadLetterQueryFilter?, int)

Retrieves dead letter entries based on filter criteria.

public Task<IReadOnlyList<DeadLetterEntry>> GetEntriesAsync(CancellationToken cancellationToken, DeadLetterQueryFilter? filter = null, int limit = 100)

Parameters

cancellationToken CancellationToken

Cancellation token.

filter DeadLetterQueryFilter

Optional filter for querying entries. If null, returns all entries up to the limit.

limit int

Maximum number of entries to return.

Returns

Task<IReadOnlyList<DeadLetterEntry>>

A read-only list of dead letter entries matching the criteria.

Remarks

Tenant-scoped: returns none of another tenant's entries, and every one of the caller's own that matches filter. The tenant term is taken from the registered tenant context, never from filter, so a caller cannot widen this read by omitting a tenant nor redirect it by naming another one.

Fails closed: when multi-tenancy is registered but resolves no tenant, this raises TenantRequiredException rather than returning entries across tenants. With no tenant context registered at all, the read binds the reserved untenanted partition.

GetEntryAsync(Guid, CancellationToken)

Retrieves a specific dead letter entry by its ID.

public Task<DeadLetterEntry?> GetEntryAsync(Guid entryId, CancellationToken cancellationToken)

Parameters

entryId Guid

The unique identifier of the entry.

cancellationToken CancellationToken

Cancellation token.

Returns

Task<DeadLetterEntry>

The dead letter entry if found, null otherwise.

Remarks

Tenant-scoped: resolves the caller's own entry for entryId when one exists, and an entry stored under another tenant is reported as not found. An identifier alone does not address an entry — it is addressed by identifier within the ambient tenant, so holding an entry id obtained from a log line, an export, or a correlation trail does not grant access to it.

Fails closed: when multi-tenancy is registered but resolves no tenant, this raises TenantRequiredException rather than resolving the entry unscoped. With no tenant context registered at all, the lookup binds the reserved untenanted partition.

PurgeAllTenantsEntriesOlderThanAsync(TimeSpan, CancellationToken)

Purges all dead letter entries older than the specified age.

public Task<int> PurgeAllTenantsEntriesOlderThanAsync(TimeSpan olderThan, CancellationToken cancellationToken)

Parameters

olderThan TimeSpan

The minimum age an entry must have reached to be purged.

cancellationToken CancellationToken

Cancellation token.

Returns

Task<int>

The number of entries purged.

Remarks

Estate-wide and irreversible: deletes matching entries in every tenant on an age predicate alone. There is no tenant term in the selection, so a host that exposes this operation to a tenant-facing caller lets one tenant delete another's failed messages.

PurgeAsync(Guid, CancellationToken)

Purges a dead letter entry.

public Task<bool> PurgeAsync(Guid entryId, CancellationToken cancellationToken)

Parameters

entryId Guid

The unique identifier of the entry to purge.

cancellationToken CancellationToken

Cancellation token.

Returns

Task<bool>

True if an entry was purged; false if no entry matched.

Remarks

Estate-wide: addresses the entry in whichever tenant holds it, not only the ambient tenant.

ReplayAllTenantsEntryAsync(Guid, CancellationToken)

Replays a single dead letter entry held by any tenant.

public Task<bool> ReplayAllTenantsEntryAsync(Guid entryId, CancellationToken cancellationToken)

Parameters

entryId Guid

The unique identifier of the entry to replay.

cancellationToken CancellationToken

Cancellation token.

Returns

Task<bool>

true when an entry was replayed; false when none matched.

Remarks

The single-entry counterpart to ReplayBatchAsync(DeadLetterQueryFilter, int, CancellationToken), which is already estate-wide, and the operator counterpart to ReplayAsync(Guid, CancellationToken).

Scope governs which entry may be addressed; it never governs where the message lands. A replayed message re-enters the tenant its entry was stored under, never the operator's own, so replaying another tenant's entry cannot inject it into the caller's tenant. An entry stored without a tenant re-enters untenanted.

Likewise an optional capability whose default implementation throws.

Exceptions

NotSupportedException

Thrown by stores that do not support estate-wide replay.

ReplayAsync(Guid, CancellationToken)

Replays a dead letter entry, re-submitting it for processing.

public Task<bool> ReplayAsync(Guid entryId, CancellationToken cancellationToken)

Parameters

entryId Guid

The unique identifier of the entry to replay.

cancellationToken CancellationToken

Cancellation token.

Returns

Task<bool>

true when this call replayed the entry; false when it did not.

Remarks

A replay happens at most once per entry, and the return says whether it was THIS call that performed it. An implementation claims the entry before invoking the handler, so of several concurrent callers exactly one replays and the others return false. A false therefore carries three distinct situations and does not separate them: no such entry; the entry was already replayed; or another caller claimed it first. Treat it as "not replayed by me" rather than as "not found".

A handler that throws propagates, and the claim is released so the entry can be replayed again — a transient downstream failure does not consume the entry.

Known gap. If the process stops between claiming an entry and delivering it, or if releasing the claim after a failed handler does not succeed, the entry is left marked replayed without having been delivered — and that state cannot be told apart from a replay that succeeded, because the entry carries the same flag either way. The lost replay is bounded: it affects the one entry, and no later batch re-delivers it. The remaining signal is a logged warning, so treat a replay that reported an error as needing confirmation from your own handler's effects rather than from the entry's state.

Tenant-scoped: only an entry stored under the ambient tenant is replayable, and another tenant's entry is reported as not found. Fails closed: when multi-tenancy is registered but resolves no tenant, this raises TenantRequiredException rather than replaying unscoped.

The replay target is enforced and is a separate property: a replayed message always re-enters the tenant its entry was stored under, never the caller's, so a replay cannot inject another tenant's message into the caller's own tenant.

ReplayBatchAsync(DeadLetterQueryFilter, int, CancellationToken)

Replays multiple dead letter entries matching the filter.

public Task<ReplayBatchResult> ReplayBatchAsync(DeadLetterQueryFilter filter, int limit, CancellationToken cancellationToken)

Parameters

filter DeadLetterQueryFilter

Selects the entries to replay. The selection is not narrowed by the ambient tenant.

limit int

The maximum number of entries this call may take. Required: the batch size governs how much work a single operator action performs, so it is the caller's to state rather than an implementation's to assume.

cancellationToken CancellationToken

Cancellation token.

Returns

Task<ReplayBatchResult>

A ReplayBatchResult reporting how many entries were enumerated, how many were replayed, and whether limit cut the selection short.

Remarks

Estate-wide: selects across every tenant. Each replayed message re-enters the tenant its entry was stored under, so a batch spanning several tenants restores each message to its own.

A partial batch is reported, never silent: when the limit is reached, Truncated is true and the caller must re-run to drain the remainder. The result is not a bare count, so "this many were replayed" can no longer be mistaken for "every entry matching the filter was replayed".