API reference — Reliable messaging
Nuvora.Nexus.Relay.Outbox
Core outbox abstractions and implementations for Nuvora Nexus Relay
dotnet add package Nuvora.Nexus.Relay.Outbox
Nuvora.Nexus.Relay.Outbox
ServiceCollectionExtensions
public static class ServiceCollectionExtensions
Service collection extensions for outbox pattern
Methods
static IServiceCollection AddOutboxProcessor(this IServiceCollection services, Action<OutboxProcessorOptions>? configure = null)
Adds outbox processor with default options
static IServiceCollection AddOutboxProcessor(this IServiceCollection services, IConfiguration configuration)
Adds outbox processor from configuration. Binds the entire "Outbox" section onto OutboxProcessorOptions, so every option (including retry backoff, publish concurrency and the processing lease) is configurable — not just a hand-picked subset.
static IServiceCollection AddRelayMaintenance(this IServiceCollection services, Action<RelayMaintenanceOptions>? configure = null)
Adds the background maintenance service that prunes processed outbox messages and inbox dedup rows. Pruning a store is skipped unless its repository (IOutboxRepository / IInboxRepository) is registered and its retention window is set, so this can be added safely regardless of which transactional-messaging features the app uses.
Nuvora.Nexus.Relay.Outbox.Domain
OutboxMessage
public class OutboxMessage
Represents an integration event stored in the outbox table
Properties
DateTimeOffset CreatedAt { get; set; }
When the message was created in the outbox
DateTimeOffset NextAttemptAt { get; set; }
Earliest time the message is eligible to be (re)processed. Set into the future on failure to implement exponential backoff; defaults to creation time so new messages are immediately due.
DateTimeOffset OccurredAt { get; set; }
When the event occurred
DateTimeOffset? ClaimedAt { get; set; }
When the message was last claimed for processing (null until first claimed). A row stuck in OutboxMessageStatus.Processing whose claim is older than the processing lease is considered stranded (crashed/stopped processor) and becomes eligible for re-claiming.
DateTimeOffset? ProcessedAt { get; set; }
When the event was processed (null if not yet processed)
Guid EventId { get; set; }
The integration event’s unique identifier
Guid Id { get; set; }
Unique identifier for the outbox message
Guid? CausationId { get; set; }
Causation ID for tracing the command that triggered this event
Guid? CorrelationId { get; set; }
Correlation ID for tracing related events across services
Guid? TenantId { get; set; }
Owning tenant (null = global). Stamped from the ambient tenant at write time and propagated to the broker as the tenant-id header so the consumer can re-establish it.
OutboxMessageStatus Status { get; set; }
Current status of the message
int RetryCount { get; set; }
Number of times processing has been attempted
string EventType { get; set; }
Fully qualified type name of the integration event
string Payload { get; set; }
Serialized JSON payload of the integration event
string? ErrorMessage { get; set; }
Error message from the last failure (if any)
OutboxMessageStatus
public enum OutboxMessageStatus
Status of an outbox message
Values
Pending— Message is pending processingProcessing— Message is being processedProcessed— Message has been successfully processed and publishedFailed— Message failed processing and exceeded retry limit (dead letter)
Nuvora.Nexus.Relay.Outbox.HealthChecks
OutboxHealthCheck
public sealed class OutboxHealthCheck : IHealthCheck
Health check over the transactional outbox: reads the live backlog (one aggregate query) and reports Degraded/Unhealthy when delivery lags or dead letters accumulate. Always includes the raw numbers in the health-report data so dashboards get them even when healthy.
Constructors
OutboxHealthCheck(IServiceScopeFactory scopeFactory, IOptions<OutboxHealthCheckOptions> options)
Methods
Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default(CancellationToken))
Runs the health check, returning the status of the component being checked.
OutboxHealthCheckBuilderExtensions
public static class OutboxHealthCheckBuilderExtensions
Health-check registration for the transactional outbox.
Methods
static IHealthChecksBuilder AddRelayOutbox(this IHealthChecksBuilder builder, Action<OutboxHealthCheckOptions>? configure = null, string name = "relay-outbox", IEnumerable<string>? tags = null)
Adds the outbox backlog health check (pending age, dead-letter accumulation). Wire it into the readiness endpoint: services.AddHealthChecks().AddRelayOutbox().
OutboxHealthCheckOptions
public sealed class OutboxHealthCheckOptions
Thresholds for OutboxHealthCheck.
Properties
TimeSpan DegradedPendingAge { get; set; }
Oldest-pending age above which the outbox is reported Degraded (delivery is lagging).
TimeSpan UnhealthyPendingAge { get; set; }
Oldest-pending age above which the outbox is reported Unhealthy (delivery is stuck).
long DegradedDeadLettered { get; set; }
Dead-lettered row count at or above which the outbox is reported Degraded — dead letters require operator action (inspect, fix, requeue) and silently accumulating them defeats the pattern. Set higher if transient dead-lettering is expected and alerted elsewhere.
Nuvora.Nexus.Relay.Outbox.Infrastructure
IOutboxRepository
public interface IOutboxRepository
Repository for managing outbox messages. Writes on the command path (IOutboxRepository.AddAsync/IOutboxRepository.AddManyAsync) enlist in the caller’s ambient transaction so they commit atomically with the aggregate state and events. The processor path (IOutboxRepository.ClaimPendingAsync, IOutboxRepository.MarkAsProcessedAsync, IOutboxRepository.RecordFailureAsync) operates in its own short transactions and is safe to run from multiple instances concurrently (claims must lock rows, e.g. FOR UPDATE SKIP LOCKED).
Methods
Task AddAsync(OutboxMessage message, CancellationToken cancellationToken = default(CancellationToken))
Add a new message to the outbox (enlists in the ambient transaction; not flushed here).
Task AddManyAsync(IEnumerable<OutboxMessage> messages, CancellationToken cancellationToken = default(CancellationToken))
Add multiple messages to the outbox (enlists in the ambient transaction; not flushed here).
Task MarkAsProcessedAsync(Guid messageId, CancellationToken cancellationToken = default(CancellationToken))
Mark a claimed message as successfully processed.
Task<IReadOnlyList<OutboxMessage>> ClaimPendingAsync(int batchSize = 100, CancellationToken cancellationToken = default(CancellationToken))
Atomically claim up to batchSize due messages: rows are locked, marked as OutboxMessageStatus.Processing with a fresh claim timestamp, and returned in a single committed operation so no two instances claim the same message. Eligible rows are OutboxMessageStatus.Pending messages whose NextAttemptAt is due, plus OutboxMessageStatus.Processing rows whose claim is older than the processing lease — i.e. rows stranded by a crashed processor are recovered automatically.
Task<IReadOnlyList<OutboxMessage>> GetFailedMessagesAsync(int batchSize = 100, CancellationToken cancellationToken = default(CancellationToken))
Get messages that have been dead-lettered (for manual review/requeue).
Task<OutboxBacklog> GetBacklogAsync(CancellationToken cancellationToken = default(CancellationToken))
Counts rows by status for monitoring: pending backlog (due or not), in-flight (Processing) and dead-lettered totals, plus the age of the oldest pending row. Cheap aggregate query, intended for health checks and gauges.
Task<OutboxFailureOutcome> RecordFailureAsync(Guid messageId, string errorMessage, int maxRetries, CancellationToken cancellationToken = default(CancellationToken))
Record a processing failure against the live row: increments the retry count, sets the next backoff time, and dead-letters the message once maxRetries is reached. Reading the live row avoids the stale-retry-count bug of deciding from a batch snapshot.
Task<bool> DiscardFailedAsync(Guid messageId, CancellationToken cancellationToken = default(CancellationToken))
Permanently discards (deletes) one dead-lettered message. Operator action for messages that should never be replayed. Returns false when the row does not exist or is not dead-lettered.
Task<bool> RequeueFailedAsync(Guid messageId, CancellationToken cancellationToken = default(CancellationToken))
Requeues one dead-lettered (OutboxMessageStatus.Failed) message: resets its retry count and schedules it for immediate publication. The recovery path after fixing the defect that dead-lettered it. Returns false when the row does not exist or is not dead-lettered.
Task<int> DeleteProcessedMessagesAsync(DateTimeOffset olderThan, CancellationToken cancellationToken = default(CancellationToken))
Delete processed messages older than the specified date (cleanup).
Task<int> DiscardAllFailedAsync(int maxCount = 1000, CancellationToken cancellationToken = default(CancellationToken))
Permanently discards up to maxCount dead-lettered messages. Returns the count deleted.
Task<int> RequeueAllFailedAsync(int maxCount = 100, CancellationToken cancellationToken = default(CancellationToken))
Requeues up to maxCount dead-lettered messages (oldest first), resetting retry counts and scheduling immediate publication. Returns the number requeued.
OutboxBacklog
public sealed record OutboxBacklog : IEquatable<OutboxBacklog>
Aggregate outbox depth counters for health checks and metrics.
Constructors
OutboxBacklog(long Pending, long Processing, long DeadLettered, TimeSpan? OldestPendingAge)
Aggregate outbox depth counters for health checks and metrics.
Properties
TimeSpan? OldestPendingAge { get; init; }
Age of the oldest pending row, or null when none.
long DeadLettered { get; init; }
Rows that exhausted retries (status Failed).
long Pending { get; init; }
Rows waiting to be published (status Pending).
long Processing { get; init; }
Rows currently claimed by a processor.
OutboxFailureOutcome
public enum OutboxFailureOutcome
Outcome of recording a processing failure for an outbox message.
Values
ScheduledForRetry— The message will be retried after its backoff delay.DeadLettered— The message exhausted its retries and was dead-lettered.NotFound— No row with the given id exists (e.g. it was pruned concurrently). Nothing was recorded; callers should log rather than assume a retry was scheduled.
Nuvora.Nexus.Relay.Outbox.Maintenance
RelayMaintenanceOptions
public sealed class RelayMaintenanceOptions
Options for RelayMaintenanceService, the background job that prunes processed outbox and inbox rows so those tables don’t grow without bound.
Properties
TimeSpan Interval { get; set; }
How often a prune pass runs.
TimeSpan StartupDelay { get; set; }
Delay before the first prune pass, so pruning doesn’t compete with application startup.
TimeSpan? InboxRetention { get; set; }
How long to keep inbox dedup rows before deleting them. null disables inbox pruning. Keep this comfortably longer than the broker’s maximum redelivery delay, otherwise a late redelivery could be processed twice after its dedup row was pruned.
TimeSpan? OutboxRetention { get; set; }
How long to keep processed outbox messages before deleting them. null disables outbox pruning. Only messages in the processed state are eligible — pending, in-flight, and dead-lettered rows are never removed by maintenance.
bool Enabled { get; set; }
Whether the maintenance loop runs at all.
RelayMaintenanceService
public sealed class RelayMaintenanceService : BackgroundService
Background service that periodically prunes processed outbox messages and inbox dedup rows so the transactional-messaging tables don’t grow unbounded. Each pass resolves the (scoped) repositories from a fresh DI scope — the service is a singleton, so it must not capture a scoped repository. A repository is only pruned if it is actually registered and its retention window is configured, so this is safe to add whether an app uses the outbox, the inbox, or both. The deletes are plain DELETE ... WHERE processed/created < cutoff statements and are idempotent, so running this on every instance needs no cross-instance coordination.
Constructors
RelayMaintenanceService(IServiceScopeFactory scopeFactory, IOptions<RelayMaintenanceOptions> options, ILogger<RelayMaintenanceService> logger)
Methods
override Task ExecuteAsync(CancellationToken stoppingToken)
This method is called when the IHostedService starts. The implementation should return a task that represents the lifetime of the long running operation(s) being performed.
Nuvora.Nexus.Relay.Outbox.Monitoring
OutboxBacklogMonitor
public sealed class OutboxBacklogMonitor : BackgroundService
Periodically samples the outbox backlog (IOutboxRepository.GetBacklogAsync) into the RelayTelemetry observable gauges — pending depth, dead-letter depth and oldest pending age: the numbers operators alert on. One cheap aggregate query per interval; sampling failures are logged and retried next interval, never propagated.
Constructors
OutboxBacklogMonitor(IServiceScopeFactory scopeFactory, IOptions<OutboxMonitoringOptions> options, ILogger<OutboxBacklogMonitor> logger)
Methods
override Task ExecuteAsync(CancellationToken stoppingToken)
This method is called when the IHostedService starts. The implementation should return a task that represents the lifetime of the long running operation(s) being performed.
OutboxMonitoringOptions
public sealed class OutboxMonitoringOptions
Options for OutboxBacklogMonitor.
Properties
TimeSpan SamplingInterval { get; set; }
How often the outbox backlog is sampled into the gauges.
bool Enabled { get; set; }
Whether backlog sampling runs.
Nuvora.Nexus.Relay.Outbox.Processors
IOutboxProcessor
public interface IOutboxProcessor
Interface for outbox processor (mainly for testing/extensibility)
Methods
Task ProcessPendingMessagesAsync(CancellationToken cancellationToken = default(CancellationToken))
Process pending outbox messages manually (can be called outside of background service)
OutboxProcessor
public class OutboxProcessor : BackgroundService, IOutboxProcessor
Background service that drains the outbox and publishes messages to the message broker. Each cycle resolves the (scoped) IOutboxRepository from a fresh DI scope — the processor itself is a singleton, so it must not capture a scoped repository. Messages are claimed atomically (so multiple instances never publish the same message), published, and then marked processed; failures are recorded against the live row which owns the retry/dead-letter decision.
Constructors
OutboxProcessor(IServiceScopeFactory scopeFactory, IMessageBroker messageBroker, IOptions<OutboxProcessorOptions> options, ILogger<OutboxProcessor> logger, IRelayWakeHub? wakeHub = null)
Methods
Task ProcessPendingMessagesAsync(CancellationToken cancellationToken = default(CancellationToken))
Process pending outbox messages manually (can be called outside of background service)
override Task ExecuteAsync(CancellationToken stoppingToken)
This method is called when the IHostedService starts. The implementation should return a task that represents the lifetime of the long running operation(s) being performed.
OutboxProcessorOptions
public class OutboxProcessorOptions
Configuration options for the outbox processor
Properties
RetryStrategy RetryStrategy { get; set; }
Backoff strategy applied after a failed publish. The default RetryStrategy.Exponential reproduces the historical 2s, 4s, 8s, … curve. Ignored when an IRetryPolicy is registered in DI (that policy then drives the backoff schedule instead).
bool EnableWakeNotifications { get; set; }
Whether staging an outbox row emits a transactional pg_notify (channel relay_outbox) so the processor wakes at commit instead of waiting out a polling interval. Requires the Postgres wake listener (registered by AddRelayEventStoreEfCore). Purely a latency optimization; polling remains the correctness mechanism.
bool Enabled { get; set; }
Whether the processor is enabled
double MaxRetryDelaySeconds { get; set; }
Maximum delay (seconds) between retries (caps the backoff).
double RetryBaseDelaySeconds { get; set; }
Base delay (seconds) for backoff between retries. For exponential backoff the nth retry waits min(MaxRetryDelaySeconds, RetryBaseDelaySeconds * 2^(n-1)).
double RetryIncrementSeconds { get; set; }
Per-attempt increment (seconds) used only by RetryStrategy.Incremental backoff.
int BatchSize { get; set; }
Number of messages to process in each batch
int IdlePollingIntervalMilliseconds { get; set; }
Fallback polling interval (milliseconds) used while LISTEN/NOTIFY wakes are active. With a live listener the processor is woken on commit, so the safety-net poll can be much lazier than OutboxProcessorOptions.PollingIntervalMilliseconds, cutting idle database load. Used only when a wake listener is connected; otherwise the tight interval applies.
int MaxRetries { get; set; }
Maximum number of retries before marking message as failed
int PollingIntervalMilliseconds { get; set; }
Interval in milliseconds between polling cycles
int ProcessingLeaseSeconds { get; set; }
Processing lease (seconds): how long a claimed (Processing) outbox row may go without completion before it is considered stranded (e.g. the claiming processor crashed mid-batch) and becomes eligible for re-claiming. Must comfortably exceed the worst-case publish duration for a batch; a re-claimed row that was actually published is deduplicated by the consumer’s inbox, so a too-short lease causes duplicates rather than loss.
int PublishConcurrency { get; set; }
How many messages of a claimed batch are published concurrently (pipelining the broker’s publisher-confirm round-trips). Ordering across the batch becomes best-effort — which the outbox already is, given retries and multiple instances. Set to 1 for strictly sequential, in-claim-order publishing.