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

📚 Interview question

Read committed snapshot (RCSI) vs snapshot isolation: how does row versioning work in SQL Server, what is the difference between statement-level and transaction-level consistency, what do the version store and update conflicts cost you, and what are the defaults on Azure SQL Database?

Row versioning in SQL Server: RCSI vs snapshot isolation, statement vs transaction consistency, the tempdb or ADR persistent version store, update conflicts (error 3960), write skew, enabling them safely, and Azure SQL Database defaults.

Mid-Level Theory Intermediate azure-sql rcsi row-versioning snapshot-isolation sql-server tempdb

🎯 Key points

  • Updates keep the previous committed version; readers read versions instead of taking S locks
  • RCSI: database option, changes read committed, statement-level consistency
  • Snapshot: ALLOW_SNAPSHOT_ISOLATION plus SET TRANSACTION ISOLATION LEVEL SNAPSHOT, transaction-level consistency
  • Update conflict error 3960 under snapshot only: retry the whole transaction or keep snapshot for reads
  • RCSI writers still block writers
  • Version store in tempdb, or the persistent version store with ADR; long transactions pin versions, so monitor its size
  • Write skew under snapshot (two on-call doctors both go off call): fix with UPDLOCK, a constraint or serializable
  • Azure SQL Database: READ_COMMITTED_SNAPSHOT and ALLOW_SNAPSHOT_ISOLATION ON for new databases; OFF on SQL Server and MI

⏱ 30-second 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.

🗣 Full answer (senior)

How I would answer this in an interview

"Both options use the same mechanism. When a row is updated or deleted, SQL Server keeps the previous committed version in a version store and adds a 14-byte tag to the row with the transaction sequence number and a pointer to the old version. A reader that's using versioning doesn't take a shared lock: it walks the chain to the newest version that was committed before its snapshot point. So readers never wait for writers, and writers never wait for readers.

The difference is the snapshot point. With RCSI, which is a database setting, every statement under read committed gets its own point in time, the start of that statement. Two queries in the same transaction can see different data, exactly like normal read committed, just without blocking. With snapshot isolation the point is the start of the transaction's first data access, so a multi-statement report sees one consistent picture. The price is update conflicts: if my snapshot transaction tries to update a row that another transaction changed after my snapshot started, I get error 3960 and must retry. RCSI has no update conflicts because updates read the current committed row and take locks normally.

The mistake I see is turning on RCSI without checking the code that relied on blocking: for example, 'read the balance, check it, then update' that was accidentally safe because readers waited. Under RCSI it reads the old committed value and races. Those paths need UPDLOCK or a conditional update. The other mistake is forgetting about the version store: one transaction left open for hours keeps every version since it started, and tempdb fills up. On Azure SQL Database both are on by default, so I mostly need to know the behaviour rather than enable it."


RCSI vs snapshot

RCSI Snapshot isolation
Enable ALTER DATABASE ... SET READ_COMMITTED_SNAPSHOT ON ALLOW_SNAPSHOT_ISOLATION ON, then SET TRANSACTION ISOLATION LEVEL SNAPSHOT
Applies to All read committed statements automatically Only transactions that ask for it
Consistency Per statement Per transaction
Update conflicts No (updates use locks) Yes, error 3960
Code changes None, but check read-then-update logic Must request it and handle 3960
Anomalies left Non-repeatable reads, phantoms, lost updates Write skew

Costs

Cost Detail
Version store tempdb, or the persistent version store in the user database when ADR is on
Row size 14-byte tag added on first update after enabling, can cause page splits
Read overhead Walking long version chains if a long-running transaction pins old versions
Write overhead Generating versions on update and delete

Production example

A [SQL Server 2019] order system had [hundreds] of LCK_M_S waits a minute from dashboards reading Orders. Enabling RCSI removed them and dashboard p95 fell from [4 s] to [300 ms]. We first audited [12] read-then-update paths and added UPDLOCK to [3] of them, and added an alert on version store size after a forgotten open transaction once grew it to [40 GB].

🔍 What the interviewer is checking

Checks a precise understanding of versioning: snapshot point, conflicts, version store cost and the behaviour change RCSI introduces.

Green flags

  • Distinguishes statement-level and transaction-level consistency
  • Knows error 3960 and write skew
  • Mentions tempdb vs the ADR persistent version store and long transactions
  • Knows Azure SQL Database defaults

Red flags

  • Thinks RCSI removes writer/writer blocking
  • Treats RCSI as a free switch with no semantic change
  • Equates snapshot with NOLOCK

📚 Learn in depth

1. The version chain

Current row (in data page)            Version store
[OrderId 7 | Status=Shipped | XSN 120 | ptr] --> [Status=Paid | XSN 95 | ptr] --> [Status=New | XSN 60]

Reader with snapshot XSN 100 -> skips 120 (too new) -> reads 'Paid'

Each transaction that modifies data gets a transaction sequence number (XSN). A reader compares XSNs to pick the right version.

2. Where versions live

  • Without ADR: in tempdb's version store. Monitor with sys.dm_tran_version_store_space_usage and the Version Store Size (KB) counter.
  • With Accelerated Database Recovery (always on in Azure SQL Database, optional on SQL Server 2019+): in the persistent version store (PVS) inside the user database. Monitor with sys.dm_tran_persistent_version_store_stats.
  • Versions can be cleaned only when no active transaction might need them, so the oldest active snapshot or long transaction (sys.dm_tran_active_snapshot_database_transactions) pins them.

3. Enabling RCSI safely

ALTER DATABASE Shop SET READ_COMMITTED_SNAPSHOT ON WITH ROLLBACK IMMEDIATE; needs exclusive access to the database briefly. Before that, audit:

  • Read-then-update patterns that relied on readers blocking.
  • Triggers or procedures that check a value and then write based on it.
  • Queues implemented by polling tables (use READPAST, UPDLOCK, ROWLOCK for those).

You can still get locking behaviour per statement with the READCOMMITTEDLOCK hint.

4. Update conflicts and write skew

Under snapshot isolation, T1 reads row R at XSN 100, T2 updates R and commits, T1 tries to update R: SQL Server detects the newer committed version and raises 3960; T1 is rolled back. Write skew is different: T1 and T2 each read both doctors 'on call', each takes a different doctor off call, and both commit, leaving none. Snapshot doesn't detect it because they updated different rows. Fix with a constraint, UPDLOCK on the read, or serializable.

5. Defaults (as of November 2026)

  • Azure SQL Database: READ_COMMITTED_SNAPSHOT and ALLOW_SNAPSHOT_ISOLATION are ON for new databases.
  • SQL Server (2022, 2025) and Azure SQL Managed Instance: both OFF by default.
  • Optimized locking (Azure SQL Database, opt-in on SQL Server 2025) relies on RCSI for its lock-after-qualification part.

6. From .NET

RCSI needs no code changes. Snapshot: BeginTransaction(IsolationLevel.Snapshot); EF Core BeginTransactionAsync(IsolationLevel.Snapshot). Catch SqlException number 3960 and retry the whole unit of work.

Try it yourself

  1. Turn on RCSI in a test database, update a row in an open transaction, and read it from another window without blocking; check sys.dm_tran_version_store_space_usage.
  2. Reproduce error 3960 with two snapshot transactions updating the same row.
  3. Reproduce write skew with an 'on call' table and fix it with a check via an indexed view or UPDLOCK.
  4. Leave a snapshot transaction open while running an update loop and watch the version store grow.

💻 Code

Enable versioning, read without blocking, and handle update conflicts.

-- Needs exclusive access briefly; Azure SQL Database already has both ON.
ALTER DATABASE Shop SET READ_COMMITTED_SNAPSHOT ON WITH ROLLBACK IMMEDIATE;
ALTER DATABASE Shop SET ALLOW_SNAPSHOT_ISOLATION ON;

SELECT name, is_read_committed_snapshot_on, snapshot_isolation_state_desc
FROM sys.databases WHERE name = DB_NAME();

-- Who is pinning the version store?
SELECT session_id, transaction_id, elapsed_time_seconds
FROM sys.dm_tran_active_snapshot_database_transactions
ORDER BY elapsed_time_seconds DESC;

-- Under RCSI, a read-then-update that relied on blocking must take an update lock explicitly
BEGIN TRAN;
    SELECT Balance FROM dbo.Accounts WITH (UPDLOCK) WHERE AccountId = @id;
    -- decide in T-SQL or the app, then:
    UPDATE dbo.Accounts SET Balance -= @amount WHERE AccountId = @id;
COMMIT;
namespace Reporting.Data;

using System.Data;
using Microsoft.Data.SqlClient;

public sealed class MonthEndReport(string connectionString)
{
    // Snapshot: every query in this transaction sees the same point in time.
    public async Task<(decimal Invoiced, decimal Paid)> GetTotalsAsync(DateOnly month, CancellationToken ct)
    {
        await using var conn = new SqlConnection(connectionString);
        await conn.OpenAsync(ct);
        await using var tx = (SqlTransaction)await conn.BeginTransactionAsync(IsolationLevel.Snapshot, ct);

        var invoiced = await ScalarAsync(conn, tx, "SELECT ISNULL(SUM(Amount),0) FROM dbo.Invoices WHERE InvoiceMonth = @m", month, ct);
        var paid = await ScalarAsync(conn, tx, "SELECT ISNULL(SUM(Amount),0) FROM dbo.Payments WHERE InvoiceMonth = @m", month, ct);

        await tx.CommitAsync(ct); // read-only: no update conflicts possible
        return (invoiced, paid);
    }

    private static async Task<decimal> ScalarAsync(SqlConnection conn, SqlTransaction tx, string sql, DateOnly month, CancellationToken ct)
    {
        await using var cmd = new SqlCommand(sql, conn, tx);
        cmd.Parameters.Add("@m", SqlDbType.Date).Value = month.ToDateTime(TimeOnly.MinValue);
        return (decimal)(await cmd.ExecuteScalarAsync(ct))!;
    }
}

⚠ Common mistakes

  • Mistake: Thinking RCSI and snapshot isolation are the same thing. Why it is wrong: RCSI is statement-level and automatic; snapshot is transaction-level, opt-in and can raise 3960. Instead: Explain the snapshot point of each.
  • Mistake: Enabling RCSI without auditing read-then-update code. Why it is wrong: Code that relied on readers blocking now reads stale committed values and races. Instead: Add UPDLOCK or conditional updates on those paths.
  • Mistake: Believing RCSI stops all blocking. Why it is wrong: Writers still block writers. Instead: Fix writer contention with indexes and short transactions.
  • Mistake: Ignoring the version store. Why it is wrong: A long-running or forgotten transaction pins versions and fills tempdb or the PVS. Instead: Monitor version store size and the oldest active snapshot transaction.
  • Mistake: Not handling error 3960. Why it is wrong: Snapshot writers fail on conflicts. Instead: Retry the whole transaction, or use snapshot only for reads.
  • Mistake: Assuming snapshot prevents every anomaly. Why it is wrong: Write skew still happens. Instead: Use constraints, UPDLOCK or serializable for cross-row rules.
  • Mistake: Assuming SQL Server on-premises has the Azure defaults. Why it is wrong: RCSI is off by default on SQL Server and Managed Instance. Instead: Check sys.databases.

🏛 Senior insight: trade-offs

RCSI is the right default for most OLTP databases, which is why Azure SQL Database ships with it, but it changes semantics, so the senior move is an audit before flipping it on an existing system. Snapshot isolation is best for read-only consistent reports; for writers its update conflicts make it a niche tool.

Option When it fits Cost When not to
RCSI General OLTP with reader/writer blocking Version store, row tag, audit of existing code Code relying on blocking reads, unless fixed first
Snapshot (read-only) Multi-query reports, exports Long snapshots pin versions Very long exports on busy systems without monitoring
Snapshot (writers) Low-contention workflows wanting consistency 3960 retries Hot rows updated by many sessions
READCOMMITTEDLOCK hint One statement that must see blocking semantics under RCSI Blocking returns for that statement General use

🔗 Follow-ups the interviewer may ask

  1. When: Candidate compares RCSI with NOLOCK. Why: Checks the difference between consistent versioned reads and dirty reads.
    How to answer

    NOLOCK is read uncommitted: it reads rows other transactions haven't committed (which may be rolled back), and because it can use allocation-order scans without shared locks, it can skip rows or read them twice when pages split during the scan. It can even fail with error 601. It removes blocking by giving up correctness. Use read committed snapshot isolation (RCSI), the default in Azure SQL Database, so readers see the last committed version without blocking writers, and fix the long write transactions that cause blocking.

  2. When: Candidate mentions using snapshot or RCSI from EF Core. Why: Checks the EF Core side of versioning.
    How to answer

    New Azure SQL Database databases have READ_COMMITTED_SNAPSHOT (RCSI) on by default (on-premises SQL Server doesn't; check is_read_committed_snapshot_on in sys.databases for your database). With RCSI each statement reads a consistent committed version without blocking writers. For several statements to see the same version, use IsolationLevel.Snapshot (needs ALLOW_SNAPSHOT_ISOLATION ON). The cost is the row-version store (tempdb, or the persistent version store when accelerated database recovery is on, as it always is in Azure SQL Database), a 14-byte versioning tag added to modified rows, and update conflicts (error 3960) under snapshot that you must retry.

  3. When: Candidate mentions consistent reads across several queries. Why: Checks applying snapshot isolation to EF Core split queries.
    How to answer

    Wrap the split query in a transaction: await using var tx = await db.Database.BeginTransactionAsync(IsolationLevel.Snapshot, ct); then run the query and commit. Every split statement then reads the same committed row versions without blocking writers. Snapshot isolation must be allowed on the database (ALTER DATABASE ... SET ALLOW_SNAPSHOT_ISOLATION ON; Azure SQL enables it by default); turning it on adds row versioning for all writes, so test the tempdb / version store impact. Serializable also gives consistency but takes range locks and blocks writers. Keep the transaction short. If a single projected query can return what you need, it is consistent by itself and avoids the problem.

🛠 Real-world problems: how you handle them

Forgotten snapshot transaction fills tempdb
Situation
A [SQL Server 2022] OLTP database with RCSI and snapshot isolation on, [N] writes a second. An ad-hoc export tool opened a snapshot transaction and the user left it open over a weekend.
Signals
tempdb data files growing steadily; the `Version Store Size (KB)` performance counter rising; alert at [80%] tempdb usage on Sunday; reads getting slower as version chains grew.
Investigation
Checked `sys.dm_tran_version_store_space_usage` (version store [40 GB] for the database), then `sys.dm_tran_active_snapshot_database_transactions` ordered by `elapsed_time_seconds`: one session open for [50] hours. `sys.dm_exec_sessions` showed host and program name of the export tool.
Resolution
Immediate: killed the session after confirming it was read-only; version cleanup freed the space within [minutes]. Real fix: the export tool now runs each export in a bounded transaction with a command timeout and closes connections; long exports read from a readable secondary instead.
Prevention
Alerts on version store size and on any snapshot transaction older than [30 minutes]; runbook entry; code review rule that tools must `await using` connections and transactions.

How to tell it (STAR)

**S:** One weekend tempdb on our [order database server] kept growing and hit [80%]. **T:** I was [on call] and had to stop it before tempdb filled and writes started failing. **A:** The version store counter was climbing, so I checked `sys.dm_tran_active_snapshot_database_transactions` and found a snapshot transaction open for [50] hours from an export tool. It was read-only, so I killed it and the version store cleared. Then I changed the tool to use bounded transactions and run long exports on a readable secondary. **R:** tempdb dropped from [40 GB] of versions to under [1 GB], and an alert on old snapshot transactions has caught [two] similar cases early since.

↩ Usually asked after

More in Transactions and Locking

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me