Concurrency Checkpoint

Fix GreenMart's Race Condition

Playground Checkpoint

Design and build a real schema — no auto-grading, just a real attempt.

20–24 min

The Challenge

Mike wants the flash sale relaunched — correctly this time. Sarah's job: rewrite the checkout logic so it can never oversell an item again, no matter how many customers hit "buy" at the same instant.

Open the Playground and write the safe pattern yourself: one atomic statement, wrapped in a transaction, verified before it's ever trusted.

What Your Schema Needs

  • Write a single, atomic UPDATE statement that decrements a product's stock only if InStock is currently greater than 0 — never a separate SELECT followed by a second UPDATE.
  • Wrap the stock update and the sale record (INSERT into Sales) inside one transaction, so both succeed together or neither does.
  • After the UPDATE, check SQLite's changes() function to see how many rows it actually affected.
  • If changes() is 0, the item was already out of stock — ROLLBACK the transaction, and do not insert a sale.
  • If changes() is 1, the update succeeded — INSERT the sale, then COMMIT.
  • Test both paths: attempt a sale against Bananas (already out of stock) and confirm it's correctly refused, then attempt one against Rice (still in stock) and confirm it correctly succeeds.
Stuck? A Few Hints
  • The check and the decrement have to happen in the exact same UPDATE statement — a separate SELECT first brings the original race condition right back.
  • SQLite's changes() function, called right after a statement, tells you exactly how many rows that statement actually affected.
  • If changes() comes back 0, the sale never really happened — don't INSERT into Sales, and roll the transaction back instead of committing it.

Ready to Build It?

Opens the Playground, right in your browser — nothing to install.

Open Playground

Before You Move On

Every skill from this Act comes together here — the atomic UPDATE from the locking chapter, wrapped in a real transaction, verified with a row-count check instead of a second read that could itself race. The next Act moves past correctness entirely: GreenMart now has millions of rows, and the query that used to be instant isn't anymore.

Next