The hold that ends while she is paying
Her ten minutes end while she is paying. Who gets the seat?
The lesson
- Never give away a seat while she is paying.
- Before you charge, mark the seat as payment pending.
- Then only the provider's answer can free it.
The code
the change mark the seat as being paid for
UPDATE show_seat SET status = 'payment_pending'
which row only the row of seat 14A
WHERE seat_id = '14A'
the check only if her hold is still running
AND status = 'held' AND held_by = 'Priya' AND held_until > now();
- 1 row changed
- now charge her card
- 0 rows changed
- do not charge her
The code that follows it
when the provider says yes 1 row changed: "paid" and the booking are written with it, in one transaction. 0 rows: no booking is written, "paid" is saved by itself, and she is refunded.
UPDATE show_seat SET status = 'booked' WHERE seat_id = '14A' AND status = 'payment_pending' AND held_by = 'Priya';
when the provider says failed The payment is marked failed and the seat goes back on sale, together.
BEGIN; UPDATE payment SET status = 'failed' WHERE payment_id = 'pay_77'; UPDATE show_seat SET status = 'available', held_by = NULL, held_until = NULL WHERE seat_id = '14A' AND status = 'payment_pending' AND held_by = 'Priya'; COMMIT;
What this lab leaves out
- Why not just give the hold more time? More time only moves the problem. A held seat is freed by the clock alone, so a slow payment can still lose it. A seat that is being paid for is freed by the provider's answer.
- It does not stay that way for ever. The video gives this state its own deadline, a little longer than the time to check out. When it passes with no clear answer, a job asks the provider. A payment that failed, or that timed out, puts the seat back on sale. Otherwise someone could keep a seat just by starting a payment.
- Why nothing gets between its check and its change. They are one query, as in the first lab. The database runs two changes to one row one after the other, so Rahul's query runs either before hers or after it, never in the middle.
- Pay clicked twice. The second click changes 0 rows, so no second charge starts. On 0 rows our code reads the row: if it says she is already paying, it shows that payment, not an error.
- It is saved together with the payment's "pending" row. Both are written before the charge, in one transaction: the payment row from the lab before this one, and this change to the seat. A seat marked as being paid for, with no payment row, would have nothing to end it.
- The video's row points to a hold, not to a person. Each hold is its own record, and the row carries its id. Then a late answer about an old payment can never touch a newer hold of the same person. Here the row just names Priya, so it can be read at a glance.
In the video
This idea is taught at 28:24 in the video, with the rest of the design around it.