Distributed failure and idempotency
Distributed failure and idempotency
A distributed timeout means the caller lacks a result, not that the remote operation failed. Idempotency and saga compensation make partial failures recoverable without pretending that independent databases share one transaction.
If a reservation commits but the reply is lost, retrying with a new request ID may reserve twice. Reuse an operation key scoped to the tenant and operation type, and bind it to a normalized payload or fingerprint. Persist the outcome and business update atomically; same key/different payload should conflict. A retention window must cover the supported retry horizon. In-flight requests need concurrency control, not a local dictionary alone. A saga coordinates local commits and compensating actions. Compensation is a new domain action, not time travel; it can fail, require retry or human reconciliation. A durable saga stores progress, stable command IDs, deadlines and recovery state; choreography distributes coordination through events, while orchestration makes steps explicit. If the result is unknown, reconcile it before releasing resources or sending a contradictory command. Use correlation IDs for tracing, not authentication. Never retry arbitrary non-idempotent actions. The following examples are single-process sequential models without durable storage.
Baseline: .NET 10 / C# 14. All C# results below are reasoned, not executed. Offline models and the separate Aspire lab are explicitly distinguished.
Recover a lost response using one operation key
Simulate the first response being lost after the stock change; repeat the identical operation.
Use the archived Fixture.csproj with an approved .NET 10 SDK. No third-party packages are required. Inspect the project, then build and run with the approved SDK.
using System;using System.Collections.Generic;var outcomes = new Dictionary<string, (int Units, bool Result)>();int stock = 5;bool Reserve(string key, int units) { if (outcomes.TryGetValue(key, out var saved)) { if (saved.Units != units) throw new InvalidOperationException("conflict"); return saved.Result; } bool ok = units > 0 && units <= stock; if (ok) stock -= units; outcomes.Add(key, (units, ok)); return ok;}_ = Reserve("tenant-A/reserve/1", 2);Console.WriteLine("reply lost");Console.WriteLine($"retry={Reserve("tenant-A/reserve/1", 2)}; stock={stock}");try { Reserve("tenant-A/reserve/1", 1); }catch (InvalidOperationException) { Console.WriteLine("conflict"); }Expected result (not executed):
reply lostretry=True; stock=3conflictThe dictionary models key/payload binding. It is not crash-safe or thread-safe; durable atomic uniqueness and authenticated tenant identity are required.
Compensate a committed reservation
Reserve two units, simulate a definitive shipping failure, then compensate twice with the same reservation identity.
Use the archived Fixture.csproj with an approved .NET 10 SDK. No third-party packages are required. Inspect the project, then build and run with the approved SDK.
using System;using System.Collections.Generic;int stock = 5;var active = new Dictionary<string, int> { ["R1"] = 2 };stock -= 2;Console.WriteLine($"reserved: {stock}");Console.WriteLine("shipping rejected");foreach (var id in new[] { "R1", "R1" }) { if (active.Remove(id, out int units)) stock += units; Console.WriteLine($"after release: {stock}");}Expected result (not executed):
reserved: 3shipping rejectedafter release: 5after release: 5Release is a separate idempotent operation, not a distributed rollback. Real implementations must preserve reservation identity, tombstones and atomic update semantics.
Track compensation failure instead of declaring success
A finite simulated schedule records pending reconciliation after two failed compensation attempts, then succeeds on an explicit later attempt.
Use the archived Fixture.csproj with an approved .NET 10 SDK. No third-party packages are required. Inspect the project, then build and run with the approved SDK.
using System;string state = "Compensating";foreach (bool success in new[] { false, false }) { if (success) { state = "Cancelled"; break; } Console.WriteLine("release failed");}if (state != "Cancelled") state = "NeedsReconciliation";Console.WriteLine(state);bool verifiedRelease = true;if (state == "NeedsReconciliation" && verifiedRelease) state = "Cancelled";Console.WriteLine(state);Expected result (not executed):
release failedrelease failedNeedsReconciliationCancelledA bounded retry budget stops automatic attempts but does not erase the obligation. Persist the state and reconcile against the authoritative service before closing the saga.
Apply the concept
Model a workflow where reservation succeeds, shipping times out, and the reply is unknown. Specify IDs, timeout behavior, a recovery decision and a terminal-state invariant.
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
Distributed failure and idempotency — knowledge check
Apply the lesson concepts to the following scenarios.
What does a timeout after a remote command establish?
What should happen when a key is reused with changed payload?
What makes a durable idempotency record useful?
Is compensation a universal distributed rollback?
What should exhausted compensation retries produce?