#46 · Races

Find the bug · #46 · Races Medium Python

The last seat sells twice

Two people buy the last seat at the same moment, and both get a ticket.

On this page

The report

Bug report

A ticketing service sells seats for a show. When two people buy the last seat at the same moment, both get a ticket, and the show ends up with −1 seats left.

The code

Read it first: what should it do? Then click the line where you think the bug is.

PythonClick the line you think is wrong
import asyncio

class Show:
    def __init__(self, seats):
        self.seats = seats
        self.sold = []

    async def book(self, customer, pay):
        """Sells a seat if one is left; pay() waits on the payment gateway."""
        if self.seats > 0:
            await pay(customer)
            self.seats -= 1
            self.sold.append(customer)
            return True
        return False

Read it, then pick a line.

What it prints

Running it on a small example prints the output on the left. It should print the output on the right.

The example
async def pay(customer):
    await asyncio.sleep(0.01)

async def main():
    show = Show(seats=1)
    results = await asyncio.gather(show.book("Asha", pay), show.book("Ravi", pay))
    print(results, show.sold, "seats left:", show.seats)

asyncio.run(main())

It prints

[True, True] ['Asha', 'Ravi'] seats left: -1

It should print

[True, False] ['Asha'] seats left: 0
Show the answer: the bug, the fix, and how you’d find it

The bug (lines 11, 12)

Line 10 checks that a seat is left, line 11 waits for the payment, and only line 12 takes the seat. While the first buyer is paying, the second buyer’s book runs, sees the same seat still free, and pays too. Hold the seat before waiting: with asyncio, code with no await between the check and the update can’t be interrupted.

The fix

8    async def book(self, customer, pay):9        """Sells a seat if one is left; pay() waits on the payment gateway."""10        if self.seats > 0:11            await pay(customer)12            self.seats -= 112            await pay(customer)13            self.sold.append(customer)14            return True15        return False

How you’d find it

  1. Reproduce with two buyers at once (asyncio.gather) and one seat. Both succeed.
  2. Trace the interleaving: A checks (1 seat), A starts paying and gives way; B checks (still 1 seat), B pays; then both take the seat.
  3. The gap is the await between the check and the update. Move the update before it.

The test that catches it

It fails on the code above and passes once it’s fixed. Keep it, so the bug can’t come back.

async def pay(customer):
    await asyncio.sleep(0.01)

async def main():
    show = Show(seats=2)
    results = await asyncio.gather(*(show.book(c, pay) for c in "ABC"))
    assert results.count(True) == 2
    assert show.seats == 0

asyncio.run(main())

Where else this bites

  • The same race between threads, or between two servers sharing a database.
  • Coupons with “one use per customer”.
Your progress stays on this device.