Hajj Ticket War Part 6: State Machine

An image with the text "hajj ticket war part 6: state machine"
Background image by Ghulam Sarvar from Unsplash

Part 5 left the status columns on reservation and payment empty on purpose. This part fills them in and covers the checks that decide whether a reservation can be made at all.

The state machine is on the reservation. The payment has a small one of its own.

Checks before a reservation

Creating a reservation goes through five checks:

  1. The stage is open and the pilgrim belongs to it.
  2. The pilgrim is ready for this season. Only stages 2 to 4 need this.
  3. The health check is still valid.
  4. The pilgrim has no other active reservation this season.
  5. A seat is left.

Stage 1 skips check 2. Nobody re-registers there, so the reservation is created when the pilgrim opens the payment screen and the seat already follows the schedule. It holds the seat until expires_at and how long that is comes in a later part.

A pair of pilgrims is one reservation with two seats, as in part 5, so the statuses below apply to the pair as a whole. How its two payments work comes in a later part.

The five checks run in one transaction and the order is on purpose. We start with the cheapest, checks 1 to 3, which only read a pilgrim row and a stage row. Check 4 is the partial unique index from part 5, which fails at insert if the pilgrim already has a reservation that’s held or paid. Check 5 is the counter update, the only one that takes a lock.

The database holds a row lock until that transaction ends. So the counter update is the last statement and the transaction commits right after it. If it updates no row, the whole transaction rolls back, including the reservation insert.

Checks 1 to 3 can also be answered early from a cache, to turn away the obvious failures without touching the primary database, the one that takes the writes.

But the cache can be out of date. It might still show a stage as open after it closed, or miss a health check that was just updated. So the cache only turns people away and the real checks still run in the transaction on the primary.

How long a health check stays valid decides what losing costs. I didn’t find a rule, so I assume about 3 months. A pilgrim has to time the checkup so it’s still valid on the day of the stage and health_check_valid_until holds that date.

Someone who loses stage 3 pays for a new checkup the next season. At 10% ready there are about 480 people for each of the 1k seats nationwide, so almost everyone who gets ready loses. This design doesn’t remove the cost of a wasted checkup, but nobody is forced to pay it.

Everyone in stage 3 is scheduled more than 4 years out and gets their own turn in stage 1 or 2 without a war. Playing stage 3 is a choice to try to skip ahead.

Reservation statuses

A reservation that passes the checks starts as held. These are all the statuses it can have:

StatusMeaning
heldThe reservation waits for payment while it holds seats or counts as a reserve
paidThe payment succeeded. For a seat this is final. For a reserve it means paid, with no seat yet
expiredThe pilgrim didn’t pay before expires_at and the seats went back
withdrawnA paid pilgrim gave up before registration closed and the seat went back
promotedA paid reserve that got a seat
rolledA paid reserve that got no seat before registration closed and carries into stage 0 next season
A reservation starts as held when the pilgrim passes the checks. From held it goes to expired when expires_at passes and the seats go back, or to paid when the payment succeeds. A paid seat can only go to withdrawn when the pilgrim gives up and the seat goes back. A paid reserve has no seat yet and goes to promoted when a seat opens or to rolled when registration closes

These are the moves between them and what each one does to the counter:

FromToTriggerCounter
noneheldThe pilgrim passes the checksseats_taken plus seats, or reserve_taken plus 1 for a reserve
heldpaidThe payment succeedsNo change
heldexpiredexpires_at has passedGives back
paid (seat)withdrawnThe pilgrim gives upGives back
paid (reserve)promotedA seat opens and this is the next reserve by queue numberseats_taken plus 1, conditional
paid (reserve)rolledRegistration closes with no seatNo change

Nothing leaves expired, withdrawn, promoted or rolled. A seat that went back can be taken by someone else, so moving the old reservation back to held would leave seats_taken lower than the seats actually held. A pilgrim who wants a seat again makes a new reservation.

A trigger enforces which move is allowed. It runs before every update of status and rejects any pair that isn’t in the table above, such as expired back to held, even if some code forgets to check. The WHERE clause in each update still settles a race between two moves, as the next section shows.

One rule for every move

Every status change is a conditional update that names the status it expects. Expiry is the example:

-- $1 is the reservation id
-- The update only happens if the reservation is still held and the seats
-- go back in the same statement, so a seat can't be given back twice.
WITH moved AS (
UPDATE reservation
SET status = 'expired'
WHERE id = $1
AND status = 'held'
RETURNING quota_id, seats
)
UPDATE quota
SET seats_taken = seats_taken - moved.seats
FROM moved
WHERE quota.id = moved.quota_id;

If the reservation isn’t held, the first update returns no rows and the second one has nothing to give back. For a reserve, the second update subtracts from reserve_taken instead.

This matters because two things can move the same reservation at the same time. A payment can succeed in the same moment the expiry job picks that reservation up. Whichever update runs first wins and the other one updates no row.

The payment side is the same shape:

-- $1 is the reservation id
UPDATE reservation
SET status = 'paid'
WHERE id = $1
AND status = 'held';

For a reserve, this also requires reserve_ack_at to be filled in, the rule from the overbooking cap.

If no row is updated, the reservation already expired and the payment can’t be used. That’s the late payment case from part 5 and the money goes back.

The payment update never looks at the clock. It only checks that the status is still held. expires_at just tells the expiry job when to move a reservation to expired. How the job picks rows comes in a later part.

So if the job runs a few seconds late and a payment arrives in that time, the payment still works. The seat stays in seats_taken until the job moves the reservation, so nobody else could have taken it.

Payment statuses

A payment has three statuses: pending, succeeded and failed. It moves from pending to one of the other two and then stays there. When it succeeds, the reservation moves from held to paid with the SET status = 'paid' update in the previous section. Late payments, retries and reconciliation with the payment provider come in the part on payments in flight.

Where each move runs

Every move writes, so every move runs on the primary. A replica only shows a status. A status page may show held for a moment after the payment succeeded, which is fine for a screen.

The writes are bounded by the seats. At about three writes per reservation (the insert, the status change, the payment) across 203k seats, that’s roughly 600k writes in a season. It counts one payment per reservation and each retry adds one, so the real number is higher but still small.

The pressure is somewhere else. In the first seconds of stage 3, thousands of requests a second compete for 1k seats and almost all of them fail before they write anything, as part 4 showed. A later part deals with them.

Next is the load profile and the high-level design.

soft pattern background