How to Implement the Transactional Outbox Pattern in ASP.NET Core 10 Using C#, EF Core and RabbitMQ – Complete Guide (2026)
Transactional Outbox in ASP.NET Core 10: EF Core and RabbitMQ
An order is saved successfully, but the warehouse never receives its message. The API returned success, RabbitMQ was briefly unavailable, and a simple retry around Publish cannot reconstruct an event that disappeared with the process. This is the dual-write problem the Transactional Outbox Pattern in ASP.NET Core 10 is designed to address.
This guide builds a complete local C# sample with EF Core 10, SQL Server, RabbitMQ.Client 7.2.2, a background relay, and an idempotent fulfillment consumer. It explains the failure windows, not just the happy path. Seven original diagrams show the boundaries and retry lifecycle.
Direct answer: Save the order and its integration-event payload in one SQL transaction. A background worker publishes committed outbox rows with RabbitMQ publisher confirms and records success afterward. Keep a stable event ID and deduplicate the consumer’s business effect in its own local transaction. Duplicate deliveries remain possible.
Execution disclosure: Documentation and current package APIs were researched on November 4, 2026. The application was manually reviewed but not compiled or executed: this environment has no .NET SDK, SQL Server, or running RabbitMQ test deployment. All responses and SQL observations are expected results. The diagrams are original illustrations; no execution screenshots or benchmark results are fabricated.
Why database-plus-message publishing can fail
A local SQL transaction can make several database changes atomic. It does not automatically enlist RabbitMQ in that same commit. Saving SQL then publishing leaves a crash window after the commit; publishing first can tell other services about an order that later rolls back.
A try-catch block helps while the process is alive, but its in-memory retry state can disappear. A distributed transaction would require coordination and support across resource managers; wrapping EF SaveChanges and a RabbitMQ call in an ordinary database transaction does not create that coordination.
The outbox makes the publication intent durable beside the business row. Microsoft’s outbox architecture guidance discusses this boundary, including the relational approach. Its Cosmos DB implementation is different from the SQL Server code below.
Architecture, guarantees, and tradeoffs
The API acknowledges the local order write. The relay and consumer can finish later, creating eventual consistency. In an e-commerce application, the order may be “accepted” before a fulfillment projection appears. A user-facing order status should communicate that state rather than imply shipping is complete.
| Approach | What it solves | What remains |
|---|---|---|
| Direct RabbitMQ publish | Sends immediately when the broker is reachable | SQL and publish can disagree after a failure |
| Transactional Outbox | Durably records business change and publication intent together | Requires a relay, monitoring, retries and consumer idempotency |
| Saga | Coordinates a multi-step business workflow and compensating actions | Still needs reliable messages; can use an outbox at each step |
An outbox and a Saga are complementary. Reserving stock, charging payment, and arranging shipment may form a Saga; each participant still needs a safe boundary for its outgoing messages. See Microsoft’s Saga guidance.
At-least-once is conditional, and is not exactly-once delivery
A relay can receive a broker confirm and crash before its SQL success update commits. On restart, it republishes the row. A consumer can commit its side effect and lose the connection before its ACK reaches RabbitMQ. That delivery may be sent again.
This sample provides durable retryable intent and deduplicates one database effect. Progress still depends on recoverable infrastructure, retained data, operational replay of quarantined failures, and appropriate broker durability. It does not promise survival of catastrophic storage loss or automatic completion after retries stop.
Project setup and research-backed package choices
Prerequisites: .NET 10 SDK, a compatible IDE, SQL Server/Express or LocalDB on Windows, Docker with Linux containers, and Postman. The checked RabbitMQ.Client package is 7.2.2 and is compatible with .NET 10. Current 7.x examples use IChannel and asynchronous APIs; do not paste older IModel/ConfirmSelect code into this project.
The Microsoft packages stay on the 10.0 servicing line. Inspect resolved versions with dotnet list package, align the EF provider/design/tool versions, and pin exact reviewed versions or a lock file before committing a production project. The sample uses the SQL Server provider.
Create Data, Contracts, Messaging, and Workers folders. Add all eight C# files below and replace the generated Program.cs. API, relay, and consumer share one host and one physical database for the local exercise. They execute separate transactions; no transaction spans SQL and RabbitMQ. Real services can split deployment roles and give the consumer its own database, keeping its inbox and effect in that same consumer database.
Run RabbitMQ with Docker
Save this as compose.yaml in the project folder. The 4.3 image line is explicit; review RabbitMQ installation guidance and pin a reviewed image digest for reproducible deployment.
Replace the password placeholder before starting Docker. Exclude .env from source control. These are local development credentials and must match the API secrets. A named volume retains broker data across container replacement; changing initial-user environment variables does not rotate credentials in an existing initialized volume.
The policy command uses Bash/WSL quoting. In another shell, enter the same policy keys through the RabbitMQ management UI or use that shell’s JSON quoting rules. It matches only orders.fulfillment and can be set before the queue exists. The management UI is at http://localhost:15672 after startup.
The source queue policy configures bounded failed deliveries, a DLX, reject-publish overflow, and quorum at-least-once dead lettering. Check that it applied. Without it, defaults differ and the poison queue may not receive rejected messages. Prefer policies over immutable queue x-arguments for settings operators need to change. Review the quorum-queue requirements and caveats, including the stream_queue feature flag on applicable deployments.
Configuration and development secrets
The LocalDB connection is Windows-only. Replace it for another SQL Server instance. TrustServerCertificate=True is a local-development concession; production requires a trusted SQL certificate and appropriate authentication. Secret Manager keeps values out of the repository but does not encrypt them; use a controlled production secret provider. See Microsoft’s secret-storage guidance.
Order, outbox, inbox, and fulfillment entities
The outbox ID is the event ID, not a new ID on every attempt. PublishedUtc means the broker accepted the publish under the configured confirms—not that the consumer completed. FailedUtc is a quarantine marker that stops automatic relay attempts.
The filtered index supports due-row polling. The inbox EventId primary key enforces deduplication even when two consumers race. A prior SELECT is only a fast path; the constraint provides the concurrency guarantee. The fulfillment OrderId key additionally protects this example’s one-fulfillment-per-order rule. See SQL Server unique indexes.
Persist a versioned, immutable integration-event snapshot. Do not serialize an EF entity graph and later reload changing fields during replay. This sample assumes one illustrative currency; production order contracts should represent currency and business rounding rules explicitly.
RabbitMQ topology and connection ownership
The direct exchange routes orders.created.v1 to a durable quorum queue. Persistent message properties and publisher confirms are also necessary for the intended safety boundary; durable topology alone is not enough. The dead-letter exchange routes failed consumer deliveries to orders.poison. A single Docker node is not a highly available cluster.
Each worker owns a long-lived connection/channel during a healthy session. The publisher uses its channel sequentially; the consumer dispatch concurrency and prefetch are one. Automatic recovery is disabled because the explicit worker loops recreate sessions, including initial-connection failures. Follow the official .NET API guide for channel concurrency and memory safety.
BackgroundService relay with publisher confirms
Why awaiting publish matters
With confirmation and confirmation tracking enabled, awaiting BasicPublishAsync waits for the broker outcome; a nack or mandatory return can fail that operation. Only after successful completion does the relay set PublishedUtc. An unroutable mandatory publish is not treated as success. See RabbitMQ’s reliable publishing tutorial.
The ten-second linked timeout bounds the application’s publish wait, not every network or SQL operation. Cancellation or connection loss can leave the outcome unknown. Retrying with the same ID is therefore necessary, and consumer idempotency remains essential.
Multiple instances and SQL locking
The relay begins a READ COMMITTED transaction and selects one due row with UPDLOCK and READPAST. The update lock prevents another cooperating relay from claiming that row until commit/rollback. READCOMMITTEDLOCK is included for this READ COMMITTED queue-read design when SQL Server’s READ_COMMITTED_SNAPSHOT option is enabled.
READPAST skips row locks, not page locks. The code is not a claim of lock-free processing or guaranteed fairness. Have a DBA review the execution plan, lock escalation, index, and actual isolation settings. The exact restrictions are in SQL Server table-hint documentation.
This teaching design intentionally holds a SQL transaction while waiting for one confirm. It reduces competing claims but consumes locks and a database connection during network work. High-throughput systems often use short atomic claims with expiring leases and ownership/fencing checks instead. Those designs require their own crash and lease-expiry analysis.
Retry scheduling and quarantine
Publish failures increment Attempts and schedule exponential delay with jitter, capped around a minute. Ten recorded publish failures quarantine that row. Connection failures before a row is selected reconnect every two seconds and do not increment a row’s Attempts. Database failures can roll back attempt updates too.
Quarantined rows retain their payload for investigation and controlled replay. Alert on them; do not label them “delivered.” Outbox failures are different from consumer poison messages in RabbitMQ. The former failed publication; the latter reached a consumer but could not be processed.
Idempotent consumer with an inbox transaction
The consumer commits InboxMessages and FulfillmentOrders in one SaveChanges transaction, then ACKs. If a concurrent delivery hits a unique-key violation, it verifies that the inbox ID actually exists before treating it as a duplicate. An unrelated uniqueness failure is not silently acknowledged.
The event body is deserialized before asynchronous database work; the callback does not retain RabbitMQ’s borrowed body buffer. Invalid contracts are rejected without requeue. Other failures wait briefly and use basic.reject with requeue, allowing the quorum delivery-limit policy to count failed attempts.
Version-sensitive detail: Current quorum queue documentation distinguishes basic.nack from basic.reject for failed-delivery accounting from RabbitMQ 4.3 onward. Do not assume an unlimited nack/requeue loop will reach a delivery limit. This sample uses reject; check the current poison-message behavior for your broker version.
Publisher confirms and consumer ACKs protect different boundaries. A confirm does not observe the consumer’s SQL commit. See RabbitMQ acknowledgements and confirms. Default dead lettering is not automatically lossless; the configured at-least-once quorum policy has resource and availability caveats. Review DLX configuration rather than merely adding a dead-queue name.
Deduplication protects only effects included in the inbox transaction. An email, payment, or HTTP call outside it needs an idempotency key or another durable outbox boundary. Keep inbox records at least as long as the permitted replay horizon; deleting them too early can repeat an old effect.
Save the order and event atomically in the API
The endpoint tracks both new rows, then makes one relational SaveChanges call. EF applies those changes transactionally; it either persists both or neither. The relay sees only committed rows. This follows EF Core’s transaction behavior; no RabbitMQ publish happens in the request’s transaction.
The API returns 201 Created for the local order, 400 for rejected input, and GET returns 200 or 404. A generic problem response handles unexpected errors without exposing a stack trace. For deeper error handling see the published ASP.NET Core IExceptionHandler guide.
Do not trust a client-supplied unit price in a real shop. This local exercise accepts it to avoid unrelated catalog code. Production calculates authoritative prices, taxes, stock rules, and permissions server-side. Also add API idempotency: a retried POST currently creates a second order with a new event ID. Consumer deduplication does not solve duplicate HTTP submissions.
Background services create fresh DI scopes for DbContext work instead of capturing a scoped context in the singleton hosted service. See Microsoft hosted-service guidance. Production can deploy the relay and consumer independently.
Migrations, Postman, and SQL verification
Add every code file and configure credentials before running these commands. LocalDB requires the API/worker identity to have access to that database; it runs under the local Windows user.
EF creates the Orders, OutboxMessages, InboxMessages, and FulfillmentOrders tables and the migration history. Do not mix EnsureCreated with migrations. For production use reviewed scripts/bundles and a separate schema-deployment identity. See EF migrations guidance. The published EF Core and SQL Server CRUD tutorial is a related foundation.
Open/import http://localhost:5080/openapi/v1.json in Development, or send requests directly in Postman. Built-in OpenAPI JSON does not install a Swagger UI. See Microsoft OpenAPI documentation.
Use the returned order GUID for GET /orders/{id}. With healthy dependencies, the relay should eventually log “Outbox confirmed” and the consumer “Fulfillment committed.” Depending on timing, the consumer can commit before the relay’s SQL success marker, so do not assume those log lines have a global order.
Expected healthy state: one order, one outbox row with PublishedUtc, one inbox EventId, and one fulfillment row totaling 158.00. UUIDs and timestamps vary. These are expected observations, not results captured here.
Failure tests that matter
| Test | Expected observation |
|---|---|
| Broker down during POST | SQL order and outbox persist; relay reconnects; consumer projection waits |
| Restart API with pending rows | Relay resumes from SQL, rather than relying on in-memory work |
| Publish succeeds, SQL marker fails | Replay may duplicate delivery; inbox prevents a second database effect |
| Consumer commits then disconnects before ACK | Redelivery is acknowledged after detecting the committed inbox record |
| Two app instances on different HTTP ports | Cooperating relays coordinate with SQL; consumers rely on the unique inbox key |
| Bad routing or persistent publish rejection | No success marker; retries or quarantine are visible |
| Poison payload / repeated consumer failure | Policy routes it to orders.poison after rejection/limit |
| Forced order/outbox save failure in an isolated integration test | Neither producer row commits |
Stop/start the broker with docker compose stop rabbitmq and docker compose start rabbitmq. Keep the volume. For the confirm/marker crash window, use an isolated test deployment and stop the process after publish but before SQL commit, or inject a database failure. A normal broker-down test does not exercise that ambiguity.
To exercise idempotency without manufacturing a second business event, replay the same committed event ID in a disposable lab:
After replay, expect a duplicate-skipped log and one inbox/effect row. Do not run broad UPDATE statements on production outbox rows. Production replay needs authorization, audit history, preserved payload/ID, and a repair plan for the original failure.
Security, monitoring, and production operations
Secure both boundaries
The local broker ports bind to loopback and the sample disables TLS for the exercise. Production needs private networking, a dedicated vhost, narrowly scoped permissions, protected credentials, and TLS with certificate/hostname validation. Set Rabbit UseTls=true and the correct TLS port/hostname only after configuring the broker. Never accept every certificate just to fix a handshake error; consult RabbitMQ TLS guidance.
Separate topology-provisioning privileges from publisher/consumer privileges where possible. Do not expose management UI ports publicly. Protect the API with authentication, authorization and rate limits; the published JWT authentication tutorial is related reading. Validate payload size and trusted event types.
Monitor backlog age, not just request success
- Pending outbox count and oldest pending age.
- Quarantined row count and failure-type trends.
- Publisher confirm latency, timeouts, returns, and nacks.
- Queue ready/unacknowledged depth, poison queue growth, redeliveries.
- Consumer processing latency, SQL failures, and duplicate skips.
- Database lock waits, deadlocks, connection use, and table/index growth.
Correlate OrderId, EventId, and request trace identifiers without logging credentials or sensitive payloads. The published C# logging article provides additional background. Alert when an accepted order remains unfulfilled beyond the business tolerance.
Ordering, throughput, retention, and retries
The sample does not guarantee per-order ordering across multiple events or workers. For OrderCreated followed by OrderUpdated, add aggregate sequence numbers and an appropriate partition/processing strategy. RabbitMQ FIFO alone does not undo concurrency, retry, or multi-publisher reordering.
Single-message confirms are intentionally easy to inspect, not a throughput recommendation. Batch or pipeline confirms only with explicit per-message outcome tracking. Use measured workloads to choose batch size, polling interval, prefetch, and concurrency. No invented messages-per-second claims are needed.
Archive/delete published rows in bounded batches after an agreed replay/audit period. Preserve pending/quarantined messages. Protect inbox retention and back up authoritative stores. A high-volume relay may use leases, CDC, or a maintained messaging framework; adopting one still requires understanding its guarantees and current package/licensing requirements.
Do not simply enable EF retrying execution strategies around these explicit transactions. Follow the provider’s transaction/retry coordination rules, and assume a replay can resend after an uncertain outcome. SQL uniqueness violations on insert are provider-specific errors, not automatically DbUpdateConcurrencyException.
Common errors and troubleshooting
ACCESS_REFUSED or broker connection failure
Verify the username, password, vhost, permissions, listener port, and container network path. Inside a container, localhost means that container. The initialized Docker volume retains its existing broker users. Repair credentials deliberately rather than deleting data to make an error disappear.
PRECONDITION_FAILED when declaring a queue
An existing queue may have different type/durability settings. The workers reconnect but cannot repair an incompatible declaration. Plan a migration or use a fresh disposable lab queue. Do not delete a production queue as a routine workaround.
Outbox rows exist but never become published
Check worker registration, broker connectivity, routing/bindings, due times, FailedUtc, and SQL locking settings. A successful API response only proves its local write. Inspect NextAttemptUtc and alert on age; do not repeatedly POST the same purchase to “retry the message.”
Duplicates despite publisher confirms
Confirms cannot atomically update SQL. Preserve the EventId and rely on inbox/effect atomicity. A redelivery flag is not a unique event identifier and cannot replace the unique-key check.
Consumer retries forever or poison messages disappear
Verify the policy matches the exact source queue, its effective keys, and the broker version’s reject/nack accounting. Confirm that the DLX and poison binding exist. Default dead lettering has different safety properties from the explicit quorum at-least-once policy.
READPAST or locking errors
Confirm READ COMMITTED isolation, RCSI configuration, and the exact hints used. Avoid mixing incompatible granularity hints. Examine page locks and deadlock reports instead of assuming READPAST skips every kind of blocking.
Frequently asked questions
Does Transactional Outbox guarantee exactly-once delivery?
No. It preserves publication intent atomically with business data. The relay can resend, and the broker can redeliver. Idempotency can protect a specific database effect, not make every external operation globally exactly-once.
Should PublishedUtc be set before or after publishing?
After the awaited broker confirm. Marking first can lose a message if publishing fails. Marking afterward leaves a duplicate window, which is why stable IDs and an inbox are needed.
Can the relay run on several ASP.NET Core instances?
Yes, with coordinated claims. This sample uses a SQL transaction and update locks. A process-local SemaphoreSlim would not coordinate separate instances.
Do I need an outbox if I already use a Saga?
A Saga coordinates workflow decisions and compensation. An outbox protects a participant’s local write/publication boundary. Many systems use both.
Why not publish directly in an EF interceptor?
Direct network publishing still creates an independent failure boundary and can occur before a commit is durable. An interceptor can help collect outbox rows, but it must not be mistaken for atomic broker delivery.
What happens when the maximum retry count is reached?
The row is quarantined, retained and alerted on. An operator repairs the cause and performs an audited replay with the same ID. Automatic progress has stopped; the system must not silently call it success.
Is the HTTP endpoint idempotent?
No. Retrying POST creates another order in this teaching sample. Production needs a separately designed client request/idempotency key and payload-consistency policy.
Conclusion
The useful guarantee is narrow and concrete: the order and the intent to publish commit together. Confirms, durable routing, SQL coordination, bounded retries, an inbox, and monitoring then protect the next boundaries. Treat duplicates and ambiguous outcomes as normal failure modes, verify the complete flow in an integration environment, and make pending/quarantined work operationally visible.
References and further reading
Primary documentation checked November 4, 2026. These references support the technical claims; the code and diagrams in this article are original. Package and broker behavior should be rechecked during upgrades.
- Microsoft: Transactional Outbox architecture
- Microsoft: EF Core transactions
- Microsoft: EF Core migrations
- Microsoft: BackgroundService and hosted services
- RabbitMQ: .NET client API guide
- RabbitMQ: reliable publishing tutorial
- RabbitMQ: confirms and consumer acknowledgements
- RabbitMQ: quorum queues, delivery limits and dead lettering
- RabbitMQ: dead-letter exchanges
- RabbitMQ: TLS
- RabbitMQ: installation
- Microsoft: SQL Server table hints
- Microsoft: Saga pattern
- Microsoft: unique indexes
- Microsoft: development secret storage
- Microsoft: OpenAPI generation
- NuGet: RabbitMQ.Client package
- Microsoft: EF Core SQL Server provider
Comments
Post a Comment