Optimistic concurrency with a rowversion column and a WHERE check, pessimistic locking with UPDLOCK, HOLDLOCK and READPAST, application locks with sp_getapplock, implemented with Microsoft.Data.SqlClient and Dapper, and the criteria for choosing each.
Optimistic concurrency assumes conflicts are rare: read the row with its rowversion, and when saving run UPDATE ... WHERE Id = @id AND RowVersion = @original. If 0 rows are affected, someone else changed it: return 409/412 and let the user reload or merge. No locks are held between read and write, so it suits web forms with user think time.
Pessimistic concurrency locks first: inside a short transaction, SELECT ... WITH (UPDLOCK, HOLDLOCK) so no one else can take the row until you commit; for job queues, UPDLOCK, READPAST lets workers skip claimed rows. sp_getapplock locks a logical name (e.g. 'invoice-run-2026-11') when there's no single row to lock.
The trade-off: optimistic costs retries under contention; pessimistic costs blocking and deadlock risk.
"I decide based on contention and on how long the gap is between reading and writing. For a customer edit screen the gap is user think time, maybe minutes, and conflicts are rare, so I use optimistic concurrency. I add a
rowversioncolumn, which SQL Server changes automatically on every update, send it to the client, often as an ETag, and the update includesAND RowVersion = @originalin the WHERE clause. If it affects zero rows, I know someone else saved first and I return a 409 or 412. No locks are held while the user is thinking.When the work is server-side, short, and the row is hot, like workers claiming jobs from a table or decrementing a shared counter, optimistic concurrency just produces a storm of retries. There I use pessimistic locking inside a short transaction:
UPDLOCKso only one session can hold the update lock,HOLDLOCKso it's kept to commit, and for queuesREADPASTso other workers skip locked rows instead of waiting. Often I can collapse it into one statement:UPDATE TOP (1) ... OUTPUT inserted.*. When there's no row to lock, for example 'only one instance may run the month-end invoice job', I usesp_getapplockwith a resource name, and I always check its return code, because a negative value means I didn't get the lock.The mistake I see is the read-modify-write without either: read the row, change it in C#, save it, and the last writer silently wins. The other mistake is holding a pessimistic lock across an HTTP call or a user's edit. Optimistic for people, pessimistic for short machine work, and never a lock across a network you don't control."
| Situation | Choose | Why |
|---|---|---|
| User edits a record in a form | Optimistic (rowversion) | Long think time, rare conflicts |
| Workers claim jobs from a table | Pessimistic: UPDLOCK, READPAST |
Hot rows, short work |
| Decrement stock or balance | Single conditional UPDATE |
Atomic, no explicit lock needed |
| Singleton job across instances | sp_getapplock |
No single row to lock |
| High contention on one row | Pessimistic or redesign (sharded counters) | Optimistic retries would thrash |
| Optimistic | Pessimistic | |
|---|---|---|
| Locks held between read and write | None | U/X locks until commit |
| Failure mode | Conflict to handle (409, retry) | Blocking, deadlocks |
| Works across HTTP requests | Yes | No |
| Best for | Low contention | High contention, short transactions |
A job table processed by [8] worker instances used 'select top 1 where Status = Pending, then update'. Under load [5-10%] of jobs ran twice. Replacing it with a single UPDATE TOP (1) ... WITH (UPDLOCK, READPAST, ROWLOCK) OUTPUT inserted.JobId removed duplicates completely and raised throughput by [3x] because workers no longer waited on each other.
Checks that the candidate can implement both concurrency styles in T-SQL (rowversion predicates, lock hints, sp_getapplock) and in .NET (SqlClient or Dapper, ETags, conflict responses), and choose based on contention.
Green flags
rowversion in the WHERE clause and checks rows affectedUPDLOCK, READPAST for queuessp_getapplock return codeRed flags
NOLOCK or a C# lock for cross-instance concurrencyrowversion (formerly timestamp) is an 8-byte binary value from a database-wide counter, assigned on every insert and update. It is not a time. Because the engine maintains it, no application code can forget to bump it. Compare it, don't order by it across tables.
GET /customers/7 -> Name, ..., RowVersion=0x00000000000007D3 (ETag)
... user edits for 3 minutes ...
PUT /customers/7 If-Match: 0x...07D3
UPDATE ... WHERE Id = 7 AND RowVersion = 0x...07D3
rows = 1 -> 204, new ETag
rows = 0 -> 412 Precondition Failed (or 409) -> client reloads
EF Core does the same with [Timestamp] / IsRowVersion() and throws DbUpdateConcurrencyException.
| Hint | Effect |
|---|---|
UPDLOCK |
Take U locks instead of S; only one session holds U on a row |
HOLDLOCK (= SERIALIZABLE) |
Keep locks to commit, and range-lock if the row doesn't exist |
ROWLOCK |
Prefer row locks (a request, not a guarantee) |
READPAST |
Skip rows locked by others instead of waiting |
XLOCK |
Exclusive lock while reading (rarely needed) |
UPDLOCK without HOLDLOCK is held to commit anyway for rows that were read, but HOLDLOCK matters for the 'row does not exist yet' case (upserts).
Worker A: UPDATE TOP(1) Jobs WITH (UPDLOCK, READPAST, ROWLOCK) ... -> claims job 1
Worker B: same statement -> skips locked job 1 -> claims job 2
READPAST needs read committed or repeatable read (not snapshot), and an index on (Status, CreatedAt) so each claim seeks.
sp_getapplock @Resource, @LockMode ('Exclusive' / 'Shared'), @LockOwner ('Transaction' or 'Session'), @LockTimeout (ms). Return codes: 0 granted, 1 granted after waiting, negative = timeout, cancelled, deadlock or error. Transaction-owned locks release at commit; session-owned locks need sp_releaseapplock and are lost if the connection drops, so the caller must treat losing the connection as losing the lock.
Count optimistic conflicts per minute (logs or metrics). If more than a few percent of saves conflict, switch to a pessimistic or redesigned approach. For pessimistic, watch LCK_M_U waits and deadlock counts.
rowversion column, read a row in two windows, update in one, then try the optimistic update in the other and check @@ROWCOUNT.READPAST and measure how throughput drops.sp_getapplock with a 0 ms timeout from two sessions and log the return codes.Schema, then optimistic update, queue claim and an application lock with Microsoft.Data.SqlClient.
CREATE TABLE dbo.Customers (
CustomerId int IDENTITY PRIMARY KEY,
Name nvarchar(200) NOT NULL,
Email varchar(254) NOT NULL,
RowVersion rowversion NOT NULL);
CREATE TABLE dbo.Jobs (
JobId bigint IDENTITY PRIMARY KEY,
Status tinyint NOT NULL DEFAULT 0, -- 0 pending, 1 running, 2 done
Payload nvarchar(4000) NOT NULL,
CreatedAt datetime2 NOT NULL DEFAULT SYSUTCDATETIME(),
ClaimedBy varchar(64) NULL);
CREATE INDEX IX_Jobs_Status_CreatedAt ON dbo.Jobs (Status, CreatedAt);
namespace Crm.Data;
using System.Data;
using Microsoft.Data.SqlClient;
public sealed record CustomerUpdate(int CustomerId, string Name, string Email, byte[] RowVersion);
public sealed record ClaimedJob(long JobId, string Payload);
public sealed class ConcurrencyExamples(string connectionString)
{
// Optimistic: no locks between read and write; 0 rows means someone else saved first.
public async Task<byte[]?> UpdateCustomerAsync(CustomerUpdate c, CancellationToken ct)
{
await using var conn = new SqlConnection(connectionString);
await conn.OpenAsync(ct);
await using var cmd = new SqlCommand("""
UPDATE dbo.Customers SET Name = @name, Email = @email
OUTPUT inserted.RowVersion
WHERE CustomerId = @id AND RowVersion = @rv;
""", conn);
cmd.Parameters.Add("@name", SqlDbType.NVarChar, 200).Value = c.Name;
cmd.Parameters.Add("@email", SqlDbType.VarChar, 254).Value = c.Email;
cmd.Parameters.Add("@id", SqlDbType.Int).Value = c.CustomerId;
cmd.Parameters.Add("@rv", SqlDbType.Timestamp).Value = c.RowVersion;
return (byte[]?)await cmd.ExecuteScalarAsync(ct); // null => conflict => return 412 to the client
}
// Pessimistic queue claim: one atomic statement; READPAST skips jobs other workers hold.
public async Task<ClaimedJob?> ClaimNextJobAsync(string workerId, CancellationToken ct)
{
await using var conn = new SqlConnection(connectionString);
await conn.OpenAsync(ct);
await using var cmd = new SqlCommand("""
WITH next AS (
SELECT TOP (1) * FROM dbo.Jobs WITH (UPDLOCK, READPAST, ROWLOCK)
WHERE Status = 0 ORDER BY CreatedAt)
UPDATE next SET Status = 1, ClaimedBy = @worker
OUTPUT inserted.JobId, inserted.Payload;
""", conn);
cmd.Parameters.Add("@worker", SqlDbType.VarChar, 64).Value = workerId;
await using var reader = await cmd.ExecuteReaderAsync(ct);
return await reader.ReadAsync(ct) ? new ClaimedJob(reader.GetInt64(0), reader.GetString(1)) : null;
}
// Application lock: a named mutex across all app instances, released at commit.
public async Task<bool> RunExclusivelyAsync(string resource, Func<SqlConnection, SqlTransaction, Task> work, CancellationToken ct)
{
await using var conn = new SqlConnection(connectionString);
await conn.OpenAsync(ct);
await using var tx = (SqlTransaction)await conn.BeginTransactionAsync(ct);
await using var cmd = new SqlCommand("sp_getapplock", conn, tx) { CommandType = CommandType.StoredProcedure };
cmd.Parameters.AddWithValue("@Resource", resource);
cmd.Parameters.AddWithValue("@LockMode", "Exclusive");
cmd.Parameters.AddWithValue("@LockOwner", "Transaction");
cmd.Parameters.AddWithValue("@LockTimeout", 0);
var result = cmd.Parameters.Add("@ret", SqlDbType.Int);
result.Direction = ParameterDirection.ReturnValue;
await cmd.ExecuteNonQueryAsync(ct);
if ((int)result.Value < 0) return false; // someone else holds it: don't run
await work(conn, tx);
await tx.CommitAsync(ct); // releases the app lock
return true;
}
}
UPDATE.datetime LastModified column as the concurrency token. Why it is wrong: Two updates within the column's precision get the same value, so a conflict goes undetected, and the value depends on every writer (including scripts and triggers) setting it. Instead: rowversion, which the engine changes on every update.UPDLOCK across an HTTP call or user edit. Why it is wrong: Every other request for that row blocks. Instead: Optimistic concurrency for anything with think time.HOLDLOCK without UPDLOCK in read-then-update. Why it is wrong: Two sessions take S locks and deadlock converting to X. Instead: UPDLOCK, HOLDLOCK.READPAST. Why it is wrong: Workers queue behind each other and throughput collapses. Instead: UPDLOCK, READPAST, ROWLOCK with a supporting index.sp_getapplock return code. Why it is wrong: A timeout returns a negative value without throwing, so the 'exclusive' work runs anyway. Instead: Check for values < 0.@LockOwner = 'Transaction' where possible.The decision is about contention rate and lock duration, and you can measure both: conflict rate for optimistic, LCK_M_U waits for pessimistic. Often the best answer is neither pattern but one atomic statement, because SQL Server already serialises a single UPDATE on a row.
| Approach | When it fits | Cost | When not to |
|---|---|---|---|
| rowversion check | Human edits, APIs with ETags | Conflict UX, retries | Hot rows updated by many workers |
Atomic conditional UPDATE |
Counters, stock, state transitions | Logic must fit one statement | Multi-step decisions needing reads |
UPDLOCK, HOLDLOCK transaction |
Short server-side read-decide-write | Blocking, deadlock risk | Anything spanning network calls |
sp_getapplock |
Singleton jobs, coarse logical locks | Connection-bound, easy to misuse | Fine-grained row protection |
db.Entry(entity) returns an EntityEntry<T>, the change tracker's view of one entity:
State, CurrentValues, OriginalValues and GetDatabaseValuesAsync() for state and values.Property(p => p.X) gives CurrentValue, OriginalValue and IsModified, so you can mark one column for update, or set the RowVersion original value for a concurrency check.Collection(...)/Reference(...) give explicit loading (LoadAsync, IsLoaded) and Query() to filter or count related rows without loading them all.CurrentValues.SetValues(dto) copies matching values; ReloadAsync() discards local changes.For disconnected graphs, ChangeTracker.TrackGraph visits each node so you choose its state. The trade-off: it gives precise control, but it is easy to misuse (setting current instead of original values, or calling Entry() in hot loops).
A race condition is a bug where the result depends on the timing of concurrent operations. Classic forms are read-modify-write (count++ from two threads), check-then-act (if (!dict.ContainsKey(k)) dict.Add(k, v)), and unsafe publication. In .NET they also appear with non-thread-safe collections (a shared Dictionary or List corrupted under concurrent writes), in async code that interleaves at await points even on one thread, and in databases as lost updates when two requests read, modify and save the same row. Fixes: atomic operations, locks, concurrent collections, immutability, single-writer designs, and in databases optimistic concurrency tokens, unique constraints and idempotency.
A deadlock is a cycle: session A holds what B needs and B holds what A needs. The lock monitor detects it and kills the cheapest transaction as the victim with error 1205. On SQL Server, the system_health Extended Events session already captures every xml_deadlock_report; in Azure SQL Database I create a database-scoped XE session (or use the deadlock data in Query Performance Insight).
The graph shows each process's statement, isolation level and the resources with owner and waiter lock modes. Common causes: two code paths touching tables in opposite order, read-then-update conversions, scans from missing indexes, and serializable range locks. Fixes: index to shrink the lock footprint, consistent access order, UPDLOCK, RCSI, lower isolation. Then retry 1205 for idempotent work, as a safety net, not the fix.
How to tell it (STAR)
**S:** Our job workers were occasionally processing the same job twice, and customers got duplicate emails, [5-10%] of jobs at peak. **T:** I had to make job claiming safe across [8] instances. **A:** The claim was a SELECT followed by a separate UPDATE, so two workers could read the same pending row. I reproduced it with a parallel Testcontainers test, added a unique constraint on the email audit as a safety net, and replaced the claim with a single UPDATE TOP (1) using UPDLOCK, READPAST and OUTPUT, backed by an index. **R:** Duplicates went to zero, throughput rose about [3x] because workers stopped waiting on each other, and the parallel test stays in CI.
Last updated 23 Nov 2026.