Skip to content

Lesson 6 of 9 · 27m

Transactions, Concurrency, and Resilient Writes

Design EF Core writes around units of work, optimistic concurrency, execution strategies, and idempotency rather than assuming the network behaves.

A payment-adjacent system I reviewed once retried the whole transaction when a network failure happened after commit but before the response arrived. The database had committed; the client saw a timeout; the retry charged the customer twice. Resilience is not 'try it again.' Resilience is knowing exactly which operations are atomic, which are retryable, and how you recognize work that already happened.

SaveChanges is a unit of work, not a business invariant

One SaveChangesAsync call is atomic within its transaction, but many workflows span multiple writes or services. Be explicit when the invariant needs a broader transaction:

await using var tx = await db.Database.BeginTransactionAsync(ct);

db.Orders.Add(order);
db.InventoryReservations.AddRange(reservations);
await db.SaveChangesAsync(ct);

await tx.CommitAsync(ct);

Keep transactions short. Do not call external APIs inside them, do not wait for user input, and do not hold locks while doing unrelated computation. Long transactions turn business convenience into database contention.

Optimistic concurrency is a user-experience decision

Add a concurrency token where stale writes matter:

public sealed class Order
{
    public Guid Id { get; set; }
    public string Status { get; set; } = "open";

    [Timestamp]
    public byte[] RowVersion { get; set; } = Array.Empty<byte[]>();
}

When two users update the same row, the second save raises DbUpdateConcurrencyException. Catching it is not enough. Decide whether to show a conflict, merge fields, reload and retry, or overwrite intentionally. Correct behavior belongs to the workflow.

Execution strategies retry only safe units

Providers such as SQL Server support execution strategies that retry transient failures:

options.UseSqlServer(connectionString, sql =>
{
    sql.EnableRetryOnFailure(maxRetryCount: 5, maxRetryDelay: TimeSpan.FromSeconds(5), errorNumbersToAdd: null);
});

Retries must wrap the entire retryable unit, not random individual statements. If the operation is not idempotent, retrying after an uncertain commit can duplicate effects. For multi-statement transactions, use the execution strategy explicitly so all work is retried as one unit.

Idempotency is the real network contract

Give mutating operations idempotency keys when clients can retry:

POST /payments
Idempotency-Key: 7f2a0d0a-4a3d-4f64-a1f5-1ff3a7a0f2d1

Store the key with the result or processing state, enforce uniqueness, and return the original result on replay. The key must be scoped to the caller and operation so unrelated tenants cannot collide. Queue consumers need the same discipline: message delivery is usually at-least-once, not exactly-once.

Partial failure is the normal case

Distributed workflows fail between steps. A database write can succeed while a queue publish fails. The outbox pattern addresses this by writing the domain change and outgoing message in one transaction, then publishing asynchronously. That machinery is not fashion; it is what prevents inventory being decremented without the fulfillment event ever leaving the building.

Field notes

  • A unique constraint is often the safest concurrency control. Application-level checks without constraint enforcement race under load.
  • Deadlocks are frequently caused by updating rows in inconsistent order across transactions; normalize update ordering where possible.
  • Do not retry on fixed tiny intervals. Use jittered backoff so synchronized clients do not hammer a recovering dependency.
  • Timeout, cancellation, and retry are different controls. Conflating them produces systems that give up too late and retry too aggressively.

Was this lesson helpful?

Sign in to rate