
Your Transaction Doesn't See a Frozen Database: Isolation Levels Explained
- كاتب موثّق
محتويات المقال
READ_COMMITTED_SNAPSHOT gave exactly the same result.
The common misconception
What actually happens
The default gives each statement its own view
READ COMMITTED, data can be changed by other transactions between individual statements within the current transaction, resulting in nonrepeatable reads or phantom data, and this is the SQL Server default. With READ_COMMITTED_SNAPSHOT on, each statement gets a consistent snapshot as of the start of that statement, not of the transaction. PostgreSQL, whose default is also Read Committed, warns that two successive SELECT commands can see different data even within a single transaction. The statement in the hook hit a : a row that matched the query appeared between two reads.
The anomalies, in plain words
Dirty read: you read another transaction's uncommitted change, which may still be rolled back. Nonrepeatable read: you read a row twice and get different values, because someone committed in between. Phantom: you run the same query twice and get a different set of rows. : two transactions read the same data, each changes a different row based on what it read, and together they break a rule neither broke alone.
What each level prevents
READ UNCOMMITTED | NOLOCK on every table | |||
READ COMMITTED (default) | ||||
REPEATABLE READ | ||||
SNAPSHOT | ||||
SERIALIZABLE |
Snapshot freezes reads, not decisions
SNAPSHOT, session A read the total, B inserted the payment, and A's lines still added up to 750.00. The snapshot starts at the first data access, not at BEGIN TRANSACTION: Microsoft's docs say so, and in the test a transaction that hadn't read anything yet saw a payment committed after it began. But a frozen view isn't the same as running one at a time. Berenson and colleagues' 1995 critique of the ANSI isolation levels puts it precisely: "Snapshot Isolation is non-serializable because a transaction's Reads come at one instant and the Writes at another." The test below reproduced write skew with two real sessions.
Make the report consistent
using Microsoft.EntityFrameworkCore;static async Task<Statement> BuildAsync(BankDb db, int accountId){ // Default READ COMMITTED: each query sees the latest commits await using var tx = await db.Database.BeginTransactionAsync(); var entries = db.Entries.Where(e => e.AccountId == accountId); var total = await entries.SumAsync(e => e.Amount); var lines = await entries.ToListAsync(); // T-SQL test: 750.00 vs 1,250.00 return new Statement(total, lines);}using System.Data;using Microsoft.EntityFrameworkCore;static async Task<Statement> BuildAsync(BankDb db, int accountId){ // One snapshot from the first read; needs ALLOW_SNAPSHOT_ISOLATION ON await using var tx = await db.Database.BeginTransactionAsync(IsolationLevel.Snapshot); var entries = db.Entries.Where(e => e.AccountId == accountId); var total = await entries.SumAsync(e => e.Amount); var lines = await entries.ToListAsync(); // T-SQL test: 750.00 and 750.00 await tx.CommitAsync(); return new Statement(total, lines);}-- Session A (Hany, DoctorId 1) and session B (Laila, DoctorId 2) each ran:SET TRANSACTION ISOLATION LEVEL SNAPSHOT;BEGIN TRANSACTION;SELECT COUNT(*) FROM dbo.OnCall WHERE IsOnCall = 1; -- A saw 2, then B saw 2UPDATE dbo.OnCall SET IsOnCall = 0 WHERE DoctorId = 1; -- B used DoctorId 2COMMIT; -- both committed: 0 doctors on call-- Under SERIALIZABLE: A's UPDATE waited, B's UPDATE made A the-- deadlock victim (Msg 1205), and Hany stayed on callSNAPSHOT saw no conflict. Under SERIALIZABLE, SQL Server's range locks turned the race into a deadlock and rolled one session back; deadlocks get their own article later in this path. PostgreSQL's Serializable is built differently, as Serializable Snapshot Isolation, which adds checks for serialization anomalies on top of snapshots, and its docs say the losing transaction fails with a serialization failure. Both docs say the same thing in different words: be ready to retry.
How to apply it in your project
Find transactions that read twice Look for code that reads, then reads again or reads and then decides: statements, exports, balance checks, capacity checks. Those are the places a moving database shows. Know your actual level Check is_read_committed_snapshot_onandsnapshot_isolation_state_descinsys.databases, and the level your driver or ORM sets. Note that Azure SQL Database turnsREAD_COMMITTED_SNAPSHOTon by default and SQL Server doesn't.Give consistent reads a snapshot Turn on ALLOW_SNAPSHOT_ISOLATIONand run reports atSNAPSHOT, or on PostgreSQL at Repeatable Read. Keep those transactions short, since row versions are kept while they run.Make decisions serializable and retryable Wrap read-then-decide logic in SERIALIZABLE, or encode the rule as a constraint the database enforces, and retry the whole transaction on error 1205 in SQL Server or a serialization failure in PostgreSQL.
Key takeaways
At the default READ COMMITTED, every statement sees the latest commits, so two queries in one transaction can disagree.In the test, a statement's total and lines differed by a 500.00 payment committed between them, with or without READ_COMMITTED_SNAPSHOT.SNAPSHOTfreezes reads from the first data access to commit, but allows write skew: both doctors went off call.SERIALIZABLEprevents write skew by blocking or failing one transaction, so it needs retry logic.Choose the level per transaction, based on whether its reads must agree or its decisions must hold.
📚 المصادر
SET TRANSACTION ISOLATION LEVEL (Transact-SQL) — SQL Server, Microsoft Learn Transaction locking and row versioning guide — SQL Server, Microsoft Learn Transaction Isolation — PostgreSQL documentation A Critique of ANSI SQL Isolation Levels — Berenson, Bernstein, Gray, Melton, O'Neil, O'Neil (SIGMOD 1995), arXiv
التعليقات (0)