LowCodeHub.InboxOutbox
0.1.0
dotnet add package LowCodeHub.InboxOutbox --version 0.1.0
NuGet\Install-Package LowCodeHub.InboxOutbox -Version 0.1.0
<PackageReference Include="LowCodeHub.InboxOutbox" Version="0.1.0" />
<PackageVersion Include="LowCodeHub.InboxOutbox" Version="0.1.0" />
<PackageReference Include="LowCodeHub.InboxOutbox" />
paket add LowCodeHub.InboxOutbox --version 0.1.0
#r "nuget: LowCodeHub.InboxOutbox, 0.1.0"
#:package LowCodeHub.InboxOutbox@0.1.0
#addin nuget:?package=LowCodeHub.InboxOutbox&version=0.1.0
#tool nuget:?package=LowCodeHub.InboxOutbox&version=0.1.0
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.
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 ofLeaseDuration(default 2 min). Lease comparisons use the database clock, so app servers with skewed clocks agree on ownership. At mostMaxParallelismrows are claimed at a time. - Lease renewal — while a handler/sender runs, the lease is renewed every
LeaseDuration / 3and 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 + 1andNextAttemptAtUtc = now + min(InitialRetryDelay × 2^(n−1), MaxRetryDelay) ± RetryJitterFactor. AfterMaxRetriesattempts the message isFailed. - 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
Failedinstead of looping forever. - Shutdown — workers stop claiming, wait up to
DrainTimeoutfor in-flight messages, then cancel them and release their leases (back toPending, 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 11; SQL Server (Microsoft.Data.SqlClient) or PostgreSQL (Npgsql), or your own repositories.
License
MIT © Ahmed Abuelnour
AI agent skills
This package targets net11.0 and includes version-matched agent instructions under
skills/. After restoring your application's dependencies, install them into your
agent's skill directory:
dotnet tool install --global dotnet-package-skills --prerelease
dotnet-package-skills install
The default destination is .agents/skills/. For Claude, pass
--destination .claude/skills. Run the installer again after package upgrades.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net11.0 is compatible. |
-
net11.0
- Microsoft.Data.SqlClient (>= 7.1.2)
- Microsoft.Extensions.Diagnostics.HealthChecks (>= 11.0.0)
- Microsoft.Extensions.Options.ConfigurationExtensions (>= 11.0.0)
- Npgsql (>= 10.0.3)
- System.Security.Cryptography.Pkcs (>= 11.0.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.