📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Two users edit the same customer record, or two workers claim the same job. Show how you implement optimistic concurrency with rowversion and pessimistic concurrency with UPDLOCK/HOLDLOCK and sp_getapplock from .NET against SQL Server, and explain how you choose between them.

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.

Mid-Level Coding Intermediate dotnet optimistic-concurrency pessimistic-locking rowversion sp-getapplock sql-server

🎯 Key points

  • rowversion: 8-byte value changed by SQL Server on every update, used as a concurrency token
  • Optimistic: UPDATE ... WHERE Id = @id AND RowVersion = @rv; 0 rows = conflict
  • Send rowversion to the client as an ETag; If-Match on save; 412/409 on conflict
  • Conflict UX: show what changed, let the user reload or merge; never silently overwrite
  • Pessimistic: SELECT ... WITH (UPDLOCK, HOLDLOCK) inside a short transaction
  • Queue claiming: UPDLOCK, READPAST, ROWLOCK with TOP (1) and OUTPUT
  • sp_getapplock locks a name, not a row; Transaction or Session owner, check the return code
  • Optimistic for low contention and user think time; pessimistic for hot rows and short server-side work

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 rowversion column, which SQL Server changes automatically on every update, send it to the client, often as an ETag, and the update includes AND RowVersion = @original in 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: UPDLOCK so only one session can hold the update lock, HOLDLOCK so it's kept to commit, and for queues READPAST so 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 use sp_getapplock with 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."


Choosing

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 vs pessimistic

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

Production example

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.

🔍 What the interviewer is checking

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

  • Uses rowversion in the WHERE clause and checks rows affected
  • Returns a clear conflict response the user can act on
  • Knows UPDLOCK, READPAST for queues
  • Checks the sp_getapplock return code
  • Refuses to hold locks across user think time

Red flags

  • Last-writer-wins without noticing
  • Uses NOLOCK or a C# lock for cross-instance concurrency
  • Pessimistic locks spanning HTTP requests

📚 Learn in depth

1. rowversion

rowversion (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.

2. Optimistic flow

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.

3. Pessimistic hints

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).

4. Queue tables

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.

5. Application locks

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.

6. Measuring contention

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.

Try it yourself

  1. Add a rowversion column, read a row in two windows, update in one, then try the optimistic update in the other and check @@ROWCOUNT.
  2. Run the queue claim from the code example in 4 parallel PowerShell or C# loops and verify no job is processed twice.
  3. Remove READPAST and measure how throughput drops.
  4. Call sp_getapplock with a 0 ms timeout from two sessions and log the return codes.

💻 Code

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;
    }
}

⚠ Common mistakes

  • Mistake: Read, modify in C#, save without any check. Why it is wrong: The last writer silently overwrites the other user's change (lost update). Instead: rowversion check or a conditional UPDATE.
  • Mistake: Using a 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.
  • Mistake: Returning a generic 500 on a concurrency conflict. Why it is wrong: The user loses their edit and doesn't know why. Instead: Return 409/412, show the current values, and let the user reapply or merge.
  • Mistake: Holding 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.
  • Mistake: HOLDLOCK without UPDLOCK in read-then-update. Why it is wrong: Two sessions take S locks and deadlock converting to X. Instead: UPDLOCK, HOLDLOCK.
  • Mistake: Queue claims without READPAST. Why it is wrong: Workers queue behind each other and throughput collapses. Instead: UPDLOCK, READPAST, ROWLOCK with a supporting index.
  • Mistake: Ignoring the 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.
  • Mistake: Session-owned app locks on pooled connections without release. Why it is wrong: The lock stays with the pooled connection. Instead: Use @LockOwner = 'Transaction' where possible.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions EF Core concurrency tokens or DbUpdateConcurrencyException. Why: Checks the EF Core implementation of optimistic concurrency and reading original values.
    How to answer

    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).

  2. When: Candidate mentions lost updates or race conditions. Why: Checks broader race-condition diagnosis across app and database.
    How to answer

    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.

  3. When: Candidate mentions deadlocks from HOLDLOCK or lock conversions. Why: Checks deadlock diagnosis and fixes.
    How to answer

    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.

🛠 Real-world problems: how you handle them

Jobs processed twice by competing workers
Situation
A background processing system with [8] worker instances on [Azure Container Apps] pulling jobs from a SQL table, [N] jobs an hour; duplicate processing sent customers duplicate emails.
Signals
Customer complaints about duplicate emails; logs showing the same JobId started by two workers within milliseconds; duplicate rows in the email audit table ([5-10%] of jobs at peak).
Investigation
Reviewed the claim code: `SELECT TOP 1 ... WHERE Status = 0` followed by a separate `UPDATE ... SET Status = 1`. Reproduced with a parallel integration test against a Testcontainers SQL Server: two workers read the same row under read committed before either updated it. `sys.dm_tran_locks` during the test showed only short S locks on the read.
Resolution
Immediate: added a unique constraint on the email audit (JobId) so duplicates failed fast. Real fix: replaced the two statements with one `UPDATE TOP (1)` using `UPDLOCK, READPAST, ROWLOCK` and `OUTPUT`, plus an index on (Status, CreatedAt).
Prevention
Kept the parallel claim test in CI; idempotency key on the email send; metric for jobs started more than once.

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.

↩ Usually asked after

More in Transactions and Locking

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me