The four locking isolation levels in SQL Server, the read anomalies each prevents, how S, X and key-range locks implement them, where snapshot-based levels fit, and how to choose and set the level from T-SQL and .NET.
Isolation levels decide which anomalies a transaction can see. Read uncommitted takes no shared locks, so dirty reads are possible (it's what NOLOCK does). Read committed, the default, only reads committed data, using short-lived S locks, or row versions when RCSI is on, but a re-read can change (non-repeatable read). Repeatable read holds S locks to the end of the transaction, so rows you read can't change, but new rows can appear (phantoms). Serializable adds key-range locks so ranges can't change either. Snapshot gives a transaction-consistent view from row versions.
The trade-off: each step up holds more locks for longer, which means more blocking and deadlocks. Pick the lowest level that is correct, and solve specific races with targeted locks or constraints.
"Isolation levels are a dial between correctness under concurrency and throughput. The SQL standard defines them by the anomalies they allow: a dirty read is reading data another transaction hasn't committed; a non-repeatable read is reading the same row twice and getting different values; a phantom is running the same range query twice and getting new rows. SQL Server implements the four standard levels with locks. Read uncommitted takes no shared locks at all. Read committed takes a shared lock per row or page and releases it straight after reading. Repeatable read keeps those shared locks until commit. Serializable also takes key-range locks, so nobody can insert into a range you've read. On top of that, there are two versioning options: read committed snapshot, which changes how read committed works, and snapshot isolation.
In .NET the level is per connection:
BeginTransaction(IsolationLevel.Serializable)sets it, and EF Core'sBeginTransactionAsynctakes the same enum. One trap is that the isolation level stays on the pooled connection after it's returned, so a connection used for a serializable transaction can come back to the next request still serializable. SqlClient resets it on newer versions, but I still prefer setting it explicitly in the transaction that needs it.The mistake I see is people thinking a higher level automatically fixes races. A classic lost update, read the stock, subtract in C#, write it back, still happens under read committed and repeatable read deadlocks instead of overwriting. The real fix is usually a single conditional
UPDATE, anUPDLOCKon the read, or a rowversion check. Serializable is the right tool for range rules like 'no overlapping bookings', and even then I'd rather have a constraint. The best isolation level is the lowest one that's still correct for that transaction."
| Level | Dirty read | Non-repeatable read | Phantom | How SQL Server does it |
|---|---|---|---|---|
| Read uncommitted | possible | possible | possible | No S locks for reads |
| Read committed (locking) | prevented | possible | possible | S locks released after each read |
| Read committed snapshot (RCSI) | prevented | possible | possible | Statement-level row versions, no S locks |
| Repeatable read | prevented | prevented | possible | S locks held to commit |
| Snapshot | prevented | prevented | prevented | Transaction-level row versions; update conflicts raise error 3960 |
| Serializable | prevented | prevented | prevented | S locks plus key-range locks to commit |
| Need | Choose |
|---|---|
| Normal OLTP reads and writes | Read committed with RCSI |
| A report that must see one consistent point in time | Snapshot |
| Read a row, decide, then update it | Read committed + UPDLOCK or a conditional UPDATE |
| Enforce a rule over a range (no overlap, max N) | Serializable on that transaction only, or a constraint |
| Approximate counts where wrong data is acceptable | Still not read uncommitted; use RCSI |
A booking service ran every transaction at serializable 'to be safe'. Under [Monday morning] load it produced [dozens] of deadlocks an hour. We moved to read committed with RCSI for reads, used serializable only in the one 'check for overlapping booking and insert' transaction with an index on (RoomId, StartsAt), and deadlocks dropped to [one or two a week], handled by a retry.
Checks that the candidate understands the anomalies, the lock mechanism behind each level, and chooses levels per transaction.
Green flags
TransactionScope serializable defaultRed flags
Non-repeatable read (read committed):
T1: SELECT Price FROM Products WHERE Id = 1 -> 10
T2: UPDATE Products SET Price = 12 WHERE Id = 1; COMMIT
T1: SELECT Price FROM Products WHERE Id = 1 -> 12 (changed)
Phantom (repeatable read):
T1: SELECT COUNT(*) FROM Bookings WHERE RoomId = 5 AND Day = '2026-11-20' -> 0
T2: INSERT Bookings (RoomId, Day) VALUES (5, '2026-11-20'); COMMIT
T1: SELECT COUNT(*) ... -> 1 (new row)
A lost update is two read-modify-write cycles where the second write overwrites the first. It is not in the standard's table, but it is the anomaly that hurts most in applications.
RangeS-S, RangeI-N and others) on index keys cover gaps between keys, so inserts into the range wait. Without a useful index the range lock may cover the whole table.X locks from writes are held to commit at every level, including read uncommitted.
RCSI (a database option) makes read committed use the version store: each statement sees data as of its start. Snapshot isolation (ALLOW_SNAPSHOT_ISOLATION ON plus SET TRANSACTION ISOLATION LEVEL SNAPSHOT) gives the whole transaction a view as of its first data access, and if it tries to update a row someone else changed since, it fails with error 3960. Azure SQL Database enables both RCSI and snapshot isolation on new databases by default.
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE; -- session level
SELECT ... FROM dbo.Bookings WITH (SERIALIZABLE); -- table hint (= HOLDLOCK)
From .NET: conn.BeginTransaction(IsolationLevel.Snapshot), EF Core Database.BeginTransactionAsync(IsolationLevel.Serializable). TransactionScope defaults to Serializable, a frequent surprise; always pass TransactionOptions { IsolationLevel = ReadCommitted }.
Check the current level with DBCC USEROPTIONS or sys.dm_exec_sessions.transaction_isolation_level.
Higher levels increase lock duration (repeatable read) and lock footprint (serializable ranges). Both increase blocking and the chance of a cycle, so deadlocks rise sharply. Versioning moves the cost to tempdb (or the persistent version store with ADR) and a 14-byte versioning tag per row.
SELECT and query sys.dm_tran_locks for RANGE request modes; drop the supporting index and see the lock widen.TransactionScope with default options in a console app and print sys.dm_exec_sessions.transaction_isolation_level (4 = serializable).UPDLOCK.Setting the isolation level explicitly where it is needed, and avoiding the TransactionScope default.
-- Range rule: no overlapping booking for a room. Serializable takes key-range locks on the index.
CREATE INDEX IX_Bookings_Room_Start ON dbo.Bookings (RoomId, StartsAt) INCLUDE (EndsAt);
GO
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRAN;
IF NOT EXISTS (SELECT 1 FROM dbo.Bookings
WHERE RoomId = @RoomId AND StartsAt < @EndsAt AND EndsAt > @StartsAt)
INSERT dbo.Bookings (RoomId, StartsAt, EndsAt) VALUES (@RoomId, @StartsAt, @EndsAt);
COMMIT;
SET TRANSACTION ISOLATION LEVEL READ COMMITTED; -- don't leave the session serializable
namespace Bookings.Data;
using System.Data;
using System.Transactions;
using Microsoft.Data.SqlClient;
using IsolationLevel = System.Data.IsolationLevel;
public sealed class BookingStore(string connectionString)
{
public async Task<bool> TryBookAsync(int roomId, DateTime startsAt, DateTime endsAt, CancellationToken ct)
{
await using var conn = new SqlConnection(connectionString);
await conn.OpenAsync(ct);
// Serializable only for this transaction, not the whole app.
await using var tx = (SqlTransaction)await conn.BeginTransactionAsync(IsolationLevel.Serializable, ct);
await using var cmd = new SqlCommand("""
IF NOT EXISTS (SELECT 1 FROM dbo.Bookings
WHERE RoomId = @r AND StartsAt < @e AND EndsAt > @s)
BEGIN
INSERT dbo.Bookings (RoomId, StartsAt, EndsAt) VALUES (@r, @s, @e);
SELECT 1;
END
ELSE SELECT 0;
""", conn, tx);
cmd.Parameters.Add("@r", SqlDbType.Int).Value = roomId;
cmd.Parameters.Add("@s", SqlDbType.DateTime2).Value = startsAt;
cmd.Parameters.Add("@e", SqlDbType.DateTime2).Value = endsAt;
var booked = (int)(await cmd.ExecuteScalarAsync(ct))! == 1;
await tx.CommitAsync(ct);
return booked; // callers retry on deadlock (error 1205)
}
// TransactionScope defaults to Serializable: always say what you mean.
public static TransactionScope ReadCommittedScope() => new(
TransactionScopeOption.Required,
new TransactionOptions { IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted },
TransactionScopeAsyncFlowOption.Enabled);
}
UPDATE, UPDLOCK or a rowversion check.TransactionScope with default options. Why it is wrong: It defaults to serializable, causing range locks and deadlocks. Instead: Pass TransactionOptions with read committed.Strong candidates know that isolation levels are a blunt instrument and that most correctness bugs are specific races better solved by targeted locking (UPDLOCK), optimistic checks (rowversion), or constraints (unique, check). They also know the defaults: read committed on SQL Server, RCSI on Azure SQL Database, and serializable for TransactionScope.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| RCSI (read committed) | Default for OLTP | Version store, small write overhead | Code that needs readers to wait for writers |
| Snapshot | Consistent multi-statement reads, reports | Update conflicts (3960) need retry | Write-heavy transactions on hot rows |
| Serializable | Range invariants (no overlap, max N) | Range locks, deadlocks | Whole-app default |
Targeted UPDLOCK |
Read-then-update on one row | Serialises those updaters | Long transactions |
With row versioning, an update copies the previous committed row into a version store and readers follow a pointer chain to the version they should see, instead of taking shared locks. RCSI is a database option that makes plain read committed use versions: each statement sees data as of when it started. Snapshot isolation must be allowed on the database and requested per transaction: the whole transaction sees data as of its first read, and if it updates a row someone else changed since, it fails with error 3960 (update conflict).
Readers stop blocking writers and vice versa, but writers still block writers. The cost is version store space (tempdb, or the database's persistent version store when ADR is on), a 14-byte tag per row, and longer version chains under long transactions. Azure SQL Database turns both on by default.
Key-range locks protect the gap between index keys so no other session can insert a row that would change the result of a range read. They appear only under SERIALIZABLE (or the HOLDLOCK hint). Modes such as RangeS-S, RangeS-U and RangeI-N combine a range part and a key part. They prevent phantoms and make upserts safe, but they need a suitable index (otherwise far more is locked), increase blocking, and are a common cause of deadlocks.
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.
How to tell it (STAR)
**S:** Our booking API started throwing deadlock errors as traffic grew, [N] an hour at peak. **T:** I had to find why a fairly simple workload was deadlocking. **A:** The deadlock graphs in system_health showed range locks on both sides, which only happen under serializable. I checked `sys.dm_exec_sessions` and every API session was serializable, because we used `new TransactionScope()` everywhere and it defaults to serializable. I introduced a helper with read committed, turned on RCSI, kept serializable only for the overlap check with a proper index, and added a retry for the rare remaining deadlock. **R:** Deadlocks went from [N an hour] to [about one a week], p95 latency dropped [by X%], and a banned-API rule stops the default constructor coming back.
Last updated 23 Nov 2026.