When an ASP.NET Core MVC action saves business state to a relational database and then publishes a domain event or webhook to a message broker, two distinct failure modes emerge:
Database commits, broker publish fails (network blip, broker restart, timeout): Your database records the state change, but downstream consumers never receive the event—causing silent data drift.
Broker publish succeeds before or outside the transaction, database rolls back (constraint violation, deadlock, validation failure): Downstream consumers react to an event for data that does not exist.
The Transactional Outbox Pattern eliminates dual-write inconsistency by persisting outbox messages inside the exact same database transaction as your domain changes. An EF Core SaveChangesInterceptor harvests domain events raised on tracked entities right before SaveChangesAsync commits, writes OutboxMessage rows into the same transaction, and a BackgroundService backed by a bounded Channel<T> (plus periodic polling for crash recovery) dispatches pending messages reliably with retry/backoff and idempotent consumer handling.
1. Architectural Blueprint & Delivery Flow
Plaintext
[MVC Controller Action]
│ raises domain event on aggregate entity
▼
[AppDbContext.SaveChangesAsync()]
│ triggers SaveChangesInterceptor.SavingChangesAsync()
▼
[OutboxSaveChangesInterceptor]
│ collects domain events from ChangeTracker
│ serializes & adds OutboxMessage rows to same DbContext transaction
▼
[Database COMMIT] ──(atomic: domain row + outbox row commit together)
│
├─> signals ChannelWriter<Guid> (fast wake-up path)
│
▼
[OutboxDispatcherBackgroundService]
├─ drains ChannelReader<Guid> + periodic fallback poll (catches un-notified rows after restart)
├─ claims batch with row-level lock / atomic status transition
├─ publishes via IOutboxMessagePublisher (broker / event bus)
└─ marks ProcessedAtUtc or increments RetryCount + NextAttemptAtUtc with backoff
Component | Responsibility | Failure & Recovery Behavior |
Domain Entity ( | Records domain events during state transitions without knowing about EF Core or brokers. | Cleared once harvested by the interceptor. |
| Extracts uncommitted domain events and inserts | Rolls back automatically if the database transaction fails. |
| Provides near-real-time dispatch while a periodic sweep catches missed/retryable rows. | Bounded channel with |
Outbox Worker Retry Policy | Retries transient broker errors with exponential backoff; isolates poison messages after max attempts. | Never drops unacknowledged messages silently; logs failure details and |
2. Domain Model, Outbox Entity, and EF Core Configuration
Let's model a clean aggregate (Invoice), an IDomainEvent contract, and an OutboxMessage entity persisted in the same AppDbContext.
C#
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
public interface IDomainEvent
{
Guid EventId { get; }
DateTimeOffset OccurredAtUtc { get; }
}
public sealed record InvoiceIssuedDomainEvent(
Guid EventId,
Guid InvoiceId,
string InvoiceNumber,
decimal GrossAmount,
DateTimeOffset OccurredAtUtc
) : IDomainEvent;
public abstract class Entity
{
private readonly List<IDomainEvent> _domainEvents = [];
public IReadOnlyCollection<IDomainEvent> DomainEvents => _domainEvents.AsReadOnly();
protected void RaiseDomainEvent(IDomainEvent domainEvent)
{
_domainEvents.Add(domainEvent);
}
public void ClearDomainEvents()
{
_domainEvents.Clear();
}
}
public sealed class Invoice : Entity
{
public Guid Id { get; private set; }
public string InvoiceNumber { get; private set; } = string.Empty;
public decimal GrossAmount { get; private set; }
public string Status { get; private set; } = "Draft";
public DateTimeOffset CreatedAtUtc { get; private set; }
private Invoice() { }
public static Invoice Issue(string invoiceNumber, decimal grossAmount, DateTimeOffset nowUtc)
{
if (string.IsNullOrWhiteSpace(invoiceNumber))
{
throw new ArgumentException("Invoice number is required.", nameof(invoiceNumber));
}
if (grossAmount <= 0m)
{
throw new ArgumentOutOfRangeException(nameof(grossAmount), "Gross amount must be positive.");
}
var invoice = new Invoice
{
Id = Guid.NewGuid(),
InvoiceNumber = invoiceNumber.Trim().ToUpperInvariant(),
GrossAmount = decimal.Round(grossAmount, 2, MidpointRounding.AwayFromZero),
Status = "Issued",
CreatedAtUtc = nowUtc
};
invoice.RaiseDomainEvent(new InvoiceIssuedDomainEvent(
EventId: Guid.NewGuid(),
InvoiceId: invoice.Id,
InvoiceNumber: invoice.InvoiceNumber,
GrossAmount: invoice.GrossAmount,
OccurredAtUtc: nowUtc));
return invoice;
}
}
public sealed class OutboxMessage
{
public Guid Id { get; set; }
public string EventType { get; set; } = string.Empty;
public string PayloadJson { get; set; } = string.Empty;
public DateTimeOffset OccurredAtUtc { get; set; }
public DateTimeOffset? ProcessedAtUtc { get; set; }
public DateTimeOffset NextAttemptAtUtc { get; set; }
public int RetryCount { get; set; }
public string? LastError { get; set; }
}
public sealed class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options)
: base(options)
{
}
public DbSet<Invoice> Invoices => Set<Invoice>();
public DbSet<OutboxMessage> OutboxMessages => Set<OutboxMessage>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Invoice>(builder =>
{
builder.HasKey(x => x.Id);
builder.Property(x => x.InvoiceNumber).HasMaxLength(40).IsRequired();
builder.HasIndex(x => x.InvoiceNumber).IsUnique();
builder.Property(x => x.GrossAmount).HasColumnType("decimal(18,2)");
builder.Property(x => x.Status).HasMaxLength(24).IsRequired();
});
modelBuilder.Entity<OutboxMessage>(builder =>
{
builder.HasKey(x => x.Id);
builder.Property(x => x.EventType).HasMaxLength(256).IsRequired();
builder.Property(x => x.PayloadJson).IsRequired();
builder.Property(x => x.LastError).HasMaxLength(2000);
// Supports fast polling of unprocessed messages eligible for retry
builder.HasIndex(x => new { x.ProcessedAtUtc, x.NextAttemptAtUtc, x.OccurredAtUtc });
});
}
}
3. EF Core SaveChangesInterceptor & Wake-Up Signaler
OutboxSaveChangesInterceptor hooks into SavingChangesAsync before EF Core flushes changes to the database. Any OutboxMessage entities added here become part of the exact same DbContext transaction as the Invoice insert or update.
C#
using System.Text.Json;
using System.Threading.Channels;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
public sealed class OutboxNotificationQueue
{
private readonly Channel<Guid> _channel;
public OutboxNotificationQueue(int capacity = 4096)
{
var options = new BoundedChannelOptions(capacity)
{
FullMode = BoundedChannelFullMode.DropOldest,
SingleReader = true,
SingleWriter = false
};
_channel = Channel.CreateBounded<Guid>(options);
}
public ChannelReader<Guid> Reader => _channel.Reader;
public void TryNotify(Guid outboxMessageId)
{
_channel.Writer.TryWrite(outboxMessageId);
}
}
public sealed class OutboxSaveChangesInterceptor : SaveChangesInterceptor
{
private static readonly JsonSerializerOptions SerializerOptions = new(JsonSerializerDefaults.Web);
private readonly OutboxNotificationQueue _notificationQueue;
public OutboxSaveChangesInterceptor(OutboxNotificationQueue notificationQueue)
{
_notificationQueue = notificationQueue;
}
public override ValueTask<InterceptionResult<int>> SavingChangesAsync(
DbContextEventData eventData,
InterceptionResult<int> result,
CancellationToken cancellationToken = default)
{
if (eventData.Context is not null)
{
AppendOutboxMessages(eventData.Context);
}
return ValueTask.FromResult(result);
}
private void AppendOutboxMessages(DbContext dbContext)
{
var entitiesWithEvents = dbContext.ChangeTracker
.Entries<Entity>()
.Where(e => e.Entity.DomainEvents.Count > 0)
.Select(e => e.Entity)
.ToList();
if (entitiesWithEvents.Count == 0)
{
return;
}
DateTimeOffset nowUtc = DateTimeOffset.UtcNow;
var outboxEntries = new List<OutboxMessage>();
foreach (Entity entity in entitiesWithEvents)
{
foreach (IDomainEvent domainEvent in entity.DomainEvents)
{
Type eventClrType = domainEvent.GetType();
string payloadJson = JsonSerializer.Serialize(domainEvent, eventClrType, SerializerOptions);
outboxEntries.Add(new OutboxMessage
{
Id = domainEvent.EventId == Guid.Empty ? Guid.NewGuid() : domainEvent.EventId,
EventType = eventClrType.AssemblyQualifiedName ?? eventClrType.FullName ?? eventClrType.Name,
PayloadJson = payloadJson,
OccurredAtUtc = domainEvent.OccurredAtUtc == default ? nowUtc : domainEvent.OccurredAtUtc,
NextAttemptAtUtc = nowUtc,
RetryCount = 0
});
}
entity.ClearDomainEvents();
}
dbContext.Set<OutboxMessage>().AddRange(outboxEntries);
foreach (OutboxMessage msg in outboxEntries)
{
_notificationQueue.TryNotify(msg.Id);
}
}
}
Join the conversation! Your thoughts help the community grow.