
Read, Modify, Write, Lose: Preventing Lost Updates
- كاتب موثّق
محتويات المقال
The common misconception
SaveChanges. And on a laptop with one user, nobody else writes between your read and your write. The isolation levels article earlier in this path covered what the default level lets reads see; this one covers writes.
What actually happens
Your read leaves nothing behind
READ COMMITTED, SQL Server releases a shared lock as soon as the read completes, so nothing stops a second transaction from reading the same 10 a moment later. Then comes the write. EF Core sends UPDATE ... SET [Stock] = @p0, a constant your process computed. The database can't know that 7 came from a value that's no longer current, so it writes it, and the next writer replaces it. That's a , and the transaction around it doesn't prevent it.
Fix 1: let the database do the arithmetic
UPDATE Products SET Stock = Stock - @qty WHERE Id = @id AND Stock >= @qty reads and writes in one statement. A second update of the same row waits until the first transaction ends. PostgreSQL's docs describe what happens next at Read Committed: the waiting updater re-evaluates its WHERE clause against the updated version of the row and applies its change to that version. In the test, session B waited about a second for A's commit, then took the stock from 7 to 5. The guard in WHERE replaces your if: when there isn't enough stock, the update matches 0 rows instead of going negative.
Fix 2: check a version when you write
UPDATE: someone editing a product page reads the row, thinks for a minute and saves the whole form. Keep the read, but make the write conditional: add a rowversion column, which SQL Server changes on every update, and update only WHERE Id = @id AND Version = @versionRead. That's : no locks, and the late writer finds out. In the T-SQL test, B's update matched 0 rows. EF Core adds that condition for you when the property is marked [Timestamp] or IsRowVersion(). In a test with EF Core 10, the second SaveChangesAsync threw DbUpdateConcurrencyException: "The database operation was expected to affect 1 row(s), but actually affected 0 row(s)".
Fix 3: lock the row when you read it
UPDLOCK hint takes update locks and holds them until the transaction completes, and only one transaction can hold an update lock on a row. PostgreSQL's SELECT ... FOR UPDATE locks the rows as though for update, blocking other updates, deletes and FOR UPDATE reads until the transaction ends. In both tests, B's locked read waited for A's commit, returned 7, and the stock ended at 5.
A stricter level turns the bug into an error
REPEATABLE READ keeps shared locks to the end of the transaction. In the test, both sessions held one, each UPDATE waited for the other's lock, and SQL Server picked B as the deadlock victim with Msg 1205. Microsoft's guide describes this select-then-update deadlock and recommends UPDLOCK to avoid it. PostgreSQL's Repeatable Read doesn't lock reads: in the test, B's update failed with could not serialize access due to concurrent update. Nothing was lost, but one order failed, and it only succeeds if your code retries the whole transaction.
Reserve stock without losing an update
using Microsoft.EntityFrameworkCore;static async Task ReserveAsync(ShopDb db, int productId, int qty){ // The transaction doesn't stop another request reading the same Stock await using var tx = await db.Database.BeginTransactionAsync(); var product = await db.Products.SingleAsync(p => p.Id == productId); if (product.Stock < qty) throw new OutOfStockException(productId); product.Stock -= qty; // EF sends SET [Stock] = @p0, a constant await db.SaveChangesAsync(); await tx.CommitAsync(); // Test, orders of 3 and 2: stock 10 -> 8}using Microsoft.EntityFrameworkCore;static async Task ReserveAsync(ShopDb db, int productId, int qty){ // Check and write in one statement; a second one waits for the row var updated = await db.Products .Where(p => p.Id == productId && p.Stock >= qty) .ExecuteUpdateAsync(s => s.SetProperty(p => p.Stock, p => p.Stock - qty)); if (updated == 0) throw new OutOfStockException(productId); // Test, orders of 3 and 2: stock 10 -> 5}-- Optimistic (SQL Server): write only if the row is unchangedUPDATE dbo.Products SET Stock = @newStockWHERE Id = @id AND Version = @versionRead; -- test: B got 0 rows-- Pessimistic (SQL Server): hold an update lock until COMMITSELECT Stock FROM dbo.Products WITH (UPDLOCK) WHERE Id = @id;-- Pessimistic (PostgreSQL)SELECT stock FROM products WHERE id = $1 FOR UPDATE;UPDATE | |||
UPDLOCK / FOR UPDATE | |||
REPEATABLE READ |
How to apply it in your project
Find read-modify-write code Look for writes computed from an earlier read: +=and-=on tracked entities, balances, stock counts, and procedures thatSELECTinto a variable andUPDATEwith it. Reproduce one with two connections and a delay between read and write.Push the arithmetic into the UPDATE Use ExecuteUpdateAsyncor plain SQL, put the business check inWHERE, and treat 0 affected rows as "not enough" or "not found".Version the rows people edit Add a rowversioncolumn, map it with[Timestamp], and catchDbUpdateConcurrencyException. On databases without such a type, EF Core supports a concurrency token your code changes on every save.Lock only inside short transactions Use UPDLOCKorFOR UPDATEwhen logic must run between the read and the write, and never hold that transaction open while waiting for a user, which PostgreSQL's docs call a bad idea.
Key takeaways
A transaction at the default level doesn't protect read-modify-write: in tests on SQL Server 2022 and PostgreSQL 18, orders of 3 and 2 left the stock at 8 instead of 5, with no error. Prefer one atomic UPDATEwith the check inWHERE; a concurrent update waits, then applies its change to the current value.When a person or complex logic sits between read and write, check a version on write and handle the conflict. UPDLOCKandFOR UPDATEmake the second reader wait; keep those transactions short.REPEATABLE READturns lost updates into deadlocks in SQL Server and serialization errors in PostgreSQL, so retry from the read.
التعليقات (0)