- PostgreSQL
- Concurrency
- NestJS
Spending a credit exactly once: a locked transaction and a balance that can’t go negative
In RightUni, agencies prepay credits for student leads. Each credit is spent in the same locked transaction as its ledger row, and the database refuses a negative balance, so two leads at once can’t overspend.
Toukir Ahmed Rony · · 3 min read
RightUni is free for students. It earns money from study-abroad agencies, in a way we tried hard to keep fair.
Agencies buy credits in advance. When a student asks for help and chooses an agency, and ticks to give consent, the agency spends one credit and receives that student's details. Agencies are shown in random order, never ranked by how much they pay, and a student's details only go to the agency the student picks.
That model is simple to describe. The tricky part is the moment a credit is spent.
The race
Picture an agency with exactly one credit left. Two students choose it at almost the same moment.
The obvious code checks the balance, sees one credit, and spends it. The trouble is that both requests can run that check before either has spent anything. Both see "1 credit", both go ahead, and the agency ends up with two leads for one credit, and a balance of minus one.
Each request did the right thing on its own. Together they broke the rules. It's the same kind of bug as two customers booking the same appointment, which I wrote about in my Slotwise post on double-bookings.
Spend inside one locked transaction
In RightUni, a credit is spent in the same locked transaction as its ledger row. At the start of that transaction, the agency's row is locked:
/** SELECT … FOR UPDATE on the agency: concurrent uses of its credits queue up behind this. */
async lockAgency(tx: Tx, agencyId: string) {
const rows = await tx.$queryRaw<{ id: string; status: string; creditBalance: number }[]>`
SELECT "id", "status"::text AS "status", "creditBalance" FROM "Agency" WHERE "id" = ${agencyId}::uuid FOR UPDATE`;
return rows[0] ?? null;
}FOR UPDATE means that while one spend is running for an agency, a second spend for the same agency has to wait its turn. When it gets its turn, it sees the real, updated balance. The nightly expiry job and admin credit changes take the same lock, so they can't race a spend either. The student's own row is locked too, so one student can't race their own daily limits.
Every spend also writes a row in the credit ledger. The balance and the ledger change together or not at all. There is no moment where a credit has left the balance but no ledger row says where it went. And if there isn't enough credit, nothing is created, not even the lead.
The database has the final say
On top of the lock, the database refuses a negative balance. A check constraint, Agency_balance_not_negative, requires the balance to stay at zero or above. Even if some future code path forgets to take the lock, PostgreSQL will reject a spend that takes the balance below zero.
I like having both. The lock makes the normal case correct and orderly. The database rule makes the worst case impossible. If the two ever disagreed, the database would win.
Other parts of the money flow
A few related details keep the credit system honest:
- Credits expire, and expiry runs as a nightly background job on BullMQ, so no web request waits for it.
- Agencies see their leads, their balance, when credits expire, and their credit history.
- Agencies are vetted before they appear, and only show on universities we've confirmed they represent. An agency with no credits left is hidden automatically. The admin panel has fraud flags for anything that looks wrong.
What it costs
The lock has a cost. Spends for the same agency run one after another instead of side by side. At RightUni's size that is not a problem, because one agency rarely receives many leads in the same second. But it is a queue, and at much larger scale it would need a second look.
What I took from it
Any time money or credits move, ask: what happens if two requests arrive at once? If the honest answer is "both might succeed", the check belongs inside a lock, and the final rule belongs in the database, where no code path can skip it.
