Interface IOutboxDispatcher
Defines the outbox dispatcher contract for reliable message publishing with transactional guarantees.
public interface IOutboxDispatcher : IAsyncDisposable
- Inherited Members
- Extension Methods
Remarks
The outbox dispatcher orchestrates background processing and publishing of messages stored in the outbox. This is the orchestration layer interface for the outbox pattern, coordinating message dispatch to external systems.
Pattern Benefits:
- Guarantees at-least-once delivery semantics
- Maintains transactional consistency between data and messages
- Provides resilience against network failures and external system outages
- Enables idempotent message processing through deduplication
- Supports message ordering and retry mechanisms.
Implementation Strategy:
- Business operations save data and messages in a single database transaction
- A background dispatcher polls for pending messages and publishes them
- Successfully published messages are marked as processed or deleted
- Failed messages are retried with exponential backoff.
Operational Considerations:
- Requires reliable background processing for message dispatch
- Should implement appropriate retry policies and dead letter handling
- May need partitioning or sharding for high-throughput scenarios
- Monitoring and alerting are essential for operational visibility.
Methods
GetPendingMessagesAsync(CancellationToken)
Retrieves all pending messages from the outbox that are ready for dispatch.
Task<IEnumerable<IDispatchMessage>> GetPendingMessagesAsync(CancellationToken cancellationToken)
Parameters
cancellationTokenCancellationTokenCancellation token for operation timeout and cancellation support.
Returns
- Task<IEnumerable<IDispatchMessage>>
A task representing the asynchronous operation, with the result containing an enumerable collection of pending dispatch messages.
Remarks
This method provides read-only access to pending outbox messages for monitoring, diagnostics, and manual intervention scenarios. It does not modify message states or reserve messages for processing.
Message Selection Criteria:
Pending messages are typically those that:
- Have not been successfully processed yet
- Are not currently reserved by active dispatchers
- Have not exceeded maximum retry limits
- Are scheduled for immediate or past processing.
Operational Use Cases:
- Health monitoring and alerting on message queue depth
- Troubleshooting and diagnostics for failed message processing
- Manual message inspection and intervention
- Metrics collection and performance analysis.
Performance Considerations:
This operation may return large result sets in high-throughput scenarios. Consider implementing pagination or filtering for production monitoring systems.
RunOutboxDispatchAsync(string, CancellationToken)
Executes a single outbox dispatch cycle, processing pending messages for reliable delivery.
Task<int> RunOutboxDispatchAsync(string dispatcherId, CancellationToken cancellationToken)
Parameters
dispatcherIdstringUnique identifier for the dispatcher instance to enable distributed processing coordination.
cancellationTokenCancellationTokenCancellation token to support graceful shutdown and timeout scenarios.
Returns
- Task<int>
A task representing the asynchronous operation, with the result containing the number of messages successfully processed during this dispatch cycle.
Remarks
This method implements the core outbox processing logic by:
Processing Steps:
- Reserving a batch of pending messages using the dispatcher ID
- Attempting to publish each reserved message to its target destination
- Marking successfully published messages as processed or deleting them
- Updating retry counts and next retry times for failed messages
- Moving messages to dead letter storage after maximum retry attempts.
Concurrency and Distribution:
The dispatcher ID enables multiple instances to process the outbox concurrently without message duplication, supporting horizontal scaling and high availability.
Error Handling:
Transient failures are handled through retry mechanisms with exponential backoff, while permanent failures result in dead letter storage for manual intervention.
Exceptions
- OperationCanceledException
Thrown when the operation is cancelled via the cancellation token.
SaveEventsAsync(IReadOnlyCollection<IIntegrationEvent>, IMessageMetadata, CancellationToken)
Saves integration events to the outbox within the current database transaction scope.
Task SaveEventsAsync(IReadOnlyCollection<IIntegrationEvent> integrationEvents, IMessageMetadata metadata, CancellationToken cancellationToken)
Parameters
integrationEventsIReadOnlyCollection<IIntegrationEvent>Collection of integration events to be saved for eventual publishing.
metadataIMessageMetadataMetadata associated with the events including correlation IDs, timestamps, and routing information.
cancellationTokenCancellationTokenCancellation token for operation timeout and cancellation support.
Returns
- Task
A task representing the asynchronous save operation.
Remarks
This method stores integration events in the outbox table as part of the same database transaction that modifies business data, ensuring transactional consistency and preventing message loss.
Transactional Behavior:
The save operation must execute within an active database transaction context. If the transaction is rolled back, the saved events will also be rolled back, maintaining consistency between business operations and message publishing.
Event Processing:
Events are serialized and stored with appropriate metadata including:
- Event type and version information for deserialization
- Correlation and causation IDs for distributed tracing
- Timestamps for processing order and debugging
- Routing keys and headers for proper delivery.
Performance Considerations:
Batch saving multiple events in a single operation is more efficient than individual saves, reducing database round trips and transaction overhead.
Exceptions
- ArgumentNullException
Thrown when integrationEvents or metadata is null.
- InvalidOperationException
Thrown when not executed within an active transaction context.
SaveMessagesAsync(ICollection<IOutboxMessage>, CancellationToken)
Saves pre-constructed outbox messages directly to the outbox store.
Task<int> SaveMessagesAsync(ICollection<IOutboxMessage> outboxMessages, CancellationToken cancellationToken)
Parameters
outboxMessagesICollection<IOutboxMessage>Collection of fully prepared outbox messages ready for storage.
cancellationTokenCancellationTokenCancellation token for operation timeout and cancellation support.
Returns
- Task<int>
A task representing the asynchronous operation, with the result containing the number of messages successfully saved to the outbox.
Remarks
This method provides direct control over outbox message creation and storage, suitable for advanced scenarios where custom message formatting or routing logic is required.
Use Cases:
- Custom message serialization or encryption requirements
- Complex routing scenarios with multiple destinations
- Message transformation or enrichment logic
- Integration with external message formats or protocols.
Message Validation:
The implementation should validate that messages have required fields populated including message body, type information, and routing details before storage.
Transactional Context:
Like SaveEventsAsync, this operation should execute within an active database transaction to maintain consistency with associated business operations.
Exceptions
- ArgumentNullException
Thrown when outboxMessages is null.
- ArgumentException
Thrown when outboxMessages contains invalid or incomplete message data.