Bugpit

Lessons › Core concepts

Last one in stock

A phone launch: 7,500 req/s, and 20% are people pressing Buy on the same phone, 1,500 a second. Last launch, the shop sold more phones than it had, and had to refund angry customers.

Play this level

Free with an account. It runs in your browser: build the design, press Run, and watch what breaks.

The lesson

The app reads the stock, sees 1 left, then writes the sale. Two buyers who read within the same few milliseconds both see 1 left, and both buy it. That's a race: the result depends on timing, so it never shows up in testing.

The fix is to check and take in one step: UPDATE stock SET left = left - 1 WHERE id = 7 AND left > 0. The database locks the row for the update, so only one buyer gets the last unit. If no row changed, it's sold out.

That lock has a price. Every Buy of this phone now waits its turn for the same row, about 1,200 a second however big the database is. Press Run after you switch it on and watch.

Put the buys in a queue. Each buyer hears "you're in line" at once, and workers take buys at a pace the row can keep up with. Big shops also hold a unit for a few minutes while the buyer pays, and put it back if they don't.

What you have to achieve

7,500 requests a second at the busiest hour, 20% of them writes.

What you learn

Nothing is sold twice, and the database never drowns: the queue turns a crowd into a line. A race like this is invisible until real traffic arrives, which is why launches are when shops oversell.

Check yourself

The app reads the stock, sees 1 left, then writes the sale. Why can two people buy the last phone?

Show the answer

Both read before either writes, so both see 1 left. Reading and then writing are two steps. Anything can happen in between, including another buyer reading the same 1.

Buys now take stock in one locked step, and the database is overloaded. What helps?

Show the answer

A queue, so workers send buys no faster than the row can take. Every Buy waits for the same row lock, so a bigger machine adds nothing. A queue lines buyers up instead of piling them onto the row.

Try it yourself

More in Core concepts

← All or nothing Two transfers, stuck forever →