GM.Messaging.Persistence
4.1.0
See the version list below for details.
dotnet add package GM.Messaging.Persistence --version 4.1.0
NuGet\Install-Package GM.Messaging.Persistence -Version 4.1.0
<PackageReference Include="GM.Messaging.Persistence" Version="4.1.0" />
<PackageVersion Include="GM.Messaging.Persistence" Version="4.1.0" />
<PackageReference Include="GM.Messaging.Persistence" />
paket add GM.Messaging.Persistence --version 4.1.0
#r "nuget: GM.Messaging.Persistence, 4.1.0"
#:package GM.Messaging.Persistence@4.1.0
#addin nuget:?package=GM.Messaging.Persistence&version=4.1.0
#tool nuget:?package=GM.Messaging.Persistence&version=4.1.0
<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
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",
"UpgradeExchanges": false
},
"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"
}
}
}
Connecting to a managed or clustered broker. Instead of HostName … Password, set RabbitMq:Uri
(amqps://user:password@host/vhost turns TLS on). RabbitMq:UseTls (with an optional TlsServerName)
enables TLS for host-based settings and moves the default port to 5671, and RabbitMq:ClusterNodes
(["mq-2", "mq-3:5673"]) lists further nodes to connect or fail over to. Wolverine's transport, the
outbox wake-ups and the broker tools all use these settings.
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 withNoRouteExceptionand is retried, then dead-lettered, instead of being dropped silently. - Retries with backoff. A failed publish waits
RetryBaseDelaySeconds, doubling each time up toRetryMaxDelaySeconds. - 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 thegm.unroutedqueue 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
MaxRetriesfailures the message getsDeadLetteredAtUtc, is logged at error level, and is no longer tried. Fix the cause, then requeue it throughIOutboxAdministration(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
DbContextand 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 callservices.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.AddGMInboxrecords theDbContext, andAddGMMessaginghas Wolverine take it from the message's scope (its generated code can't build aDbContextitself), sodbabove is the same instance the inbox uses. No Wolverine setup needed. - One transaction. The inbox row and everything the handler saves through the same
DbContextcommit together. Changes made elsewhere (another database, an HTTP call) aren't covered; a handler that changes nothing through thatDbContextis logged once, as a hint. - One consumer name per service. Set
Messaging:Inbox:ConsumerName(default: the entry assembly's name) and callProcessAsync(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.
These settings are process-wide (every host in a process reads the same rows and messages). Running the
same AddGMIntegrationEvents setup in two hosts of one process, as integration tests often do, is fine;
registering a different upcaster for the same step, or different JSON options, throws instead of
silently changing how the other host reads events.
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.
A ProcessAsync handler that still fails on the broker's last delivery (the first try plus
Messaging:Retry retries) has its inbox row dead-lettered too, so IInboxAdministration lists it next to
the message in the broker's dead-letter queue. Such rows have RetriedByInboxWorker = false: fix the
cause and replay them from the broker (below), which hands them to the handler again. Requeueing in
IInboxAdministration applies to ingested rows only.
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.
A BrokerMessageFilter picks messages by type, original queue or routing key, caps how many, and with
DryRun only counts; messages it leaves alone stay in the queue in their order.
app.MapGet("/admin/broker/dead-letters", (IBrokerQueueAdministration broker) => broker.PeekAsync("gm.dead-letters"));
app.MapPost("/admin/broker/dead-letters/replay", (IBrokerQueueAdministration broker, string? type, bool dryRun) =>
broker.ReplayDeadLettersAsync("gm.dead-letters", new BrokerMessageFilter { MessageType = type, DryRun = dryRun }));
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 4.0
Nothing to change. Behaviour to know about in 4.1:
- Inbox rows of
ProcessAsynchandlers that fail on the broker's last delivery are now dead-lettered (shown byIInboxAdministrationand the backlog health check).RequeueAsync/RequeueAllDeadLetteredAsyncskip them; replay them from the broker's dead-letter queue. IBrokerQueueAdministrationgained filtered overloads; the old ones remain. If you implement the interface yourself (a test fake), implement the three new members.- Registering a different upcaster for the same event and version, or configuring different JSON options twice, now throws.
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. A service that finds such an exchange stops at startup with a message naming it. Either
delete those exchanges once (the services recreate them, and consumers rebind their queues, at startup),
set Messaging:RabbitMq:UpgradeExchanges to true in one service to have it delete and recreate them
(then restart the consumers, which rebind, and move anything that landed in gm.unrouted back), 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
DbContextdirectly; remove anyCodeGeneration.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; useWakeUp()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 theix_outbox_messages_orderingindex.inbox_messages:event_version(default 1).
Also changed:
IInboxProcessorhas overloads without a consumer name (custom implementations must add them).OutboxMessage.FromandPopulatetake an optionalorderingKey, andInboxMessage.Createan optionaleventVersion(recompile; source-compatible).- Payloads are written with
IntegrationEventSerializer.Optionsand 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 theix_outbox_messages_pendingindex.inbox_messages:attempts,ingested,next_attempt_at_utc,dead_lettered_at_utc,locked_by,locked_until_utc,trace_parent, and theix_inbox_messages_pendingindex.
Also changed:
IInboxStore<T>,IOutboxDbContext<T>andAddGMInboxProcessor<T>()are gone;AddGMInboxandAddGMOutboxRelaywork on theDbContextdirectly.IInboxProcessoris scoped (it shares the handler'sDbContext), 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
RetentionDaysto 0 to keep them. - Rows ingested by 1.x have
ingested = falseafter the migration, so the inbox worker ignores them. Finish them with your existing poller, or setingested = trueon 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 | Versions 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. |
-
net10.0
- GM.Messaging.Domain (>= 4.1.0)
- Microsoft.EntityFrameworkCore (>= 10.0.10)
- Microsoft.EntityFrameworkCore.Relational (>= 10.0.10)
- Microsoft.Extensions.Configuration.Binder (>= 10.0.10)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 10.0.10)
- Microsoft.Extensions.Hosting.Abstractions (>= 10.0.10)
- Microsoft.Extensions.Options (>= 10.0.10)
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 |