Backend Case Studies

Topic B11

Transactions and race conditions

Two requests, one piece of data: why read-then-write fails, and three ways to fix it.

11 min · advanced

Watch: Ana and Budi buy the last ticket at the same moment. The first method sells two tickets for one seat.

0 soldstock 1TICKETAna: wants oneBudi: wants one
  • writing / getting the ticket
  • looking at stock, or a double ticket
  • waiting for the lock
  • holds a valid ticket
Step 1 of 5

One concert ticket left. Ana and Budi press Buy in the same millisecond, handled by two different server processes.

The problem is the gap between reading the stock and writing it. Another request can slip into that gap.

Why you don't see it in development

On your laptop, requests come one at a time, so the gap between reading and writing never gets filled. In production, hundreds of requests run at once across many processes. During a flash sale or a concert ticket release, thousands of people press the button in the same second, and that gap of a few milliseconds gets filled over and over. The bug shows up as negative stock, wrong balances, or a coupon used twice.

Code, for programmersThe bug: read, then write
const { stock } = await db.ticket.findUnique({ where: { id } });
if (stock > 0) {
  // another request can run right here and also see stock = 1
  await db.ticket.update({ where: { id }, data: { stock: stock - 1 } });
  await createOrder(userId, id);
}

Three fixes

Code, for programmers1. An atomic UPDATE: check and change in one statement
const { count } = await db.ticket.updateMany({
  where: { id, stock: { gt: 0 } },
  data: { stock: { decrement: 1 } },
});
if (count === 0) throw new Error("sold out");
// SQL: UPDATE tickets SET stock = stock - 1 WHERE id = $1 AND stock > 0
Code, for programmers2. Lock the row inside a transaction
BEGIN;
SELECT stock FROM tickets WHERE id = 7 FOR UPDATE;  -- others wait here
-- check in code, then:
UPDATE tickets SET stock = stock - 1 WHERE id = 7;
INSERT INTO orders (user_id, ticket_id) VALUES (42, 7);
COMMIT;                                             -- the lock is released
Code, for programmers3. Let the database refuse bad data
ALTER TABLE tickets ADD CONSTRAINT stock_not_negative CHECK (stock >= 0);
ALTER TABLE coupon_uses ADD CONSTRAINT one_use UNIQUE (coupon_id, user_id);

What a transaction is

A transaction groups several statements into one: all of them succeed, or all of them are undone (ROLLBACK). Decrementing stock and creating the order must be one transaction; if creating the order fails, the stock mustn't have dropped. But a transaction alone doesn't automatically prevent race conditions. At PostgreSQL's default isolation level (READ COMMITTED), two transactions can still read the same stock. You still need one of the three fixes above.

Quiz

  1. Why do race conditions rarely show up in development?

  2. Which stops two people buying the last ticket?

  3. In default PostgreSQL, is wrapping read-then-write code in BEGIN/COMMIT enough on its own?

0 of 3 answered.