LowCodeHub.InboxOutbox 0.0.16

There is a newer version of this package available.
See the version list below for details.
dotnet add package LowCodeHub.InboxOutbox --version 0.0.16
                    
NuGet\Install-Package LowCodeHub.InboxOutbox -Version 0.0.16
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="LowCodeHub.InboxOutbox" Version="0.0.16" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="LowCodeHub.InboxOutbox" Version="0.0.16" />
                    
Directory.Packages.props
<PackageReference Include="LowCodeHub.InboxOutbox" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add LowCodeHub.InboxOutbox --version 0.0.16
                    
#r "nuget: LowCodeHub.InboxOutbox, 0.0.16"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package LowCodeHub.InboxOutbox@0.0.16
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=LowCodeHub.InboxOutbox&version=0.0.16
                    
Install as a Cake Addin
#tool nuget:?package=LowCodeHub.InboxOutbox&version=0.0.16
                    
Install as a Cake Tool

LowCodeHub.InboxOutbox

Transactional outbox and de-duplicating inbox for ASP.NET Core, backed by SQL Server or PostgreSQL. Background workers claim messages under a renewable lease, deliver them with retries (exponential backoff

  • jitter), and record the outcome. Includes retention cleanup, requeue of failed messages, health checks, and OpenTelemetry metrics/traces.

NuGet License: MIT

dotnet add package LowCodeHub.InboxOutbox

Quick start

1. Configure (appsettings.json), choosing the provider with one key:

{
  "InboxOutbox": {
    "Provider": "SqlServer",
    "SqlServer": { "ConnectionString": "Server=...;Database=...;" }
  }
}

("Provider": "PostgreSql" with an "InboxOutbox:PostgreSql" section works the same way.)

2. Register the workers, your outbox sender, and your inbox handlers:

builder.Services.AddInboxOutbox(builder.Configuration)
    .AddOutboxSender<RabbitOutboxSender>()
    .AddInboxHandler<OrderPlacedHandler>();

3. Create the tables once (see Database schema).

4. Write to the outbox in the same transaction as your business data:

await using var tx = await connection.BeginTransactionAsync(ct);
await connection.ExecuteAsync("INSERT INTO Orders ...", order, tx);          // your write (Dapper here)
await outbox.TryAddAsync(OutboxMessage.Create("orders", new OrderPlaced(order.Id)), tx, ct);
await tx.CommitAsync(ct);

The outbox worker picks up the row after commit and calls your sender. Rolled-back transactions never send.

Writing to the outbox

IOutboxRepository (scoped) has three insert overloads. Use a transactional one — that is the whole point of the outbox pattern.

Overload Atomic with your data? Use when
TryAddAsync(message, DbTransaction tx, ct) Yes ADO.NET, Dapper, EF Core (below)
TryAddAsync(message, DbConnection conn, DbTransaction? tx, ct) Yes, if tx is passed You hold the connection explicitly
TryAddAsync(message, ct) No — opens its own connection There is no business write to pair with

The outbox table must live in the database your transaction writes to. With SQL Server pass a SqlTransaction, with PostgreSQL an NpgsqlTransaction.

EF Core (no EF dependency needed — GetDbTransaction() is in Microsoft.EntityFrameworkCore.Relational):

await using var tx = await db.Database.BeginTransactionAsync(ct);
db.Orders.Add(order);
await db.SaveChangesAsync(ct);
await outbox.TryAddAsync(OutboxMessage.Create("orders", new OrderPlaced(order.Id)), tx.GetDbTransaction(), ct);
await tx.CommitAsync(ct);

OutboxMessage.Create<T>(destination, payload, messageType?, correlationId?, headers?) serializes the payload as JSON (web defaults) and sets MessageType to typeof(T).Name unless given. You can also build OutboxMessage yourself. Set NextAttemptAtUtc to delay the first send, MaxRetries (default 5) to change the attempt budget. Returns false if a message with the same Id exists.

Sending

public sealed class RabbitOutboxSender(IMessagePublisher publisher) : IOutboxMessageSender
{
    // Payload is already JSON: publish it as a JsonElement so it is not encoded a second time.
    public Task SendAsync(OutboxMessage message, CancellationToken ct)
        => publisher.PublishAsync(message.Destination, message.MessageType,
            message.GetPayload<JsonElement>(),
            new PublishOptions { MessageId = message.Id.ToString(), CorrelationId = message.CorrelationId }, ct);
}

Throwing schedules a retry. Delivery is at-least-once: consumers should de-duplicate by message.Id. Until a sender is registered the outbox worker does not claim messages (they stay pending) and its health check reports Degraded.

Inbox: de-duplicating incoming messages

Keep the broker consumer thin: persist, then ack.

var inserted = await inbox.TryAddAsync(
    InboxMessage.Create(source: "billing", externalMessageId: delivery.MessageId, payload: evt), ct);
// true = new, false = duplicate of (Source, ExternalMessageId) — ack either way

Use TryAddAsync(message, tx, ct) to record receipt inside your own transaction; a duplicate returns false and leaves the transaction usable on both providers.

Handle messages with a typed handler (routes on MessageType, default typeof(TPayload).Name, case-insensitive):

public sealed class OrderPlacedHandler(IOrderService orders) : InboxMessageHandler<OrderPlaced>
{
    protected override Task HandleAsync(OrderPlaced payload, InboxMessage message, CancellationToken ct)
        => orders.ConfirmAsync(payload.OrderId, ct);
}

Or implement IInboxMessageHandler (CanHandle(messageType) + HandleAsync) directly. Exactly one handler must match each message type; otherwise the attempt fails. Handlers must be idempotent (at-least-once). With no handlers registered the inbox worker stays idle and reports Degraded.

How processing works

  • Claim — rows are claimed atomically (UPDLOCK, READPAST / FOR UPDATE SKIP LOCKED) with a lock token and a lease of LeaseDuration (default 2 min). Lease comparisons use the database clock, so app servers with skewed clocks agree on ownership. At most MaxParallelism rows are claimed at a time.
  • Lease renewal — while a handler/sender runs, the lease is renewed every LeaseDuration / 3 and the worker heartbeat is updated, so long deliveries are neither re-claimed nor killed by liveness probes. If a renewal is rejected (lease lost) the delivery is cancelled and the new owner records the outcome.
  • Timeout — one invocation may run at most ProcessingTimeout (default 5 min); then it counts as a failed attempt.
  • Retry — a failure sets RetryCount + 1 and NextAttemptAtUtc = now + min(InitialRetryDelay × 2^(n−1), MaxRetryDelay) ± RetryJitterFactor. After MaxRetries attempts the message is Failed.
  • Crash recovery — a lease that expires (process died) is reclaimed by any instance and counts as an attempt, so a message that crashes the process every time ends up Failed instead of looping forever.
  • Shutdown — workers stop claiming, wait up to DrainTimeout for in-flight messages, then cancel them and release their leases (back to Pending, no attempt consumed).

States: Pending → Processing → Processed, or back to Pending (retry), or Failed.

Operations

await outbox.RequeueFailedAsync(messageId, ct);           // one Failed message → Pending, fresh retry budget
await inbox.RequeueAllFailedAsync("OrderPlaced", ct);     // all Failed of a type (null = all types)

Retention — a cleanup worker runs every CleanupInterval (1 h) and deletes Processed rows older than ProcessedRetention (default 7 days) and Failed rows older than FailedRetention (default: kept). For the inbox, ProcessedRetention is also the de-duplication window. Set it to null to keep rows forever.

Configuration reference

All options bind from InboxOutbox (or use AddInboxOutbox(o => ...); AddInboxOutbox(configuration, o => ...) applies code overrides after binding). Options are validated at startup.

Worker options — InboxOutbox:Inbox and InboxOutbox:Outbox:

Option Default Description
Enabled true Run this worker (and its cleanup) on this instance
BatchSize 50 Max rows per claim (also capped by MaxParallelism)
MaxParallelism 4 Concurrent deliveries
PollInterval 00:00:02 Wait between polls when the last batch was not full
InitialRetryDelay / MaxRetryDelay 5s / 5min Exponential backoff bounds
RetryJitterFactor 0.2 ±20% randomization of each retry delay
ProcessingTimeout 00:05:00 Max duration of one handler/sender call
DrainOnShutdown / DrainTimeout true / 30s Graceful shutdown
HealthStaleAfter 00:02:00 Heartbeat age that turns the worker unhealthy
ProcessedRetention 7.00:00:00 Delete processed rows after this (null = never)
FailedRetention null Delete failed rows after this (null = never)

Root: CleanupInterval (01:00:00), CleanupBatchSize (1000), Provider (SqlServer | PostgreSql, read only by AddInboxOutbox(IConfiguration)).

Provider options — InboxOutbox:SqlServer / InboxOutbox:PostgreSql:

Option SQL Server default PostgreSQL default
ConnectionString required required
InboxSchema / InboxTable dbo / InboxMessages public / inbox_messages
OutboxSchema / OutboxTable dbo / OutboxMessages public / outbox_messages
LeaseDuration 00:02:00 00:02:00
ValidateSchemaOnStartup true true

Explicit registration instead of the Provider key:

builder.Services
    .AddInboxOutbox(builder.Configuration)
    .AddInboxOutboxPostgreSql(builder.Configuration, o => o.ConnectionString = builder.Configuration.GetConnectionString("Main")!);

Only one provider can be registered. At startup the app fails fast with an explanatory error if an enabled worker has no repository, or (when ValidateSchemaOnStartup) the configured tables/columns are missing. An unreachable database only logs a warning — the workers keep retrying.

Database schema

The package does not create tables during registration. Scripts ship as embedded resources using the default names; SqlInboxOutbox.GetSqlServerScripts(options) / GetPostgreSqlScripts(options) return them rendered for your schema/table names (non-default schemas are created).

With LowCodeHub.Migration.SqlServer (default names):

builder.Services.AddSqlServerMigrations(m => m.AddTarget<IInboxOutboxScriptScanner>(o =>
{
    o.ConnectionString = builder.Configuration["InboxOutbox:SqlServer:ConnectionString"]!;
    o.Directories = ["LowCodeHub.InboxOutbox.Repositories.SqlServer.Scripts."];
}));
await app.RunSqlServerMigrationAsync();

For PostgreSQL use AddPostgreSqlMigrations with "LowCodeHub.InboxOutbox.Repositories.PostgreSql.Scripts.". Always pass the directory filter — the assembly contains scripts for both providers.

With custom names or EF Core migrations:

protected override void Up(MigrationBuilder migrationBuilder)
{
    var options = new SqlServerInboxOutboxOptions { InboxSchema = "messaging", OutboxSchema = "messaging" };
    foreach (var script in SqlInboxOutbox.GetSqlServerScripts(options))
        migrationBuilder.Sql(script);
}

Health checks

Name Tags Meaning
inbox-worker, outbox-worker inboxoutbox, liveness Unhealthy when stopped or heartbeat older than HealthStaleAfter; Degraded when idle for lack of a handler/sender
inboxoutbox-sqlserver / inboxoutbox-postgresql inboxoutbox, readiness Database reachable
app.MapHealthChecks("/health/live", new() { Predicate = r => r.Tags.Contains("liveness") });
app.MapHealthChecks("/health/ready", new() { Predicate = r => r.Tags.Contains("readiness") });

Observability

Source and meter name: LowCodeHub.InboxOutbox (InboxOutboxDiagnostics.SourceName).

builder.Services.AddOpenTelemetry()
    .WithTracing(t => t.AddSource(InboxOutboxDiagnostics.SourceName))
    .WithMetrics(m => m.AddMeter(InboxOutboxDiagnostics.SourceName));
Metric Type Tags
inboxoutbox.messages.enqueued counter kind, message_type, outcome = inserted/duplicate
inboxoutbox.messages.processed counter kind, message_type
inboxoutbox.messages.failed counter kind, message_type, outcome = retry/dead/lease_lost
inboxoutbox.messages.cleaned counter kind
inboxoutbox.message.duration histogram (ms) kind, message_type, outcome
inboxoutbox.worker.batch_size histogram kind

Traces: each delivery is an inbox process {type} / outbox process {type} span. Inserts store the current W3C traceparent/tracestate in the message headers (unless you set them), and the delivery span continues that trace — so an HTTP request, its outbox write, and the later publish appear as one trace.

Custom repositories

Implement IInboxRepository / IOutboxRepository and register them before calling a provider extension (providers use TryAddScoped), or instead of one:

builder.Services.AddScoped<IOutboxRepository, MyOutboxRepository>();
builder.Services.AddScoped<IInboxRepository, MyInboxRepository>();
builder.Services.AddInboxOutbox(builder.Configuration);   // no Provider key

Required behaviour: ClaimPendingAsync must atomically move due rows (and rows with an expired lease, incrementing RetryCount) to Processing with a fresh LockToken, and return LockedUntilUtc as utcNow + lease; MarkProcessedAsync/MarkFailedAsync/RenewLeaseAsync/ReleaseAsync must only affect the row while it holds the given lock token. Optional operations may throw NotSupportedException: without RenewLeaseAsync deliveries are cancelled when the original lease ends; without DeleteCompletedBeforeAsync retention cleanup is skipped. See the built-in SQL repositories for reference.

Requirements

.NET 10; SQL Server (Microsoft.Data.SqlClient) or PostgreSQL (Npgsql), or your own repositories.

License

MIT © Ahmed Abuelnour

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.1.0 108 11/15/2026
0.0.16 104 10/22/2026
0.0.15 213 8/10/2026
0.0.14 123 8/6/2026
0.0.13 179 7/16/2026
0.0.12 131 7/9/2026
0.0.11 138 6/23/2026
0.0.10 141 6/21/2026
0.0.5 139 5/18/2026
0.0.4 134 5/13/2026
0.0.3 130 5/12/2026
0.0.2 142 4/23/2026
0.0.1 137 3/26/2026