Skip to the page

Transactions and locking · Write code

Two buyers and the last phone

The interviewer asks

Two customers buy the last unit of a phone at the same moment. Both get an order confirmation, and stock shows 0. Here's the code. What went wrong? Give me two ways to fix it.

row = db.query("SELECT stock FROM products WHERE id = %s", [pid])
if row.stock >= qty:
    db.execute("UPDATE products SET stock = %s WHERE id = %s", [row.stock - qty, pid])
    create_order(user, pid, qty)

Then

Follow-ups the interviewer asks next

  1. What is this bug called?
  2. If you wrap these lines in a transaction at READ COMMITTED, is it fixed?
  3. Which fix would you pick for a flash sale with 50,000 buyers for 1,000 phones?
  4. What would PostgreSQL do here at REPEATABLE READ?
  5. How would you test that your fix works?

The answer

What a strong answer covers

  • A lost update (read-modify-write race): both read 1, both compute 0, both write 0, and two orders exist for one phone.
  • A transaction at READ COMMITTED does not fix it; the reads still don't block each other.
  • Fix 1, an atomic conditional update: UPDATE products SET stock = stock - %s WHERE id = %s AND stock >= %s, then check that exactly one row changed; add CHECK (stock >= 0).
  • Fix 2, pessimistic: SELECT stock … FOR UPDATE inside a transaction, so the second buyer waits and then sees 0.
  • Fix 3, optimistic: a version column, UPDATE … WHERE id = ? AND version = ?, and retry when no row changed.
  • The stock change and the order insert go in the same transaction, so a failure can't leave one without the other.
  • At REPEATABLE READ, PostgreSQL fails the second UPDATE with "could not serialize access due to concurrent update", and the app must retry.
  • Flash sale: one hot row becomes a queue of lock waits. Options: an atomic counter in Redis as a gate in front of the database, stock split into several rows (buckets), or a queue of purchase requests.
  • Test: many parallel requests for the same item in an integration test, then assert stock never goes below zero and orders equal units sold.

The red pen

Common traps

Avoid:"add a transaction" as the whole answer; synchronized or a mutex in one server (useless across many servers).

Practise this out loud

Say your answer out loud to an AI interviewer that follows up, and get a score for it.

Practise by voice

Practise questions like this out loud

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview