Free an unpaid hold only after asking the payment provider one last time
One of my side projects lets people register for events that cost money. Registering creates a row right away and holds a spot, then sends the person to a hosted checkout page from the payment provider. When the payment goes through, a webhook flips the registration to paid.
That works until someone opens the checkout, gets distracted, and closes the tab. Now there is a registration that says “pending” forever. It holds a spot at an event with limited capacity, it shows up on the staff list as someone who might be coming, and the person who started it has no clear way to either finish or back out.
The obvious fix is a background job that deletes old pending rows. That fix is also how you end up with a paid customer who has no registration. Here is how I handled it instead.
Why “delete anything pending older than a day” is wrong
Three things can go wrong with the simple sweep:
- The payment can land after your query. The job reads the row as pending, the person pays in the meantime, and the job frees the spot a second later. Now the money is in and the seat is gone.
- The webhook can be late or lost. Pending in your database only means you have not heard about a payment yet. It does not mean there was no payment.
- Old rows have unknown history. Registrations created before the sweep existed were never promised any deadline. Some of them may be intentional, like a staff member holding a spot while a family sorts out payment in person. Expiring those silently is a surprise for everyone.
So the rule I wanted was narrow: only release holds that were created knowing they would expire, and only after confirming with the provider that nothing was paid.
Give each hold its own deadline at creation time
When a new paid registration is created, it gets a pending_expires_at timestamp. I set it to
24 hours out, or to the checkout session’s own expiry if that comes sooner, so the two never
disagree about when the offer ends.
That one column does a lot of work. The sweep only looks at rows where it is set, so anything created before this change has no marker and is never touched automatically. Before shipping, I also wrote a read-only script that counts pending registrations by age, so I knew exactly how many old ones existed and could deal with them by hand. There was one.
Expire the checkout, then check, then release
The order matters. If you release the spot first and then try to stop the checkout, there is a window where the person can still pay for something you already gave away. So the sweep does it the other way around:
def release_if_unpaid(reg):
if reg.status != "pending" or reg.pending_expires_at is None:
return "skipped"
if reg.pending_expires_at > now():
return "not_due"
# 1. Close the door: the old checkout can no longer take money.
try:
provider.expire_checkout(reg.checkout_id)
except AlreadyCompleted:
pass # it was paid; the check below will see it
# 2. Ask one last time. The provider is the source of truth for money.
session = provider.get_checkout(reg.checkout_id)
if session.payment_status == "paid":
mark_paid(reg, session) # same code path the webhook uses
return "paid"
# 3. Only now is it safe to give the spot back.
updated = db.execute(
"UPDATE registrations SET status = 'cancelled_unpaid' "
"WHERE id = %s AND status = 'pending'",
[reg.id],
)
return "released" if updated.rowcount == 1 else "changed_underneath"
A few details earn their place:
- Expiring the checkout is the lock. Once it is expired, no new payment can arrive through it, so the check in step two is final instead of a snapshot that could go stale.
- A paid result goes through the normal paid path. If the webhook was lost, the sweep fixes it with the same function the webhook would have called. There is one way a registration becomes paid, not two.
- The update is conditional.
WHERE status = 'pending'means that if the webhook won the race and marked it paid a moment earlier, the release does nothing. The job reports that instead of overwriting it. - The status is honest. “Cancelled, not paid” is different from “cancelled by the person” and different from “refunded”. Staff can tell at a glance what happened.
Give the person the same two choices
The background job handles people who walk away. People who come back need a way out too. A pending registration now says it needs payment to finish, with two buttons: finish paying and cancel.
Finish paying checks with the provider first. If the old checkout is still open, it sends the person back to that same checkout. If it already expired and the spot is still available, it starts a fresh checkout on the same registration row. It never creates a second registration, so there is no way to end up with two rows and two charges for one seat.
Cancel uses the exact same sequence as the sweep: expire the checkout, check again, then release. If a payment came through while they were deciding, they stay registered and paid, and the screen tells them so. Cancel never issues a refund and never charges anything. It only gives back a spot nobody paid for.
Sharing one function between the button and the job is the part I would repeat on any project. The race conditions are the same whether a person or a timer starts the cancel, so there is no reason to solve them twice.
Tradeoffs
- The sweep makes network calls. Every release costs two requests to the provider. With a small number of pending rows per tick that is fine. At larger scale I would batch them and cap how many the job handles per run.
- A provider outage pauses releases. If the provider cannot be reached, the job skips the row and tries again next tick. A spot stays held a little longer. I would much rather hold a seat too long than give away one somebody paid for.
- Old holds need a human. Leaving unmarked rows alone means someone has to look at them. The read-only count script makes that a five minute job instead of a guess.
- Deadlines are a promise. Once the screen says a spot is held for 24 hours, changing that number later only applies to new holds. Rows keep the deadline they were created with.
Tests that cover the races
The unit tests fake the provider and walk through each ordering: unpaid and expired, paid before the sweep, paid between the expire call and the check, webhook arriving after the check, and a row with no deadline at all. The one I care about most is the middle case, where the payment lands during the sweep. It has to end paid and registered every time.
The pattern
When a background job is about to undo something that involves money, it should not trust its own database alone. Mark which records are allowed to expire when you create them, close the door on new payments first, ask the source of truth one last time, and make the final write conditional on nothing having changed. Then let the person do the same thing with a button.