agentleFS
codewithmukeshcodewithmukesh/dotnet-agent-kit/skills/messaging/SKILL.md

messaging

Skill853 starsChanged yesterdayMITView on GitHub

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).

18 other projects use a version of this.

Adopted by

Most recently taken up by

Used with

Projects with it also use company-context and brand-kit.

Other files people use alongside this one.

Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
  • VercelSkill

    company-context

    Company names, teams, glossary, and where information lives. Load before answering questions that depend on company-specific terms, owners, or sources.

    Also in 3 projects that use this

  • ai-agents-for-agencies-coachesSkill

    brand-kit

    Establish and enforce per-client brand fidelity using the DESIGN.md standard (google-labs-code/design.md). Use whenever starting work for a client, creating any ad/landing-page/creative, or when brand colors/fonts/spacing are needed. Auto-extracts a client's visual identity into a validated DESIGN.md, keeps a central registry, and feeds the tokens into image-studio (statics), fb-ad-video-studio (video), and landing pages. Triggers: "set up brand for <client>", "make a DESIGN.md", "match the client's brand", "what are their brand colors", "new client onboarding", any creative work that must be on-brand.

    Also in 3 projects that use this

The file

We split this skill into the rules it gives an agent

3 rules. 0 are common, 3 are distinctive, and 0 are very specific to this project.

  • 0

    Common

    Most of the 14 edited versions we read keep these.

  • 3

    Distinctive

    This author's own choices. Worth a look.

  • 0

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    When another service must receive events, keep the outbox and register a consumer that forwards.

    line 158
  2. Distinctive:

    Use MassTransit when several services exchange many message types and you want a transport abstraction, consumer pipelines and sagas …

    line 180
  3. Distinctive:

    If you adopt MassTransit, use its outbox instead of the built-in one for the services that use it.

    line 205

“Common” is measured: kept by at least 6 in 10 of the 14 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

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

  1. 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.
  2. 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.
  3. Events are contracts. They are records in the publisher's Contracts project, 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.
  4. 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.
  5. 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

ScenarioRecommendation
Module-to-module events in one deployableBuilt-in per-module outbox and inbox (modular-slices/references/outbox.md)
Recurring or cron-scheduled workHangfire with PostgreSQL storage in the Worker host
One or two fixed-interval loopsBackgroundService + PeriodicTimer with TimeProvider
Events must reach another serviceKeep the outbox; forward with the Azure Service Bus or RabbitMQ client
Many services, many message types, sagasMassTransit (commercial licence from v9; v8 is open source until end of 2026)
Existing MassTransit v8 codebaseStay on v8 short term; plan a licence or move to direct clients before end of 2026
Simple 2-3 step workflowChoreography: each module reacts to the previous event
Long-running workflow with timeouts and compensationState table in the owning module + scheduled timeout job; MassTransit saga only if already on MassTransit
Local broker for developmentRabbitMQ or the Service Bus emulator via Aspire
Production cloud brokerAzure Service Bus, or RabbitMQ
In-process request/responseNot messaging: inject the handler into the endpoint

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.