Selling the last code exactly once
How the backend holds one Wi-Fi code for you before you pay, re-checks it inside the transaction, and makes the claim that hands it over safe to run twice.
Lodge Internet · 14 November 2026 · 7 min read
There is one code left for a plan at your hostel. You tap Pay on the website. At the same moment, someone in the next block taps Pay on the same plan in WhatsApp. Both of you are about to hand Paystack real money, and only one of you can walk away with that code.
Everything in this post exists so that the answer is decided before either card is charged, and so that the person who pays always gets something, never a duplicate and never nothing.
Stock is a row, not a number
A Wi-Fi code at Lodge is a voucher on a hostel's router, which our backend copies into its own stock. Each code is its own row. There is no "codes remaining" counter to decrement, because a counter can say one while two people believe they hold it.
Codes sit in pools. A pool is either one hostel's own stock for a plan, or stock shared by every hostel on the same Wi-Fi controller (the router system that issues the vouchers). Every path below works on a pool, so a shared pool behaves exactly like a single hostel's.
So "is there stock" is a count of rows that pass one rule, is_code_sellable in backend/app/services/controllers.py. A code is sellable when the router says it is unused, it has time left on it, and nobody is holding it right now. Every reader of stock goes through that one predicate: the availability badge on the plans page, the reserve path, the claim path. If they each had their own idea of "available", the badge would promise codes the checkout can't deliver.
The availability badge is cached briefly per server process. That cache is cosmetic. The comment above it in data_codes.py says so plainly: the atomic reserve is the source of truth.
Holding a code before you pay
Before Paystack's checkout opens, the client asks the backend to reserve a code. That is reserve_code_for_pool, and both the website and the bot call the same function, so a code is held the same way whichever door you came through.
It runs as one database transaction, and it does two things in order.
First, it looks for a hold you already have:
mine = tx.query(CODES, where=pool_conditions(pool) + [("reservedBy", "==", uid)], limit=5)
for d in mine:
existing = d.to_dict() or {}
r = existing.get("reservedUntil")
if r and r.timestamp() * 1000 > now_ms and is_code_sellable({**existing, "reservedUntil": None}, now_ms):
tx.update(CODES, d.id, {"reservedUntil": expires_dt, "reservedAt": NOW})
return d.idIf you already hold a live code in this pool, the hold is refreshed and you get the same code back. One active hold per buyer per pool. Tapping Pay, closing the popup and tapping Pay again doesn't quietly lock up a second code that nobody else can buy.
Second, if you hold nothing, it picks a candidate from the pool. This is where the interesting line is:
snap = tx.query(CODES, where=pool_conditions(pool), limit=25)
for d in snap:
fresh = tx.get(CODES, d.id)
if fresh is None or not is_code_sellable(fresh.to_dict() or {}, now_ms):
continue
tx.update(CODES, d.id, {"reservedUntil": expires_dt, "reservedBy": uid, "reservedAt": NOW, ...})
return d.idThe query returns candidates. The code then reads each candidate again, by id, and checks the rule again before writing anything. The comment on that line explains why: the query's snapshot can be stale by the time the transaction acts on it. Another buyer may have taken that code a moment ago, or the router sync may have just marked it used. A candidate is a suggestion. The re-read is the decision.
Why two buyers can't both win
Re-reading inside a transaction only helps if the transaction actually isolates you. On Postgres, run_transaction (in backend/app/repos/postgres/store.py) runs the whole function as one SERIALIZABLE transaction: all its reads first, then its writes, applied together when it returns. If Postgres reports that a concurrent transaction touched the same rows, the function is run again from the top.
So when two buyers race for the last code, one transaction commits its hold. The other is told to retry, re-reads the candidate, finds it held, and moves on. If there's nothing else, it raises _NoCodes and the customer sees "no codes available right now" before paying. That's the outcome we want for the loser of the race: told no, with their money still in their account.
The same store rule forces a shape on the code. Reads must come before writes inside a transaction, and the store refuses a read after a write. It's a small constraint, and it's what keeps every transaction's logic readable top to bottom: look at everything, decide, then write.
The claim: handing the code over
After Paystack confirms the charge, the client calls the claim. The claim verifies the payment with Paystack against the full total the server quoted (more on that in money arithmetic lives in one file), then calls _issue_code_transaction.
Its docstring states the contract in one line: atomically fulfil a paid claim, idempotent on the payment reference. The first thing it does inside the transaction is ask whether this payment already bought something:
prior = tx.query("dataPurchases", where=[("paymentRef", "==", payment_ref)], limit=1)
if prior:
pdata = prior[0].to_dict() or {}
return {"decrypted": pdata.get("claimedCode"), "plan": pdata,
"purchase_id": prior[0].id, "duplicate": True}If it did, you get that code back, flagged as a duplicate so no second email goes out. A double tap, a retried request, or the claim racing the Paystack webhook all end in one purchase.
If not, it uses your held code, but only after checking three things about it: it's still in the right pool, it's yours (matched by the email on the hold, or by your account id for older holds), and it's still sellable apart from your own hold. That last check matters. Between holding a code and paying for it, the router may have marked that voucher used. If so, the transaction doesn't hand you a dead code. It falls through and takes a fresh one from the pool.
The reservation id is never trusted on its own. It's the id of a code row, and code rows are reused, so the same id can belong to different people's holds over time. Ownership is always checked against who you are.
Then, in the same transaction: the code row is deleted from stock, any unreserved duplicate of the same voucher in the same scope is removed with it, and the purchase is written with the payment reference on it.
The database as the last word
Application code can have bugs. So the rule "one sale per payment" is also written into the schema: backend/app/db/schema.py puts a unique index on the purchase's payment reference, with a comment calling it "the backstop behind the claim, webhook and bot paths". Even soft-deleted purchases still count, so a deleted sale can't be replayed into a new one.
If every check in Python somehow missed, the second insert would fail at commit.
When the browser doesn't hear back
You paid, but the claim request timed out on hostel Wi-Fi that was already running out. The page doesn't give up. It switches to polling the claim-status route, which is written to be called as many times as you like. On each call it does one of three things:
- the purchase exists and is yours: return the code;
- it doesn't exist yet, and Paystack confirms the charge: issue it now, through the same
_issue_code_transaction; - Paystack can't confirm it yet: say "pending", and the page asks again.
A purchase under that reference that belongs to someone else returns "pending", never the code. And because the claim, the poll and the webhook all go through one idempotent transaction, it doesn't matter which of them gets there first. The webhook side of this is a post of its own.
The trade-offs
Holding a code before payment means some codes sit held by people who walk away. The hold expires on its own, and the website releases it when you close Paystack's popup. In return, a customer is never charged for a code that doesn't exist.
SERIALIZABLE transactions retry under contention. For one hostel's stock that contention is small, and a retry is cheap next to selling one code twice.
Re-reading every candidate costs an extra read per code tried. We pay it gladly.
What's still open
If the pool is genuinely empty after you've paid (the router sync marked your held code used and nothing else is left), the claim can't invent a code. It records an owed order under your payment reference, tells you to keep that reference, and emails the team. Recording it is idempotent too, so the claim, the poll and the webhook all reaching that point still leave one owed order.
That path is safe, but a person finishes it. The hold protects you from another buyer. It can't protect you from the voucher itself going bad on the router between your tap and your payment, and today that case still ends with someone on our side issuing the code by hand.
Last checked against the product on 14 November 2026.