
messaging
BeliebtAsync messaging for .NET: per-module outbox/inbox for integration events, Hangfire or BackgroundService jobs, forwarding to Azure Service Bus, RabbitMQ or MassTransit. Use for "outbox", "inbox", "integration event", "idempotent consumer", "Hangfire", "scheduled job", "MassTransit", "RabbitMQ". Do NOT use for in-process handlers (use modular-slices) or HTTP client retries (use resilience).
Async messaging for .NET: per-module outbox/inbox for integration events, Hangfire or BackgroundService jobs, forwarding to Azure Service Bus, RabbitMQ or MassTransit. Use for "outbox", "inbox", "integration event", "idempotent consumer", "Hangfire", "scheduled job", "MassTransit", "RabbitMQ". Do NOT use for in-process handlers (use modular-slices) or HTTP client retries (use resilience).
Messaging
The per-module outbox code itself lives in skills/modular-slices/references/outbox.md. This skill covers when to use it, how to consume events safely, scheduled jobs, and what to add when events must reach another service.
Core Principles
- Built-in outbox first, broker later. Inside one deployable, modules publish with
db.Publish(evt, clock)into their own outbox table, in the same transaction as the change. A worker delivers events to consumers in other modules. This needs no broker and no library, and it gives the same guarantees a library outbox gives: the event exists if and only if the change committed. - Delivery is at-least-once, effects are exactly-once. The dispatcher retries until a consumer succeeds, so a consumer can see an event twice. Each consumer runs in a transaction with an inbox row keyed by event ID and consumer name, so its effect happens once. Write consumers that are also safe to re-run anyway.
- Events are contracts. They are records in the publisher's
Contractsproject, with IDs and the facts that changed. The full type name is stored in the outbox, so a published event is never renamed or moved; add a new one instead. - Jobs and events are different things. "Something happened, react to it" is an event through the outbox. "Do this every night" is a scheduled job in Hangfire or a
BackgroundService. Do not fake schedules with self-publishing events. - Pick the broker client for what you need, not for what is popular. One or two queues: the Azure Service Bus or RabbitMQ client. Many services with sagas and a transport abstraction: MassTransit, which requires a commercial licence from v9.
Patterns
Publishing an integration event
// Orders.Contracts/OrderPlaced.cs
/// <summary>Published when an order is placed. Never rename or move: the type name is stored in the outbox.</summary>
public sealed record OrderPlaced(Guid OrderId, decimal Total);
// Orders/Features/PlaceOrder/PlaceOrderHandler.cs
db.Orders.Add(order);
db.Publish(new OrderPlaced(order.Id, order.Total), clock);
await db.SaveChangesAsync(ct); // order row and outbox row commit together
Why: there is no moment where the order is saved but the event is lost, or the event is sent for an order that rolled back.
Consuming in another module
// Billing/Events/InvoiceOrders.cs
internal sealed class InvoiceOrders(BillingDbContext db, TimeProvider clock) : IEventConsumer<OrderPlaced>
{
public async Task ConsumeAsync(OrderPlaced message, CancellationToken ct)
{
// Safe to re-run even without the inbox: check before acting.
if (await db.Invoices.AnyAsync(i => i.OrderId == message.OrderId, ct))
return;
db.Invoices.Add(Invoice.For(message.OrderId, message.Total, clock.GetUtcNow()));
await db.SaveChangesAsync(ct);
}
}
// BillingModule.AddServices
services.AddEventConsumer<OrderPlaced, InvoiceOrders, BillingDbContext>();
Why: the consumer depends only on Orders.Contracts. The third type argument names the consuming module's context, which holds the inbox row and the consumer's changes in one transaction.
Running delivery in the Worker host only
// Worker/Program.cs
var builder = Host.CreateApplicationBuilder(args);
builder.AddServiceDefaults();
builder.AddModule<OrdersModule>();
builder.AddModule<BillingModule>();
builder.Services.AddOutboxWorker(); // BackgroundService polling every module's outbox
builder.Build().Run();
The Api host adds the same modules but not AddOutboxWorker(): it publishes, it does not deliver. Several Worker replicas can run safely because the dispatcher reads with FOR UPDATE SKIP LOCKED.
Tune delivery through the Outbox configuration section (PollInterval, BatchSize, MaxAttempts, retry delays). Failed events stay in the table with failed_at and the exception type, so they can be inspected and replayed by clearing failed_at.
Testing event flows
await client.PostAsJsonAsync("/api/v1/orders", new PlaceOrderRequest(productId, 2), ct);
await fixture.Factory.Services.GetRequiredService<IOutboxDispatcher>().DispatchPendingAsync(ct);
var invoices = await client.GetFromJsonAsync<List<InvoiceResponse>>("/api/v1/billing/invoices", ct);
Assert.Single(invoices!);
Why: tests never start the worker loop. Calling the dispatcher directly makes event delivery deterministic.
Scheduled jobs with Hangfire
// Worker/Program.cs
builder.Services.AddHangfire((provider, config) => config
.UseSimpleAssemblyNameTypeSerializer()
.UseRecommendedSerializerSettings()
.UsePostgreSqlStorage(o => o.UseNpgsqlConnection(builder.Configuration.GetConnectionString("app"))));
builder.Services.AddHangfireServer();
// BillingModule: registered after the host starts, e.g. from an IHostedService
recurringJobs.AddOrUpdate<SendOverdueReminders>(
"billing.send-overdue-reminders",
job => job.RunAsync(CancellationToken.None),
Cron.Daily(6));
internal sealed class SendOverdueReminders(BillingDbContext db, TimeProvider clock)
{
public async Task RunAsync(CancellationToken ct)
{
var today = DateOnly.FromDateTime(clock.GetUtcNow().UtcDateTime);
var overdue = await db.Invoices.Where(i => i.DueOn < today && i.PaidAt == null).ToListAsync(ct);
foreach (var invoice in overdue)
db.Publish(new InvoiceOverdue(invoice.Id, invoice.OrderId), clock);
await db.SaveChangesAsync(ct);
}
}
Why: Hangfire gives cron schedules, retries and a dashboard, stored in the same database. Job IDs shaped like <module>.<job> keep jobs easy to find. A job that needs other modules to react publishes events rather than calling them.
A simple periodic loop without Hangfire
internal sealed partial class ExpireCarts(IServiceScopeFactory scopes, TimeProvider clock, ILogger<ExpireCarts> logger)
: BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
using var timer = new PeriodicTimer(TimeSpan.FromMinutes(5), clock);
while (await timer.WaitForNextTickAsync(stoppingToken))
{
try
{
await using var scope = scopes.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<OrdersDbContext>();
var cutoff = clock.GetUtcNow().AddHours(-24);
await db.Carts.Where(c => c.UpdatedAt < cutoff).ExecuteDeleteAsync(stoppingToken);
}
catch (Exception ex) when (!stoppingToken.IsCancellationRequested)
{
LogFailed(logger, ex);
}
}
}
[LoggerMessage(Level = LogLevel.Error, Message = "Expiring carts failed; retrying on the next tick")]
private static partial void LogFailed(ILogger logger, Exception exception);
}
Why: for one or two fixed-interval loops, PeriodicTimer with an injected TimeProvider is enough and testable. Move to Hangfire once you need cron expressions, a dashboard, or many jobs.
Forwarding events to an external broker
When another service must receive events, keep the outbox and register a consumer that forwards. The outbox still guarantees the event was stored with the change; the forwarder gets retries from the dispatcher.
internal sealed class ForwardOrderPlaced(ServiceBusSender sender) : IEventConsumer<OrderPlaced>
{
public Task ConsumeAsync(OrderPlaced message, CancellationToken ct) =>
sender.SendMessageAsync(new ServiceBusMessage(BinaryData.FromObjectAsJson(message))
{
MessageId = $"order-placed-{message.OrderId}", // lets Service Bus duplicate detection drop retries
Subject = nameof(OrderPlaced),
}, ct);
}
// OrdersModule.AddServices
services.AddSingleton(provider => provider.GetRequiredService<ServiceBusClient>().CreateSender("orders"));
services.AddEventConsumer<OrderPlaced, ForwardOrderPlaced, OrdersDbContext>();
Register the ServiceBusClient with the Aspire client integration (builder.AddAzureServiceBusClient("messaging")) or RabbitMQ.Client with builder.AddRabbitMQClient("rabbit"). On the receiving side, consume with a ServiceBusProcessor (or a RabbitMQ consumer) in a BackgroundService, one scope per message, and make the handler idempotent.
MassTransit for multi-service systems
Use MassTransit when several services exchange many message types and you want a transport abstraction, consumer pipelines and sagas instead of writing them. MassTransit v9 and later require a commercial licence; v8 stays Apache 2.0 with security patches through 2026.
builder.Services.AddMassTransit(x =>
{
x.SetKebabCaseEndpointNameFormatter();
x.AddConsumers(typeof(Program).Assembly);
x.AddEntityFrameworkOutbox<OrdersDbContext>(o => { o.UsePostgres(); o.UseBusOutbox(); });
x.UsingAzureServiceBus((context, cfg) =>
{
cfg.Host(builder.Configuration.GetConnectionString("messaging"));
cfg.ConfigureEndpoints(context);
});
});
internal sealed class OrderPlacedConsumer(ShippingDbContext db) : IConsumer<OrderPlaced>
{
public async Task Consume(ConsumeContext<OrderPlaced> context)
{
db.Shipments.Add(Shipment.For(context.Message.OrderId));
await db.SaveChangesAsync(context.CancellationToken);
}
}
If you adopt MassTransit, use its outbox instead of the built-in one for the services that use it; do not run two outboxes on one context.
Choreography vs saga
For a two- or three-step flow (order placed, invoice raised, order marked paid), let each module react to the previous module's event. When a flow needs timeouts, compensation and state across many steps, model the state explicitly: a table owned by one module, updated by its consumers, with a scheduled job for timeouts. Reach for MassTransit sagas only when you already run MassTransit.
Anti-patterns
Publishing after SaveChanges
// BAD: if the process dies between the two lines, the event is lost
await db.SaveChangesAsync(ct);
await sender.SendMessageAsync(new ServiceBusMessage(BinaryData.FromObjectAsJson(evt)), ct);
// GOOD: the event is part of the same transaction
db.Publish(evt, clock);
await db.SaveChangesAsync(ct);
Consumers that are not idempotent
// BAD: a redelivery charges twice
public async Task ConsumeAsync(OrderPlaced message, CancellationToken ct)
{
db.Invoices.Add(Invoice.For(message.OrderId, message.Total, clock.GetUtcNow()));
await db.SaveChangesAsync(ct);
}
// GOOD: check for the effect first (the inbox also protects you, but brokers do not have one)
if (await db.Invoices.AnyAsync(i => i.OrderId == message.OrderId, ct))
return;
Reaching into the publisher's data from a consumer
// BAD: Billing reads Orders' tables to fill in what the event left out
var order = await ordersDb.Orders.FindAsync([message.OrderId], ct);
// GOOD: put the facts the consumer needs in the event, or call Orders' contract interface
db.Invoices.Add(Invoice.For(message.OrderId, message.Total, clock.GetUtcNow()));
Behaviour in event records
// BAD
public sealed record OrderPlaced(Guid OrderId, decimal Total)
{
public decimal Tax() => Total * 0.2m;
}
// GOOD: data only; the consumer owns its own rules
public sealed record OrderPlaced(Guid OrderId, decimal Total);
Fire-and-forget work
// BAD: no retries, exceptions vanish, shutdown kills it mid-way
_ = Task.Run(() => emails.SendReceiptAsync(order.Id));
// GOOD: publish an event (or enqueue a Hangfire job) and let the worker do it with retries
db.Publish(new OrderPlaced(order.Id, order.Total), clock);
Running the dispatcher in every API replica
// BAD: Api/Program.cs
builder.Services.AddOutboxWorker();
// GOOD: only the Worker host delivers; the Api only publishes
Decision Guide
| Scenario | Recommendation |
|---|---|
| Module-to-module events in one deployable | Built-in per-module outbox and inbox (modular-slices/references/outbox.md) |
| Recurring or cron-scheduled work | Hangfire with PostgreSQL storage in the Worker host |
| One or two fixed-interval loops | BackgroundService + PeriodicTimer with TimeProvider |
| Events must reach another service | Keep the outbox; forward with the Azure Service Bus or RabbitMQ client |
| Many services, many message types, sagas | MassTransit (commercial licence from v9; v8 is open source until end of 2026) |
| Existing MassTransit v8 codebase | Stay on v8 short term; plan a licence or move to direct clients before end of 2026 |
| Simple 2-3 step workflow | Choreography: each module reacts to the previous event |
| Long-running workflow with timeouts and compensation | State table in the owning module + scheduled timeout job; MassTransit saga only if already on MassTransit |
| Local broker for development | RabbitMQ or the Service Bus emulator via Aspire |
| Production cloud broker | Azure Service Bus, or RabbitMQ |
| In-process request/response | Not messaging: inject the handler into the endpoint |





