Outbox and retry policy
Outbox and retry policy
A transactional outbox stores the intent to publish alongside the business update in one local database transaction. A relay later sends the message, records progress, and tolerates uncertain delivery outcomes.
Writing a database row and sending a broker message are two independent effects unless a real shared transaction contract covers them. If a database commits and publication fails, downstream systems miss the event; publishing first can expose a change that later rolls back. The outbox records immutable event ID, aggregate identity, schema version, payload and dispatch status in the same commit as the change. A relay scans pending rows in bounded batches, claims them using a provider-appropriate lease or locking protocol, sends and awaits confirmation, then marks sent. A crash after confirmation but before marking sent may produce duplicates; receivers need idempotent inbox processing. Marking sent before confirming can lose events. A production relay needs ordering policy, lease expiry, retry scheduling, poison handling, retention, backlog alerts, and a way to inspect failures without replaying blindly. Exponential backoff with jitter reduces synchronized retries; it does not eliminate them or guarantee recovery. Cap attempts, maximum delay and total elapsed budget. A confirmation for an older lease must not mark a newly claimed event sent: check the current lease generation in a conditional durable update. Broker acceptance does not prove that a consumer has committed the business effect. The local examples do not implement a distributed lease or a live broker.
Baseline: .NET 10 / C# 14. All C# results below are reasoned, not executed. Models and isolated local integration fixtures are explicitly distinguished.
Commit stock and an outbox record together
Run a rollback followed by a commit. Use a single isolated relational transaction per attempt.
Use the archived Fixture.csproj with an approved .NET 10 SDK. Inspect dependency graph, restore only approved dependencies, build and run. Requires Microsoft.Data.Sqlite 10.0.15; uses only an isolated in-memory database.
using System;using Microsoft.Data.Sqlite;using var db = new SqliteConnection("Data Source=:memory:"); db.Open();using (var c = db.CreateCommand()) { c.CommandText = "CREATE TABLE Stock(Qty INTEGER NOT NULL); INSERT INTO Stock VALUES(10); CREATE TABLE Outbox(Id TEXT PRIMARY KEY, Payload TEXT NOT NULL);"; c.ExecuteNonQuery(); }foreach (bool commit in new[] { false, true }) { using var tx = db.BeginTransaction(); using var update = db.CreateCommand(); update.Transaction = tx; update.CommandText = "UPDATE Stock SET Qty=Qty-2 WHERE Qty>=2"; if (update.ExecuteNonQuery()!=1) throw new InvalidOperationException(); using var append = db.CreateCommand(); append.Transaction = tx; append.CommandText = "INSERT INTO Outbox VALUES($id,$payload)"; append.Parameters.AddWithValue("$id","evt-1"); append.Parameters.AddWithValue("$payload","stock reduced by 2"); append.ExecuteNonQuery(); if (commit) tx.Commit(); else tx.Rollback(); using var read = db.CreateCommand(); read.CommandText = "SELECT Qty,(SELECT COUNT(*) FROM Outbox) FROM Stock"; using var r = read.ExecuteReader(); r.Read(); Console.WriteLine($"commit={commit}; stock={r.GetInt32(0)}; events={r.GetInt32(1)}");}Expected result (not executed):
commit=False; stock=10; events=0commit=True; stock=8; events=1The business row and event survive or roll back together. The in-memory DB is only a transaction lab, not a durable store across process restart.
Trace the uncertain publication window
A pure model holds an event pending until the relay marks it sent. Simulate a crash after first broker acceptance.
Use the archived Fixture.csproj with an approved .NET 10 SDK. Inspect dependency graph, restore only approved dependencies, build and run.
using System;using System.Collections.Generic;var received = new HashSet<string>();int effects = 0, deliveries = 0;bool sent = false;void Dispatch(bool crashAfterAccept) { if (sent) return; deliveries++; if (received.Add("evt-1")) effects++; if (!crashAfterAccept) sent = true;}Dispatch(true);Console.WriteLine($"pending={!sent}; effects={effects}");Dispatch(false);Console.WriteLine($"pending={!sent}; deliveries={deliveries}; effects={effects}");Expected result (not executed):
pending=True; effects=1pending=False; deliveries=2; effects=1This single-threaded model demonstrates ordering, not real crash recovery. Persist the outbox and inbox separately and atomically with their respective business changes.
Cap relay retries and delay
Compute a deterministic backoff schedule without sleeping. Jitter is intentionally absent so the expected values can be checked.
Use the archived Fixture.csproj with an approved .NET 10 SDK. Inspect dependency graph, restore only approved dependencies, build and run.
using System;int attempts = 4, delay = 100, maxDelay = 250;for (int attempt = 1; attempt <= attempts; attempt++) { Console.WriteLine($"attempt {attempt}: failed"); if (attempt == attempts) { Console.WriteLine("quarantine for review"); break; } Console.WriteLine($"next delay={delay}ms"); delay = Math.Min(maxDelay, delay * 2);}Expected result (not executed):
attempt 1: failednext delay=100msattempt 2: failednext delay=200msattempt 3: failednext delay=250msattempt 4: failedquarantine for reviewProduction scheduling should persist NextAttemptAt and a retry classification, include bounded random jitter and honor a total deadline. Quarantine does not erase the event.
Apply the concept
List outcomes for failure before DB commit, after commit before send, after broker acceptance before marking sent, and after marking sent.
Use the manual practice and knowledge check. Do not deploy or publish these fixtures.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Outbox and retry policy — knowledge check
Apply the lesson concepts to the following scenarios.
What does the outbox transaction include?
What can happen after acceptance but before marking sent?
Why avoid marking sent before confirmation?
Why add jitter to backoff?
What must a lease-based relay do after a crash?