GM.Messaging.Persistence 4.0.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package GM.Messaging.Persistence --version 4.0.0
                    
NuGet\Install-Package GM.Messaging.Persistence -Version 4.0.0
                    
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="GM.Messaging.Persistence" Version="4.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="GM.Messaging.Persistence" Version="4.0.0" />
                    
Directory.Packages.props
<PackageReference Include="GM.Messaging.Persistence" />
                    
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 GM.Messaging.Persistence --version 4.0.0
                    
#r "nuget: GM.Messaging.Persistence, 4.0.0"
                    
#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 GM.Messaging.Persistence@4.0.0
                    
#: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=GM.Messaging.Persistence&version=4.0.0
                    
Install as a Cake Addin
#tool nuget:?package=GM.Messaging.Persistence&version=4.0.0
                    
Install as a Cake Tool

<p align="center"> <img src="https://raw.githubusercontent.com/gmetskhvarishvili/GM.Messaging/master/icon.png" alt="GM.Messaging" width="140" height="140" /> </p>

GM.Messaging

CI NuGet License: MIT

A lightweight messaging setup for .NET built on Wolverine and RabbitMQ. One call wires up the message bus from configuration — connection, resilience (retry + circuit breaker), and producer/consumer topology — with a transactional outbox/inbox for reliable, integration events that are published at least once and handled once per consumer. Part of the GM.* family of packages. Targets net10.0.

Packages

This repository ships three packages that version and release in lockstep:

Package What it provides
GM.Messaging AddGMMessaging (Wolverine + RabbitMQ wiring, resilience, topology) and AddGMOutboxRelay.
GM.Messaging.Domain IntegrationEvent, [IntegrationEventName], and the InboxMessage / OutboxMessage entities.
GM.Messaging.Persistence EF Core configurations, the transactional inbox (AddGMInbox), the inbox worker (AddGMInboxWorker), and telemetry names.

Install

dotnet add package GM.Messaging

Register

using GM.Messaging;

builder.Services.AddGMMessaging(builder.Configuration);

Configure

Everything comes from the Messaging configuration section (shape matches MessagingOptions); every value has a sensible default:

{
  "Messaging": {
    "ServiceName": "orders-service",
    "RabbitMq": {
      "HostName": "localhost",
      "Port": 5672,
      "VirtualHost": "/",
      "UserName": "guest",
      "Password": "guest",
      "PublisherConfirms": true,
      "UnroutedExchange": "gm.unrouted"
    },
    "Retry": { "MaxAttempts": 5, "InitialDelayMilliseconds": 250 },
    "CircuitBreaker": { "Enabled": true, "FailurePercentageThreshold": 25 },
    "OutboxRelay": {
      "BatchSize": 50,
      "PollingIntervalSeconds": 5,
      "MaxRetries": 5,
      "RetryBaseDelaySeconds": 5,
      "RetryMaxDelaySeconds": 300,
      "LeaseSeconds": 60,
      "RetentionDays": 7,
      "CleanupIntervalMinutes": 60,
      "WakeUpExchange": "gm.outbox.wake-up"
    },
    "Inbox": {
      "RetentionDays": 30,
      "CleanupIntervalMinutes": 60,
      "BatchSize": 50,
      "PollingIntervalSeconds": 5,
      "MaxConcurrency": 10,
      "MaxAttempts": 5,
      "RetryBaseDelaySeconds": 5,
      "RetryMaxDelaySeconds": 300,
      "LeaseSeconds": 60,
      "ConsumerNames": [],
      "ConsumerName": "billing"
    }
  }
}

Optional ProducerTopology / ConsumerTopology sections declare exchange/queue routes, and the configureWolverine callback on AddGMMessaging lets you customize Wolverine directly. A route's MessageType can be the event's [IntegrationEventName] (it survives class renames), its full type name, or "Namespace.Type, Assembly":

"ProducerTopology": { "Routes": [ { "MessageType": "orders.order-placed", "Exchange": "orders" } ] }

Publish an integration event

[IntegrationEventName("orders.order-placed")] // optional, see "Event names" below
public record OrderPlaced(Guid OrderId) : IntegrationEvent;

// Save the event in the same transaction as the change that raised it.
dbContext.Add(order);
dbContext.Add(OutboxMessage.From(new OrderPlaced(order.Id)));
await dbContext.SaveChangesAsync();

The outbox relay then publishes it through Wolverine.

Wire the outbox and inbox

Both work directly on your DbContext. Map the tables with OutboxMessageConfiguration<T> and InboxMessageConfiguration<T>, then:

// Producer: publishes the outbox and deletes published messages after RetentionDays
builder.Services.AddGMOutboxRelay<OutboxMessage, AppDbContext>();

// Consumer: a scoped IInboxProcessor, plus deletion of handled rows after RetentionDays
builder.Services.AddGMInbox<InboxMessage, AppDbContext>();

TOutboxMessage / TInboxMessage can be your own subclasses of the base entities; a private parameterless constructor is enough (use Populate(evt) in a derived outbox type's factory).

The outbox relay

  • Published means confirmed. RabbitMQ publisher confirms are on (RabbitMq:PublisherConfirms), so a message is marked published only after the broker has accepted it; a rejected or lost publish throws and is retried.
  • Missing routes fail loudly. An event type with no publish route (not in ProducerTopology:Routes) fails with NoRouteException and is retried, then dead-lettered, instead of being dropped silently.
  • Retries with backoff. A failed publish waits RetryBaseDelaySeconds, doubling each time up to RetryMaxDelaySeconds.
  • Unroutable messages are kept. RabbitMQ drops a message published to an exchange with no matching queue (for example before any consumer has bound one), and still confirms it. GM topology gives every exchange it declares an alternate exchange, gm.unrouted (RabbitMq:UnroutedExchange), so such messages land in the gm.unrouted queue instead of disappearing. Watch that queue (the RabbitMQ UI shows its depth) and move messages back once the consumer's queue exists.
  • Dead-letters. After MaxRetries failures the message gets DeadLetteredAtUtc, is logged at error level, and is no longer tried. Fix the cause, then requeue it through IOutboxAdministration (see "Dead letters and backlog").
  • Keeps order per key. Messages with the same ordering key are published one at a time, in the order they were raised; see "Ordered events".
  • Publishes at once. Add the interceptor to your DbContext and a save that adds outbox messages wakes the relay instead of it waiting for its next poll, in this process directly and in other processes over a small RabbitMQ fanout exchange (OutboxRelay:WakeUpExchange): services.AddDbContext<AppDbContext>((sp, o) => o.UseNpgsql(cs).AddGMOutboxSignal(sp));. In a process that saves outbox messages but doesn't relay (an API), also call services.AddGMOutboxWakeUp(configuration). If RabbitMQ is unreachable, relays simply poll.
  • Runs in several processes. Each message is leased to one relay (LockedBy, LockedUntilUtc) with a compare-and-set update before it is published, so an API and a worker can both run the relay. A message is published twice only if a relay stops mid-publish and its lease (LeaseSeconds) runs out; the consumer's inbox absorbs that.
  • Keeps the table small. Published messages are deleted after RetentionDays (0 keeps them).

The project that calls AddGMOutboxRelay needs the GM.Messaging package, not just GM.Messaging.Persistence. If you'd rather keep the persistence layer on GM.Messaging.Persistence alone, call AddGMOutboxRelay from the host's Program.cs, or pass a flag into your persistence registration (AddPersistence(configuration, runOutboxRelay: true)) to pick which hosts relay.

Handle an event once: ProcessAsync

public static class OrderPlacedHandler
{
    public static Task Handle(OrderPlaced message, IInboxProcessor inbox, AppDbContext db, CancellationToken ct) =>
        inbox.ProcessAsync(message, () =>
        {
            db.Add(Invoice.For(message.OrderId));
            return Task.CompletedTask; // ProcessAsync saves and commits
        }, ct);
}
  • The handler gets the inbox's DbContext. AddGMInbox records the DbContext, and AddGMMessaging has Wolverine take it from the message's scope (its generated code can't build a DbContext itself), so db above is the same instance the inbox uses. No Wolverine setup needed.
  • One transaction. The inbox row and everything the handler saves through the same DbContext commit together. Changes made elsewhere (another database, an HTTP call) aren't covered; a handler that changes nothing through that DbContext is logged once, as a hint.
  • One consumer name per service. Set Messaging:Inbox:ConsumerName (default: the entry assembly's name) and call ProcessAsync(message, handler, ct) / IngestAsync(message, ct) without a name, so a typo can't create a second consumer.
  • Failures are retried. When the handler throws, its changes roll back, the error and attempt count are recorded on the row, and the exception reaches Wolverine, whose retry policy runs the handler again. Only a successful run marks the event handled.
  • Duplicates are skipped, including two deliveries arriving at the same moment: the second waits on the first's row lock and then skips.
  • Inside a transaction you opened yourself, the row joins it and you commit.

Handle it later: IngestAsync and the inbox worker

For work that shouldn't block the consumer (sending email, calling a slow API), store the event and let the inbox worker handle it:

builder.Services.AddGMInboxWorker<InboxMessage, AppDbContext>();
builder.Services.AddGMInboxHandler<UserRegistered, SendWelcomeEmail>();

// In the Wolverine handler:
public Task Handle(UserRegistered message, IInboxProcessor inbox, CancellationToken ct) =>
    inbox.IngestAsync(message, "notifications", ct);

public class SendWelcomeEmail(IEmailSender email) : IInboxHandler<UserRegistered>
{
    public Task HandleAsync(UserRegistered e, CancellationToken ct) => email.SendWelcomeAsync(e.Email, ct);
}

The worker leases rows like the relay (so it can run in several processes), runs up to MaxConcurrency handlers at once, retries failures with backoff, and dead-letters a row after MaxAttempts. InboxMessage.Requeue() makes a dead-lettered row pending again. Set ConsumerNames to handle only some consumers' rows.

Event names

Each row stores the event's name: its [IntegrationEventName] if it has one, otherwise its full type name (namespace and class, without the assembly). Moving an event to another assembly is safe. Renaming the class or its namespace strands rows already written, unless the event keeps its old name through [IntegrationEventName("…")]. Rows written by 1.x (assembly-qualified names) still resolve.

Event versions

Payloads are read leniently (property names case-insensitive, unknown properties ignored), so adding a property is safe. For an incompatible change, raise the event's version and register an upcaster from the previous one; rows still in the outbox or inbox are converted before they're read:

[IntegrationEventName("orders.order-shipped", Version = 2)] // v2 renamed Courier to Carrier
public record OrderShipped(Guid OrderId, string Carrier) : IntegrationEvent;

services.AddGMIntegrationEvents(events => events
    .AddAssembly(typeof(OrderShipped).Assembly)
    .AddUpcaster<OrderShipped>(fromVersion: 1, v1 =>
    {
        v1["Carrier"] = v1["Courier"]?.DeepClone();
        v1.Remove("Courier");
        return v1;
    }));

The version also travels on the wire: GM.Messaging sets Wolverine's serializer to one that sends each event's version in the gm-event-version header, so a consumer already at version 2 upcasts a version-1 event a not-yet-upgraded producer sent. The outbox, the inbox and the wire use the same JSON options (ConfigureJson above). A missing upcaster fails the message (retried, then dead-lettered) with an error naming the step.

Ordered events

Give events an ordering key, by implementing IOrderedIntegrationEvent or with OutboxMessage.From(evt, orderingKey: "order-42"). The relay publishes messages with the same key one at a time in creation order, even across several relays: a message waits until the earlier ones with its key are published or dead-lettered (a dead-lettered message doesn't block its key forever). Keys don't slow each other down. To keep the order on the consumer side, handle the queue sequentially (set "Sequential": true on its ConsumerTopology binding).

Dead letters and backlog

IOutboxAdministration (registered by AddGMOutboxRelay, or AddGMOutboxAdministration in a process without the relay) and IInboxAdministration (registered by AddGMInbox) list dead-lettered messages, requeue one or all, purge them, and report the backlog (pending count, oldest pending, dead-lettered count):

app.MapGet("/admin/outbox", (IOutboxAdministration outbox) => outbox.GetBacklogAsync());
app.MapGet("/admin/outbox/dead-letters", (IOutboxAdministration outbox) => outbox.GetDeadLetteredAsync());
app.MapPost("/admin/outbox/dead-letters/{id:guid}/requeue", (Guid id, IOutboxAdministration outbox) => outbox.RequeueAsync(id));

The GM.HealthChecks.Messaging package turns the backlog into a health check.

Messages in RabbitMQ that nothing handled have their own tool, IBrokerQueueAdministration (registered by AddGMMessaging): count and peek a queue, send dead letters (messages a consumer still failed after Wolverine's retries, in ConsumerTopology:DeadLetterQueue) back to the queue they came from, and move unrouted messages (in gm.unrouted) to their exchange once a consumer's queue exists.

app.MapGet("/admin/broker/dead-letters", (IBrokerQueueAdministration broker) => broker.PeekAsync("gm.dead-letters"));
app.MapPost("/admin/broker/dead-letters/replay", (IBrokerQueueAdministration broker) => broker.ReplayDeadLettersAsync("gm.dead-letters"));
app.MapPost("/admin/broker/unrouted/move", (IBrokerQueueAdministration broker) => broker.MoveAsync("gm.unrouted", "gm.events"));

Observability

Add the GM.Messaging source and meter (MessagingTelemetry.Name) to OpenTelemetry:

builder.Services.AddOpenTelemetry()
    .WithTracing(t => t.AddSource(MessagingTelemetry.Name))
    .WithMetrics(m => m.AddMeter(MessagingTelemetry.Name));

The outbox stores the W3C trace context of the request that raised each event, and the relay publishes it in that trace, so a request, its published event and the consumer's handling show up as one trace. Metrics cover published, failed and dead-lettered messages, pending counts, publish lag, handled and duplicate inbox messages, and cleanup.

Upgrading from 3.x

No database changes. 4.0 declares every exchange in ProducerTopology / ConsumerTopology with an alternate-exchange argument, and RabbitMQ refuses to redeclare an existing exchange with different arguments. On a broker that already has those exchanges, either delete them once (the services recreate them, and consumers rebind their queues, at startup), or keep the old behaviour by setting Messaging:RabbitMq:UnroutedExchange to "" in every producer and consumer. Producers and consumers of the same exchange must use the same setting.

Also new in 4.0, without breaking changes for callers:

  • Wolverine's default serializer is GM's (same JSON as storage, versions in a header). Payloads are still plain JSON.
  • Handlers can take the inbox's DbContext directly; remove any CodeGeneration.AlwaysUseServiceLocationFor<YourDbContext>() you added (it's harmless if left).
  • IBrokerQueueAdministration, AddGMIntegrationEvents, and cross-process wake-ups (AddGMOutboxWakeUp, OutboxRelay:WakeUpExchange).
  • OutboxSignal.Notify() now also tells other processes; use WakeUp() to wake only this process's relay.

Upgrading from 2.x

3.0 adds columns again, so add an EF Core migration in each service that maps the tables:

  • outbox_messages: event_version (default 1), ordering_key, and the ix_outbox_messages_ordering index.
  • inbox_messages: event_version (default 1).

Also changed:

  • IInboxProcessor has overloads without a consumer name (custom implementations must add them).
  • OutboxMessage.From and Populate take an optional orderingKey, and InboxMessage.Create an optional eventVersion (recompile; source-compatible).
  • Payloads are written with IntegrationEventSerializer.Options and read case-insensitively.

Upgrading from 1.x

2.0 adds columns to both tables, so add an EF Core migration in each service that maps them:

  • outbox_messages: next_attempt_at_utc, dead_lettered_at_utc, locked_by, locked_until_utc, trace_parent, and the ix_outbox_messages_pending index.
  • inbox_messages: attempts, ingested, next_attempt_at_utc, dead_lettered_at_utc, locked_by, locked_until_utc, trace_parent, and the ix_inbox_messages_pending index.

Also changed:

  • IInboxStore<T>, IOutboxDbContext<T> and AddGMInboxProcessor<T>() are gone; AddGMInbox and AddGMOutboxRelay work on the DbContext directly.
  • IInboxProcessor is scoped (it shares the handler's DbContext), so resolve it per message or scope, not from the root provider.
  • New rows store the event's full type name instead of its assembly-qualified name. Existing rows still resolve.
  • Published outbox messages (after 7 days) and handled inbox rows (after 30 days) are now deleted. Set RetentionDays to 0 to keep them.
  • Rows ingested by 1.x have ingested = false after the migration, so the inbox worker ignores them. Finish them with your existing poller, or set ingested = true on them.

Local infrastructure

A docker-compose.yml is included to run PostgreSQL + RabbitMQ locally:

docker compose up gm.messaging.postgres gm.messaging.rabbitmq

Requirements

  • .NET 10 SDK
  • RabbitMQ (and a relational database for the outbox/inbox).

Contributing & releases

Versioning is automated from Conventional Commits — see CONTRIBUTING.md. All three packages release together under one version.

License

MIT — see LICENSE.

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 (1)

Showing the top 1 NuGet packages that depend on GM.Messaging.Persistence:

Package Downloads
GM.Messaging

A lightweight messaging setup for .NET built on Wolverine and RabbitMQ. One call (AddGMMessaging) wires up the message bus with config-driven RabbitMQ connection, resilience (retry + circuit breaker) and producer/consumer topology, plus an outbox relay that retries with backoff, dead-letters, leases messages so it can run in several processes, cleans up old rows and continues traces. Part of the GM.Messaging family.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
5.0.0 106 11/17/2026
4.14.0 174 11/17/2026
4.13.0 97 11/17/2026
4.12.0 97 11/17/2026
4.11.0 99 11/17/2026
4.10.0 193 11/17/2026
4.9.0 97 11/17/2026
4.8.0 100 11/17/2026
4.7.0 100 11/17/2026
4.6.0 172 11/17/2026
4.5.0 115 11/16/2026
4.4.0 134 11/16/2026
4.3.0 148 11/16/2026
4.2.0 129 11/16/2026
4.1.0 204 11/16/2026
4.0.0 123 11/16/2026
3.0.0 164 11/16/2026
2.0.1 100 11/16/2026
2.0.0 107 11/16/2026
1.3.1 131 11/15/2026
Loading failed