Volume 3 · Chapter 6 — Entity Framework Core and Data Access Engineering
Transactions and Concurrency Control
6.1 Introduction
Enterprise applications must keep data consistent when many users and services touch the same data concurrently - nowhere more so than in banking, where an incorrect concurrent update means real financial error. Transactions guarantee all-or-nothing consistency, and concurrency control prevents conflicting updates from corrupting data. The most important practical technique in EF Core is optimistic concurrency with row versioning, which detects conflicts without holding locks.
6.2 ACID and EF Core Transactions
Transactions provide ACID guarantees: Atomicity (all or nothing), Consistency (rules stay valid), Isolation (concurrent transactions don’t interfere incorrectly), Durability (committed data survives failures). EF Core automatically wraps a singleSaveChangesin a transaction, so all the changes it produces commit together. For multiple operations that must succeed or fail as a unit, you use an explicit transaction.
await using var tx = await context.Database.BeginTransactionAsync(ct);
try
{
context.Accounts.Update(from);
context.Accounts.Update(to);
await context.SaveChangesAsync(ct);
// ... another operation in the same transaction ...
await tx.CommitAsync(ct);
}
catch
{
await tx.RollbackAsync(ct); // all-or-nothing
throw;
}
6.3 Optimistic Concurrency
Optimistic concurrency assumes conflicts are rare: it doesn’t lock, but detects at save time whether another process changed the row since you read it, using a version/rowversion column. If the version changed, EF Core throwsDbUpdateConcurrencyException, and you resolve the conflict (retry, merge, or inform the user). This scales well because it holds no locks.
sequenceDiagram autonumber participant A as User A participant B as User B participant DB as Account (Version 5) A->>DB: read (Version 5) B->>DB: read (Version 5) B->>DB: update -> Version 6 (succeeds) A->>DB: update expecting Version 5 DB--xA: conflict! row is Version 6 -> DbUpdateConcurrencyException A->>A: reload, re-apply, retry
public sealed class Account
{
public Guid Id { get; set; }
public decimal Balance { get; set; }
[Timestamp] public byte[] RowVersion { get; set; } = default!; // concurrency token
}
// EF adds "WHERE Id=@id AND RowVersion=@original" to the UPDATE; 0 rows affected -> conflict.
6.4 Pessimistic Concurrency and Deadlocks
Pessimistic concurrency locks rows while modifying them, preventing conflicts but reducing scalability and risking blocking and deadlocks - reserved for critical sections where a conflict is unacceptable and rare. A deadlock occurs when two transactions each hold a lock the other needs; prevent with consistent lock ordering, short transactions, proper indexing, and retry handling.
6.5 Retries and Distributed Consistency
Transient failures (network blips, deadlock victims) should be retried with EF Core’s execution-strategy retry-on-failure, combined with idempotency so a retry doesn’t double-apply. Across services, distributed ACID transactions don’t scale, so systems use sagas, compensating transactions, and the outbox pattern with eventual consistency (Volume 6 and 9 cover these in depth).
builder.Services.AddDbContext<AppDbContext>(o =>
o.UseSqlServer(cs, sql => sql.EnableRetryOnFailure())); // retry transient failures
What is the difference between optimistic and pessimistic concurrency, and when do you use each?
Both prevent concurrent updates from corrupting data, but they take opposite strategies. Optimistic concurrency assumes conflicts are rare, so it doesn’t lock anything; instead it detects at save time whether the data changed since you read it. In EF Core you add a concurrency token - typically a rowversion/timestamp column - and EF includes it in the UPDATE’s WHERE clause, so if another process modified the row (changing its version) since you loaded it, the UPDATE affects zero rows and EF throwsDbUpdateConcurrencyException; you then resolve the conflict by reloading and retrying, merging, or informing the user. Because it holds no locks, optimistic concurrency scales well and avoids blocking, which is why it’s the default choice for most web and high-concurrency scenarios where actual conflicts on the same row are infrequent. Pessimistic concurrency assumes conflicts are likely (or unacceptable), so it locks the data when you read/modify it, preventing any other transaction from changing it until you’re done. This guarantees no conflicting update can occur, which suits critical sections where a lost update would be catastrophic and contention is high, but the cost is reduced scalability (other transactions block waiting for the lock), potential for blocking chains, and deadlock risk. So I use optimistic concurrency by default - it’s scalable, lock-free, and handles the common case of rare conflicts by detecting and retrying - and I reserve pessimistic concurrency for the specific hot spots where conflicts are frequent or a conflict simply must not be allowed and the serialization cost is acceptable (e.g. decrementing scarce inventory, certain financial operations), often combined with careful lock ordering and short transactions to avoid deadlocks. The decision hinges on conflict likelihood and the cost of a conflict versus the cost of locking: rare conflicts and a need to scale favor optimistic; frequent conflicts or intolerable conflict cost favor pessimistic. Many systems use optimistic concurrency broadly and pessimistic locking narrowly where truly needed.
How does optimistic concurrency detect a conflict in EF Core, and how do you handle the exception?
It detects conflicts using a concurrency token that EF Core checks at update time. You mark a property as a concurrency token - most commonly a database-managed rowversion/timestamp column (via[Timestamp]or FluentIsRowVersion), which the database automatically changes on every update. When you load an entity, EF records the token’s original value. When you save a change, EF generates an UPDATE whose WHERE clause includes both the primary keyandthe original token value (e.g.WHERE Id=@id AND RowVersion=@original). If no other process modified the row, the token still matches and the UPDATE affects one row, succeeding. But if another process updated the row in between, the database changed the rowversion, so your WHERE clause matches zero rows - EF sees that zero rows were affected and throws aDbUpdateConcurrencyException, meaning “someone else changed this since you read it.” To handle it, I catchDbUpdateConcurrencyExceptionand resolve the conflict according to the business rules. The common resolutions are: reload the current database values from the exception’s entries, decide how to reconcile (client wins - reapply my changes over the latest; store wins - discard my changes and take the current values; or merge property by property), update the original values to the current ones so the next save’s token matches, and retry the save; or, for user-facing scenarios, surface the conflict to the user (“this record was changed by someone else, please review”) so they can decide. For automated retries I loop with a bounded number of attempts and ensure the operation is idempotent so retrying is safe. The key points to convey: the concurrency token in the UPDATE’s WHERE clause is the detection mechanism (zero rows affected = conflict),DbUpdateConcurrencyExceptionis how EF signals it, and handling means reloading, reconciling per business rules, and retrying (or informing the user) - which gives correct lost-update prevention without holding locks, at the cost of having to handle the occasional conflict.
A banking system processes account transfers from multiple channels and occasionally overwrites balances incorrectly. How do you make it reliable?
The incorrect balance overwrites are a lost-update problem: multiple channels read an account balance concurrently and write back based on their stale read, so one update clobbers another - a classic race condition on shared financial state, which is unacceptable for money. I’d fix it with a combination of proper concurrency control, transactional boundaries, idempotency, and auditing. First, concurrency control: I’d add optimistic concurrency with a rowversion token on the account, so that when a transfer updates a balance, EF includes the original version in the WHERE clause and the update fails (throwsDbUpdateConcurrencyException) if another channel changed the balance in the meantime - detecting the conflict instead of silently overwriting. On conflict, the operation reloads the current balance, re-evaluates the transfer against the fresh state (including re-checking funds), and retries, with a bounded retry loop; this prevents lost updates while scaling without locks. For the highest-contention or must-not-fail operations I might use pessimistic locking on the specific account rows within a short transaction, or better, structure balance changes as atomic operations (e.g. an atomic conditional update “set balance = balance - amount WHERE balance >= amount”) so the check-and-decrement can’t race. Second, transactional boundaries: each transfer’s debit and credit (and any ledger entries) must be one atomic transaction so a transfer is all-or-nothing, never leaving one side applied. Where a transfer spans services or systems that can’t share a transaction, I’d use a saga with compensation rather than a distributed transaction, with the outbox pattern for reliable events. Third, idempotency: because channels retry on timeouts, each transfer carries an idempotency key so a retried transfer returns the original result rather than applying twice - essential to avoid double debits, and it composes with the concurrency retries. Fourth, auditing and correctness verification: every balance change is recorded as an immutable ledger entry (ideally the balance is derived from or reconciled against the ledger), so there’s a complete audit trail and I can detect and investigate any discrepancy, and I’d add reconciliation checks. I’d also add retry-on- transient-failure with EF’s execution strategy for deadlock victims and network blips, combined with the idempotency so retries are safe. Together - optimistic concurrency (or atomic conditional updates) to detect/prevent lost updates, atomic transactions per transfer, sagas for cross-service flows, idempotency keys for safe retries, and immutable ledger-based auditing - this turns unreliable concurrent balance updates into correct, conflict-detecting, all-or-nothing, idempotent, auditable transfers, which is exactly the reliability a banking system’s money movement requires.
6.6 Production Scenario
A banking system processes account transfers from multiple channels and occasionally overwrites balances because concurrent updates each write back a stale read. The team adds optimistic concurrency with a rowversion token so conflicts are detected rather than lost, wraps each transfer’s debit/credit in one transaction, adds idempotency keys so retried transfers don’t double-apply, enables retry-on-failure for transient errors, and records immutable ledger entries for audit - making concurrent money movement correct and reliable.
Chapter Revision Notes
- Transactions give ACID guarantees; SaveChanges is transactional, use explicit transactions for multi-op units.
- Optimistic concurrency (rowversion token) detects conflicts at save time without locking - the default at scale.
- Handle DbUpdateConcurrencyException by reloading, reconciling, and retrying (or informing the user).
- Pessimistic locking prevents conflicts but risks blocking/deadlocks - reserve for critical hot spots.
- Retry transient failures with idempotency; use sagas/outbox for cross-service consistency.