الانتقال إلى المحتوى
قواعد البياناتالـ Transactions والـ Concurrency· 8 دقائق للقراءة

Read, Modify, Write, Lose: Preventing Lost Updates

A transaction at the default level doesn't stop two requests from overwriting each other. Do the math in the UPDATE, check a version on write, or lock the row you read.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
محتويات المقال

An inventory count finds 5 desk lamps on the shelf, but the product page says 8 are in stock. Two orders, for 3 lamps and 2, arrived a second apart, and the reservation code did what most code does: load the product, subtract the quantity in C#, save, all inside a transaction. In a test on SQL Server 2022 with two sessions, session A read a stock of 10, session B read 10 a second later, A wrote 7 and committed, then B wrote 8 and committed. Both updates reported 1 row affected, nothing failed, and the shop now promises 3 lamps it doesn't have. The same test on PostgreSQL 18 also ended at 8.

The common misconception

The belief: reading a value, changing it in application code and writing it back is safe as long as all three steps run inside one transaction.

It's a reasonable belief. Transactions are taught as the tool for concurrency, and "isolation" sounds like nobody else can touch the rows you're working on. ORMs make the pattern the default: load an entity, change a property, call 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

Microsoft's locking guide describes it exactly: lost updates occur when two or more transactions select the same row and then update it based on the value originally selected, and the last update overwrites the others. At 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

Not every change fits in one 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

When the logic between the read and the write is too complex for SQL but runs in one short transaction, take the lock at read time. SQL Server's 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

SQL Server's 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

C#
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}

When the new value can't be computed in SQL, use one of the other two patterns:

SQL version-or-lock.sql
-- 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;
ApproachHow it stops the lost updateWhat it costsUse it for
Atomic UPDATERead and write are one statement on the current rowNothing extra, but the logic must fit in SQLCounters, stock, balances
Version checkThe write matches 0 rows if the row changedConflicts to handle: re-read, then retry or ask the userForms, API edits, long think time
UPDLOCK / FOR UPDATEThe second reader waits until the first commitsBlocking for as long as the transaction runsComplex check-then-write in a short transaction
REPEATABLE READOne transaction fails: deadlock or serialization errorA retry of the whole transactionCode already running at that level

How to apply it in your project

  1. Find read-modify-write codeLook for writes computed from an earlier read: += and -= on tracked entities, balances, stock counts, and procedures that SELECT into a variable and UPDATE with it. Reproduce one with two connections and a delay between read and write.
  2. Push the arithmetic into the UPDATEUse ExecuteUpdateAsync or plain SQL, put the business check in WHERE, and treat 0 affected rows as "not enough" or "not found".
  3. Version the rows people editAdd a rowversion column, map it with [Timestamp], and catch DbUpdateConcurrencyException. On databases without such a type, EF Core supports a concurrency token your code changes on every save.
  4. Lock only inside short transactionsUse UPDLOCK or FOR UPDATE when 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 UPDATE with the check in WHERE; 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.
  • UPDLOCK and FOR UPDATE make the second reader wait; keep those transactions short.
  • REPEATABLE READ turns lost updates into deadlocks in SQL Server and serialization errors in PostgreSQL, so retry from the read.

📚 المصادر

  1. Transaction locking and row versioning guide — SQL Server, Microsoft Learn
  2. Table hints (Transact-SQL) — SQL Server, Microsoft Learn
  3. Handling concurrency conflicts — EF Core, Microsoft Learn
  4. Explicit Locking — PostgreSQL 18 documentation
  5. Transaction Isolation — PostgreSQL 18 documentation

التعليقات (0)