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

📚 Interview question

What are the SQL Server isolation levels? Explain read uncommitted, read committed, repeatable read and serializable, the anomalies each one prevents (dirty reads, non-repeatable reads, phantoms, lost updates), how each is implemented with locks, and how you choose one.

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.

Mid-Level Theory Intermediate concurrency isolation-levels locking serializable sql-server transactions

🎯 Key points

  • Dirty read, non-repeatable read, phantom, lost update
  • Read uncommitted: no S locks, dirty reads (= NOLOCK)
  • Read committed (default): short S locks, or with RCSI row versions and no S locks
  • Repeatable read: S locks held to commit; phantoms still possible
  • Serializable: key-range locks prevent phantoms; most blocking and deadlocks
  • Snapshot (opt-in per transaction): transaction-level versioned reads, update-conflict error 3960
  • Lost updates need UPDLOCK, rowversion or a conditional UPDATE below serializable
  • Higher level = longer and wider locks = lower throughput; set per transaction

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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's BeginTransactionAsync takes 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, an UPDLOCK on 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."


Levels and anomalies

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

Choosing

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

Production example

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.

🔍 What the interviewer is checking

Checks that the candidate understands the anomalies, the lock mechanism behind each level, and chooses levels per transaction.

Green flags

  • Defines dirty, non-repeatable and phantom reads with examples
  • Explains key-range locks for serializable
  • Knows lost updates need more than a higher level
  • Mentions the TransactionScope serializable default

Red flags

  • Says serializable is safest and should be the default
  • Thinks repeatable read prevents phantoms
  • Recommends read uncommitted for performance

📚 Learn in depth

1. Anomalies in a timeline

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.

2. How locks implement each level

  • Read uncommitted: reads take only Sch-S. They can also use allocation-order scans, which is why rows can be missed or read twice.
  • Read committed (locking): S lock on each row or page while reading it. A row read earlier can change before commit.
  • Repeatable read: S locks kept to commit. Writers to those rows wait. Two transactions that read then update the same row deadlock (S to X conversion).
  • Serializable: key-range locks (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.

3. Versioning levels

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.

4. Setting the level

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.

5. Cost model

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.

Try it yourself

  1. Reproduce each anomaly in two SSMS windows using the timelines above, switching the isolation level in window 1.
  2. Under serializable, run a range SELECT and query sys.dm_tran_locks for RANGE request modes; drop the supporting index and see the lock widen.
  3. Create a TransactionScope with default options in a console app and print sys.dm_exec_sessions.transaction_isolation_level (4 = serializable).
  4. Reproduce a lost update under read committed with two read-modify-write sessions, then fix it with UPDLOCK.

💻 Code

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

⚠ Common mistakes

  • Mistake: Believing read committed prevents lost updates. Why it is wrong: Two sessions can read the same value and both write back. Instead: Use a conditional UPDATE, UPDLOCK or a rowversion check.
  • Mistake: Using TransactionScope with default options. Why it is wrong: It defaults to serializable, causing range locks and deadlocks. Instead: Pass TransactionOptions with read committed.
  • Mistake: Setting the whole application to serializable 'to be safe'. Why it is wrong: Locks are held longer and over ranges, so blocking and deadlocks rise sharply and throughput falls under load. Instead: Raise the level only for the transaction that needs it, and load-test it.
  • Mistake: Thinking repeatable read prevents phantoms. Why it is wrong: It locks only rows already read, not the gaps. Instead: Serializable or snapshot for range consistency.
  • Mistake: Running serializable without a supporting index. Why it is wrong: Key-range locks then cover far more of the table. Instead: Index the range predicate.
  • Mistake: Treating read uncommitted as 'faster read committed'. Why it is wrong: It returns uncommitted, missing or duplicated rows. Instead: Use RCSI, which gives committed data without S locks.
  • Mistake: Confusing RCSI with snapshot isolation. Why it is wrong: RCSI is a database option that changes read committed to statement-level versioned reads; snapshot is requested per transaction and can raise update conflicts. Instead: Say which one you mean and why.
  • Mistake: Forgetting the level persists on the session. Why it is wrong: Later statements in the same session run at the higher level. Instead: Reset it or scope it to the transaction.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions RCSI or snapshot isolation. Why: Checks the versioning side of isolation, which is the default on Azure SQL.
    How to answer

    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.

  2. When: Candidate mentions key-range locks for serializable. Why: Checks how range locks actually work and when they widen.
    How to answer

    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.

  3. When: Candidate mentions lost updates or race conditions. Why: Checks how the candidate finds and fixes races across the 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.

🛠 Real-world problems: how you handle them

Deadlocks caused by a serializable TransactionScope default
Situation
A .NET booking API on [SQL Server / Azure SQL] wrapped every unit of work in `new TransactionScope()`. About [N] bookings a minute at peak.
Signals
Error 1205 deadlock exceptions in Application Insights rising with load; p95 latency spikes; `sys.dm_exec_sessions.transaction_isolation_level = 4` (serializable) for the API's sessions.
Investigation
Pulled deadlock graphs from the system_health session: both sides held `RangeS-S` locks on the bookings index. Checked session isolation levels with `sys.dm_exec_sessions` and traced them to the default `TransactionScope` constructor. Confirmed with a load test reproducing the deadlocks.
Resolution
Immediate: added a retry on 1205 for the booking endpoint. Real fix: a helper that creates `TransactionScope` with read committed, RCSI on the database, and serializable only in the overlap check, backed by an index on (RoomId, StartsAt).
Prevention
A Roslyn analyser rule (or banned-API list) forbidding the parameterless `TransactionScope` constructor; deadlock count alert from system_health; a concurrency integration test using Testcontainers.

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.

↩ Usually asked after

More in Transactions and Locking

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me