Step 03 — Write events to the outbox
What you'll do: save an OrderPlaced event in an outbox table, in the same transaction as the order.
The problem: dual writes
Shipping needs to know when an order is placed. The obvious code saves the order, then publishes a message to RabbitMQ:
await db.SaveChangesAsync(ct); // write 1: the database
await channel.BasicPublishAsync(...); // write 2: the brokerThis is a dual write: two systems, no shared transaction. Each line can fail on its own.
| What fails | Result |
|---|---|
| The publish (broker down, network blip, app restarts in between) | The order exists, but Shipping never hears about it. |
| Publish first, then the database save fails | Shipping ships an order that does not exist. |
Retrying does not fix it: the process can crash between the two lines, and then nobody knows that a retry is needed.
The transactional outbox fixes it by turning two writes into one. The event is saved as a row in an outbox_messages table, in the same database transaction as the order. Either both rows are saved or neither is. A separate publisher (next step) reads the table and sends the rows to the broker.
Steps
Create a contracts library for the events other services consume:
bashdotnet new classlib -o src/Orders.Contracts -n Orders.Contracts dotnet sln OutboxInbox.slnx add src/Orders.Contracts/Orders.Contracts.csproj dotnet add src/Orders.Api reference src/Orders.ContractsDelete the generated
Class1.csand the properties that Directory.Build.props already sets.Add the event, OrderPlaced.cs. It carries everything a consumer needs, so Shipping never has to call back into the Orders database:
csharppublic sealed record OrderPlaced(Guid OrderId, string CustomerEmail, DateTimeOffset PlacedAt, IReadOnlyList<OrderPlacedLine> Lines) { public const string MessageType = "orders.order-placed.v1"; } public sealed record OrderPlacedLine(string Sku, int Quantity);Add the outbox row, OutboxMessage.cs. It is an envelope: a few columns about the message, and the event itself as JSON.
csharppublic sealed class OutboxMessage { public Guid Id { get; init; } public required string Type { get; init; } public required string Payload { get; init; } public DateTimeOffset OccurredAt { get; init; } public DateTimeOffset? ProcessedAt { get; set; } public static OutboxMessage Create<T>(string type, T payload, DateTimeOffset occurredAt) => new() { Id = Guid.CreateVersion7(), Type = type, Payload = JsonSerializer.Serialize(payload, JsonSerializerOptions.Web), OccurredAt = occurredAt, }; }Column Meaning idUnique message id. Consumers use it to spot duplicates (step 06). typeVersioned event name, so consumers know how to read payload.payloadThe event as JSON ( jsonbin PostgreSQL).occurred_atWhen the event happened. The publisher sends the oldest first. processed_atEmpty until the broker has accepted the message. Map it in OrdersDbContext.cs:
csharppublic DbSet<OutboxMessage> OutboxMessages => Set<OutboxMessage>(); modelBuilder.Entity<OutboxMessage>(message => { message.HasKey(m => m.Id); message.Property(m => m.Type).HasMaxLength(200); message.Property(m => m.Payload).HasColumnType("jsonb"); message.HasIndex(m => m.OccurredAt).HasFilter("processed_at IS NULL"); });Add the outbox row next to the order in OrderEndpoints.cs:
csharpvar orderPlaced = new OrderPlaced( order.Id, order.CustomerEmail, order.PlacedAt, [.. order.Lines.Select(l => new OrderPlacedLine(l.Sku, l.Quantity))]); db.Orders.Add(order); db.OutboxMessages.Add(OutboxMessage.Create(OrderPlaced.MessageType, orderPlaced, order.PlacedAt)); // One SaveChangesAsync is one database transaction: the order and its event are saved together or not at all. await db.SaveChangesAsync(ct);Create the migration:
bashdotnet ef migrations add AddOutbox --project src/Orders.Api --output-dir Data/Migrations
Check it works
dotnet build OutboxInbox.slnx -warnaserror
dotnet run --project src/Orders.Apicurl -X POST localhost:5080/orders -H 'content-type: application/json' \
-d '{"customerEmail":"alex@contoso.com","items":[{"sku":"BOOK-1","quantity":2},{"sku":"MUG-7","quantity":1}]}'
docker compose exec postgres psql -U postgres -d orders \
-c "select id, type, occurred_at, processed_at from outbox_messages" id | type | occurred_at | processed_at
--------------------------------------+------------------------+-------------------------------+--------------
01a21a88-f915-7e89-be87-8e0b0a292305 | orders.order-placed.v1 | 2026-11-27 01:05:13.954179+00 |The payload is the event as JSON (jsonb stores keys in its own order):
{"lines": [{"sku": "BOOK-1", "quantity": 2}, {"sku": "MUG-7", "quantity": 1}],
"orderId": "01a21a88-f8e2-7385-9c4d-e7f2cba9170b", "placedAt": "2026-11-27T01:05:13.954179+00:00",
"customerEmail": "alex@contoso.com"}processed_at is empty: nothing publishes yet. That is the next step.
Why it works
One transaction. EF Core wraps each SaveChangesAsync in a database transaction. A transaction is a group of writes the database applies completely or not at all. Because the order and the outbox row are in the same call, there is no moment where one exists without the other, even if the process dies halfway.
The outbox is a queue inside your database. Rows wait there until a publisher has handed them to the broker. If the broker is down for an hour, orders keep working and the rows simply wait. The cost is a delay (usually under a second) and a background process to run.
Why store JSON and a type name. The publisher does not need to understand events; it copies payload to the message body and type to a header. Adding a new event later means adding a new record and a new OutboxMessage.Create call, with no change to the publisher. JsonSerializerOptions.Web gives camelCase names, the usual choice for messages read by other languages too.
Partial index. HasFilter("processed_at IS NULL") creates an index that only contains unprocessed rows. The publisher's query stays fast even when millions of processed rows are kept.
Alternatives. Some teams skip the outbox table and read the database's change log instead (change data capture, for example Debezium). Messaging frameworks such as MassTransit, NServiceBus and Wolverine ship an outbox you switch on. This guide builds it by hand so you can see what those tools do for you.