What this page is for

Intent: understand how two buyers can sell the same last pair, and how transactions, locks and retry stop it.
You’ll learn: atomicity · read-modify-write · lost update · READ COMMITTED vs REPEATABLE READ · error 40001 and retry · FOR UPDATE · optimistic vs pessimistic.
Time: about 7 minutes. Every section has a longer version on the detailed Transactions page.

Words you need first

  • Transaction: statements between BEGIN and COMMIT. All of them are saved, or (on ROLLBACK) none. That is atomic.
  • Isolation: how much a running transaction sees of the others running at the same time.
  • Read-modify-write: read a value, change it in app code, write it back. The gap between read and write is where races happen.
  • Lost update: two read-modify-writes on one row. One write overwrites the other.
  • Snapshot: the consistent “photo” of the data a transaction reads from.
  • READ COMMITTED (Postgres default) and REPEATABLE READ: isolation levels. The second one reads from one snapshot.
  • 40001: the error code (SQLSTATE) for “could not serialize access”. A write conflicts with a change made after your snapshot.
  • Drizzle: a TypeScript library. db.transaction runs a transaction.

This page uses a small shoe shop: products(id, stock), where stock is the pairs left.

Why it exists

Many buyers use the shop at once. Two of them can read “1 pair left” and both buy it. Transactions and isolation keep concurrent work correct.

The picture

Lost update: A and B both read stock 5, A writes 4, B writes 4 from its stale 5, so A's stock update is lost. Below: FOR UPDATE makes B wait, then read 0

How it works, with an example

Simply: Checkout is a few steps: read the stock, check it, save the order, and write the new stock. It is like a shop counter for one buyer. With many buyers at once, the steps can mix, and a sale can go wrong.

What to know: The gap between a read and a write is where races happen. Transactions, isolation, and locks keep the stock count right.

Checkout reads the stock, checks it, inserts an order, and writes the new stock. Each section below takes one way that can go wrong, and the fix.

The most common mistake

BEGIN and COMMIT don't keep others out

A transaction only promises that its own steps all happen or none do. Other transactions keep running and reading. Stopping them is the job of isolation and locks, not BEGIN.

Transactions: all or nothing

Simply: A transaction is a group of steps that all save together, or none do. It is like a bank transfer: money leaves one account and arrives in the other, or neither happens. The database calls this atomic: all or nothing.

What to know: Statements between BEGIN and COMMIT are saved together, or on ROLLBACK none are. A transaction does not stop other transactions from reading or writing at the same time. That is isolation’s job.

Example:

-- SQL
BEGIN;
INSERT INTO shoe_orders (product_id) VALUES (1);
UPDATE products SET stock = stock - 1 WHERE id = 1;
COMMIT;
// Drizzle
await db.transaction(async (tx) => {
  await tx.insert(shoeOrders).values({ productId: 1 });
  await tx.update(products).set({ stock: sql`${products.stock} - 1` }).where(eq(products.id, 1));
});
stepshoe_ordersstock
UPDATE fails, ROLLBACK0 rows1
COMMIT (success)1 row0

Caption: a failure leaves the table as it was. Nothing is half-done.

Why this, not that:

  • Atomicity: all steps succeed, or none do. It does not stop others while you run.
  • Isolation: controls what others see. That is a different job.

Trigger card

When I see several writes that must go together, I use one transaction, because it makes them all-or-nothing. It does not keep other transactions out.

Lost update

Simply: Two cashiers read “5 pairs left” from one notebook page. Each sells one and writes the new count. The second write covers the first, so one sale vanishes. This is a lost update.

What to know: A lost update happens when two read-modify-writes touch the same row, and the later write, built on a stale value, overwrites the earlier one. READ COMMITTED does not block it, and no error is raised. A row lock, one atomic UPDATE, or a retry under REPEATABLE READ stops it.

Example: both buyers run the same read-modify-write.

-- SQL, run by A and by B
SELECT stock FROM products WHERE id = 1;     -- app gets 5
UPDATE products SET stock = $1 WHERE id = 1; -- $1 = 5 - 1, computed in the app
// Drizzle, run by A and by B
const [p] = await db.select().from(products).where(eq(products.id, 1));
await db.update(products).set({ stock: p.stock - 1 }).where(eq(products.id, 1));
timeArowB
t2SELECT, gets 55
t35SELECT, gets 5
t5UPDATE to 4, COMMIT4
t64UPDATE to 4 (from its copy of 5), COMMIT

Caption: final stock 4. Two pairs were sold, so it should be 3.

Why this, not that:

  • The earlier write is lost: A’s sale.
  • The later write survives: B’s, built on a stale 5. Last writer wins.

Trigger card

When I see a SELECT of a value, then an UPDATE of the same row with a number computed in app code, I suspect a lost update. READ COMMITTED does not block that.

Isolation levels and retry

Simply: Isolation decides what a running transaction may see of the others. Under READ COMMITTED, each statement sees the latest saved (committed) data. Under REPEATABLE READ, the transaction keeps one snapshot, a photo of the data taken at its first query. If it tries to write a row that changed after that photo, the database refuses with error 40001, and the app must retry the whole transaction.

What to know: READ COMMITTED (the Postgres default) lets each statement see the newest committed data, so a lost update passes silently. REPEATABLE READ takes one snapshot at the first query, and a write that conflicts with a later change fails with 40001. The fix is to retry the whole transaction from BEGIN.

  • READ COMMITTED (default): each statement sees the latest committed data. Nothing re-checks the app’s earlier decision, so the lost update happens silently.
  • REPEATABLE READ: one snapshot, taken at the first query. If the transaction writes a row that changed after that snapshot, Postgres fails the write with 40001. The fix is to retry the whole transaction.

Example: the checkout under REPEATABLE READ, with a retry loop.

-- SQL, run by A and by B
BEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT stock FROM products WHERE id = 1;     -- snapshot: 5
UPDATE products SET stock = $1 WHERE id = 1; -- $1 = 5 - 1
COMMIT;
// Drizzle
async function buyOne(productId: number) {
  for (let attempt = 1; ; attempt++) {
    try {
      return await db.transaction(async (tx) => {
        const [p] = await tx.select().from(products).where(eq(products.id, productId));
        if (p.stock < 1) throw new Error("sold out");
        await tx.update(products).set({ stock: p.stock - 1 }).where(eq(products.id, productId));
      }, { isolationLevel: "repeatable read" });
    } catch (err) {
      const e = err as { code?: string; cause?: { code?: string } };
      const code = e.code ?? e.cause?.code;
      if ((code !== "40001" && code !== "40P01") || attempt >= 5) throw err;
    }
  }
}
timeArowB
t2BEGIN, snapshot, reads 55
t35BEGIN, snapshot, reads 5
t5UPDATE to 4, COMMIT4
t64UPDATE: ERROR 40001, ROLLBACK
t7retry from BEGIN: reads 4, writes 33

Caption: B’s write is refused, not silently lost. The retry sees 4 and writes 3.

Why this, not that:

  • READ COMMITTED: each statement sees the newest data, and the lost update is silent.
  • REPEATABLE READ: a conflict raises 40001, so retry the whole transaction from BEGIN. Retry only errors that can succeed next time: 40001 (and 40P01, a deadlock), never “sold out” or a constraint error.

Trigger card

When I see error 40001, the transaction tried to write over data that changed after its snapshot. I retry the whole transaction from BEGIN, not the last query.

FOR UPDATE vs SERIALIZABLE and retry

Simply: There are two ways to stop a lost update. The pessimistic way locks the row first with SELECT … FOR UPDATE, so the second buyer waits until the first one finishes. The optimistic way takes no lock. The conflicting write fails, and the app retries it. Pick the lock for a busy row, and the retry when conflicts are rare.

What to know: SELECT … FOR UPDATE takes a row lock that lasts until COMMIT or ROLLBACK, so other writers and other FOR UPDATE calls wait. Under REPEATABLE READ or SERIALIZABLE, a conflict shows up at write time as 40001, and the loop retries.

  • Pessimistic: lock first. SELECT ... FOR UPDATE makes the second buyer wait at the row until COMMIT.
  • Optimistic: no lock. A conflict fails at write time (40001 under REPEATABLE READ or SERIALIZABLE), and the loop retries.

Example:

-- SQL
BEGIN;
SELECT stock FROM products WHERE id = 1 FOR UPDATE; -- row lock until COMMIT
-- app checks stock >= 1 here, then:
UPDATE products SET stock = stock - 1 WHERE id = 1;
COMMIT;
// Drizzle
await db.transaction(async (tx) => {
  const [p] = await tx.select().from(products).where(eq(products.id, 1)).for("update");
  if (p.stock < 1) throw new Error("sold out");
  await tx.update(products).set({ stock: p.stock - 1 }).where(eq(products.id, 1));
});
timeArowB
t2SELECT … FOR UPDATE, gets 1, holds the lock1
t31SELECT … FOR UPDATE: waits
t5UPDATE to 0, COMMIT (lock released)0
t60lock granted, reads 0, “sold out”

Caption: B waits, then reads 0. No oversell.

A one-statement option needs no lock or retry: UPDATE products SET stock = stock - 1 WHERE id = 1 AND stock >= 1, then check that one row changed.

Why this, not that:

  • FOR UPDATE: waiters queue at the row. Pick it for a hot row with many buyers at once.
  • Retry: nobody waits, but conflicts cost a retry. Pick it when conflicts are rare.

Trigger card

When I see SELECT ... FOR UPDATE, other writers queue behind it until COMMIT or ROLLBACK. Plain reads are not blocked.

Say it in an interview

“A transaction groups steps so they all commit or none do. That is atomicity. It does not keep other transactions out; isolation does that. Postgres defaults to READ COMMITTED, where a read-modify-write in app code can lose an update: two buyers read stock 5, both write 4, and one sale vanishes. Under REPEATABLE READ the second writer gets error 40001, and I retry the whole transaction from BEGIN. Or I lock the row with SELECT FOR UPDATE, or write one atomic UPDATE with a stock check. I keep locked work short, because a slow call inside the lock makes everyone wait.”

Questions interviewers ask

Tap a question to see the answer.

Mental map

Transactions mental map

Watch

JaneExplainsIT, YouTube: transaction isolation levels and anomalies in PostgreSQL.

Want more? The detailed Transactions and concurrency page has every step table, the wrong version’s tables, the slow-work timeline and the harder questions. Next topic: Joins.


← Databases and SQL quick revision · Joins →