Find the bug · #48 · Races Hard Python
A retried payment charges twice
When the payment gateway is slow to reply, the retry charges the customer a second time.
On this page
The report
Payments are retried when the gateway doesn’t reply in time. Some customers are charged twice: their bank shows two identical charges a few seconds apart.
The code
Read it first: what should it do? Then click the line where you think the bug is.
import uuid
def pay(gateway, amount, retries=2):
"""Charges once, retrying if the gateway doesn't reply in time."""
for attempt in range(retries + 1):
try:
return gateway.charge(amount, key=str(uuid.uuid4()))
except TimeoutError:
if attempt == retries:
raise
class Gateway:
"""A stand-in for the payment gateway. Like real ones, it charges each key only once."""
def __init__(self, times_out_once=False):
self.charges = []
self.receipts = {}
self.times_out_once = times_out_once
def charge(self, amount, key):
if key in self.receipts:
return self.receipts[key]
self.charges.append(amount)
self.receipts[key] = f"receipt-{len(self.charges)}"
if self.times_out_once and len(self.charges) == 1:
raise TimeoutError("the charge went through, but the reply was lost")
return self.receipts[key]Read it, then pick a line.
A timeout doesn’t mean the charge failed. How does the gateway tell a retry from a brand-new payment?
What it prints
Running it on a small example prints the output on the left. It should print the output on the right.
gateway = Gateway(times_out_once=True)
print(pay(gateway, 499))
print("charged:", gateway.charges)It prints
receipt-2 charged: [499, 499]
It should print
receipt-1 charged: [499]
Show the answer: the bug, the fix, and how you’d find it
The bug (line 7)
Line 7 makes a new idempotency key on every attempt. A timeout doesn’t mean the charge failed (here it went through and only the reply was lost), and the gateway can only spot a retry by its key. With a fresh key, the retry looks like a new payment and is charged again. Make the key once, before the loop, and reuse it for every attempt.
The fix
2 3def pay(gateway, amount, retries=2):4 """Charges once, retrying if the gateway doesn't reply in time."""5 key = str(uuid.uuid4())5 for attempt in range(retries + 1):6 try:7 return gateway.charge(amount, key=str(uuid.uuid4()))8 return gateway.charge(amount, key=key)8 except TimeoutError:9 if attempt == retries:10 raiseHow you’d find it
- Reproduce with a gateway that charges but loses the first reply: two charges.
- Read the gateway’s contract: the same key is charged only once. So the retry must be sending a different key. Print the keys: they differ.
- The key is created inside the loop. It should identify the payment, not the attempt.
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.
g = Gateway(times_out_once=True)
pay(g, 100)
assert g.charges == [100]
g2 = Gateway()
assert pay(g2, 50) == "receipt-1" and g2.charges == [50]Where else this bites
- Retrying any request that has side effects: sending an email, creating a record.
- Message queues that deliver “at least once”: consumers must ignore duplicates.