
What ACID Really Promises, and the Correctness It Leaves to You
- كاتب موثّق
محتويات المقال
BEGIN TRANSACTION and COMMIT on a fully ACID database. In a test on SQL Server 2022, Karim's wallet held 950 and a CHECK constraint caps every wallet at 1,000, so the credit failed with error 547. The application received that error as an exception. Yet the debit was committed: Mona had 400, Karim still had 950, and 100 had left the system.
The common misconception
SaveChanges call in a transaction for you, so many developers never decide where a transaction begins or ends.
What actually happens
Atomicity covers the transaction you opened, not the one you meant
BEGIN and COMMIT. Two updates sent one after the other are two transactions, and a failure between them leaves the first one committed.
An error doesn't always end the transaction
XACT_ABORT is OFF by default, and Microsoft's docs say that in some cases only the statement that raised the error is rolled back and the transaction continues. In the test, the failed credit was undone, the next statement was COMMIT, and it committed the debit. PostgreSQL handles errors differently: its docs say an error puts the transaction block in an aborted state. That behavior is quoted from the docs; only SQL Server ran for this article.
Consistency means your declared rules, not your intentions
CHECK, NOT NULL. The database has no idea that a transfer must not change the total amount of money, or that an order can't ship before it's paid. The same guide is blunt about it: applications are responsible for starting and ending transactions at points that enforce the logical consistency of the data. In the test, the CHECK constraint did its job perfectly. The transaction boundary and error handling were the bug.
Isolation is a level you choose
READ COMMITTED, which Microsoft's own table lists as allowing nonrepeatable reads and phantoms. Two requests that read a balance and write it back can also overwrite each other, a lost update this path covers in its own article. A later article explains what each allows.
Durability keeps your mistakes too
Fix the boundary and the error path
-- XACT_ABORT is OFF by defaultBEGIN TRANSACTION;UPDATE dbo.Wallets SET Balance -= 100 WHERE Id = 1;UPDATE dbo.Wallets SET Balance += 100 WHERE Id = 2;COMMIT;-- Tested: Msg 547 on the credit, then COMMIT ran.-- Mona 500 -> 400, Karim stays 950: 100 vanishedSET XACT_ABORT ON;BEGIN TRY BEGIN TRANSACTION; UPDATE dbo.Wallets SET Balance -= 100 WHERE Id = 1; UPDATE dbo.Wallets SET Balance += 100 WHERE Id = 2; COMMIT;END TRYBEGIN CATCH IF XACT_STATE() <> 0 ROLLBACK; THROW;END CATCH;-- Tested: Msg 547 reaches the caller, both balances unchangedXACT_ABORT ON, the error doomed the whole transaction, the CATCH block rolled it back, and THROW passed the error on. Application code needs the same discipline. One SaveChanges call is already one transaction, but EF Core's docs warn that ExecuteUpdate and ExecuteDelete don't start one, so each call commits on its own:
using Microsoft.EntityFrameworkCore;static async Task TransferAsync( WalletsDb db, int fromId, int toId, decimal amount){ // Both statements in one transaction: both commit, or neither does await using var tx = await db.Database.BeginTransactionAsync(); await db.Wallets.Where(w => w.Id == fromId).ExecuteUpdateAsync( s => s.SetProperty(w => w.Balance, w => w.Balance - amount)); var credited = await db.Wallets.Where(w => w.Id == toId).ExecuteUpdateAsync( s => s.SetProperty(w => w.Balance, w => w.Balance + amount)); // Matching zero rows isn't an error to the database: check it yourself if (credited != 1) throw new InvalidOperationException($"No wallet {toId}"); await tx.CommitAsync(); // skipped on any exception: disposal rolls back}How to apply it in your project
List operations that write more than once Search for business operations that make several write calls: two SaveChanges, severalExecuteUpdatecalls, or a loop of inserts. Each one that must succeed as a unit needs one explicit transaction around it.Make errors abort the whole unit In T-SQL, use SET XACT_ABORT ONwithTRY/CATCHand roll back whenXACT_STATE()isn't 0. In application code, commit only as the last step, and let disposal roll back on any exception.Check row counts, not just errors An UPDATEthat matches no rows succeeds with a count of 0. Treat an unexpected count as a failure before you commit.Declare the rules you can, and know your isolation level Turn invariants into CHECK,UNIQUEand foreign key constraints, the topic of the next article. RunDBCC USEROPTIONSon SQL Server to see the session's isolation level; in the test, it showedread committed.
Key takeaways
ACID applies to the transactions you actually open; in autocommit mode, every statement is its own transaction. In SQL Server, an error inside a transaction can leave the transaction open, and a later COMMITsaves the partial work unlessXACT_ABORTis on.The C in ACID enforces only the rules you declared; business correctness still depends on your boundaries and checks. Isolation defaults to READ COMMITTEDin SQL Server, not serializable, so concurrent transactions can still interfere.Durability makes a wrong commit as permanent as a right one.
📚 المصادر
Transaction locking and row versioning guide — SQL Server, Microsoft Learn Transactions (Transact-SQL) — SQL Server, Microsoft Learn SET XACT_ABORT (Transact-SQL) — SQL Server, Microsoft Learn Transactions — PostgreSQL tutorial, PostgreSQL documentation ExecuteUpdate and ExecuteDelete — EF Core, Microsoft Learn
التعليقات (0)