Money taken, seat not confirmed

The payment goes through, then the server dies. Now what?

The lesson

  1. Never charge with nothing written down.
  2. Write "pending" first, then "paid" and the booking in one transaction.
  3. After a crash, ask the provider about every pending payment.

The code

start nothing after this is saved yet
BEGIN;
mark it paid her row now says paid
UPDATE payment SET status = 'paid'
 WHERE payment_id = 'pay_77';
the booking write her booking
INSERT INTO booking
VALUES ('pay_77', '14A');
save both together, or neither
COMMIT;
it reaches COMMIT
paid and the booking are both saved
the server dies first
neither is kept: the row still says pending

What this lab leaves out

  • The hold check, and the seat's own row. In the full design the same transaction also checks that her hold is still valid, and marks the seat as booked. Without that check, a seat whose hold ran out and was taken by someone else could be booked twice.
  • The video saves "paid" by itself, then books. This lab writes "paid" and the booking together, which is enough for a crash. The separate "paid" record matters when the seat can no longer be booked: the money has moved, and a charge cannot be rolled back, so it is refunded.
  • The provider's other answers, and who asks. A job asks the provider about payments that have been pending for a while. The lab shows it at a restart, to keep one picture. If the provider says the payment failed, it is marked failed and the seat goes back on sale. If it does not know yet, the row stays pending and we ask again.
  • Why the provider gets our id. With our id, a charge that is sent twice is taken only once.
  • The "paid" message can arrive more than once. The provider calls us back when a payment goes through, and it may send the same message two or three times. The video keeps a table of the messages it has already handled, and skips a repeat.

In the video

This idea is taught at 28:24 in the video, with the rest of the design around it.