← All work
Open-Source Core2026 · Sole Engineer

edtech-billing-core: Race-Safe Billing on PostgreSQL

Append-only ledger · Deadlock-free lock order · Verified payment webhooks · Open source

Integration Tests
110 Passing
All against a real PostgreSQL 16, no database mocks; green CI on every push
Mutation Check
15 / 15 Killed
Each defence removed in turn; the suite must fail for every one
Isolation Level
READ COMMITTED
Explicit lock order instead of SERIALIZABLE retries

Key decisions

READ COMMITTED with one explicit lock order

RejectedSERIALIZABLE transactions plus SELECT … FOR UPDATE on the student (the original production design)

A concurrency probe showed roughly 9 in 10 concurrent writes aborting with serialization failures (40001), and FOR UPDATE deadlocking against a cancellation's foreign-key checks. Ordered FOR NO KEY UPDATE / FOR SHARE locks make every concurrent call succeed without retries.

Append-only ledger enforced by a database trigger

RejectedDeleting and rewriting a lesson's charge when attendance changes

Corrections become reversal rows, so every balance can be explained row by row, and no application bug can silently rewrite history.

Every reversal names the charge it reverses, with a UNIQUE constraint on that column

RejectedRelying on every code path that reverses a charge to check the lesson's state under the right lock

A second reversal of the same charge now fails at insert, whichever path writes it. A future feature that forgets a rule gets an error instead of a wrong balance. Suggested by a reader of the write-up.

Context

The money-handling core of the production platform I run for an online school, extracted into a standalone, framework-free TypeScript library on plain PostgreSQL. The production code is private; this repository is the part worth reviewing, with every lock and constraint visible as plain SQL.

Billing: exactly-once charges under concurrency

Staff mark, re-mark, clear and cancel lessons at the same time. The student must be charged exactly once, and the ledger must always agree with the attendance journal.

  • Append-only ledger. A trigger rejects UPDATE and DELETE; corrections are reversal rows. Each reversal names the charge it undoes, and a UNIQUE constraint lets a charge be reversed only once.
  • One lock order everywhere. Writes for a student take FOR NO KEY UPDATE on the student row, then FOR SHARE on the lesson. Cancellations take FOR UPDATE on the lesson, so "is this lesson cancelled?" cannot change between the check and the write.
  • Why NO KEY UPDATE. A cancellation writing a reversal needs a KEY SHARE lock on the student via foreign-key checks. FOR UPDATE would block it and deadlock; FOR NO KEY UPDATE allows it.

Step through both versions — a mark and a cancellation racing on the same lesson, exactly as in the repository's concurrency test:

Interactive · lock order

Tx A · mark attendance
  1. 1.SELECT … FROM student WHERE id = $1 FOR UPDATE· granted
Tx B · cancel lesson
    student row locks: A · FOR UPDATE
    lesson row locks: none

    Step 1/5. Mark takes the student row first.

    Payments: a webhook that trusts nothing

    Rate limit → constant-time secret check → provider IP allowlist → re-fetch the payment from the provider's API and validate it at runtime → match owner, amount and currency against our own payment intent → credit idempotently with ON CONFLICT DO NOTHING on the provider's payment id. Ten identical deliveries credit once.

    Send a few requests through it — each scenario below is a case from the test suite:

    Interactive · send a webhook

    Pick a request above to send it through the handler.
    1. Rate limitPer source IP, counted in Postgres
    2. Shared secretConstant-time compare; mandatory in live mode
    3. Provider IP allowlistLive mode only
    4. Read payment id from bodyNothing else in the body is trusted
    5. Re-fetch from provider APIStatus, amount, currency, owner
    6. Match our payment intentSame owner, amount and currency
    7. Idempotent creditON CONFLICT DO NOTHING on the payment id

    Response will appear here.

    Auth: enumeration-safe login

    Unknown emails still cost one bcrypt compare, so response time does not reveal who has an account. Login limits run per (IP, email) and per email across IPs, checked and counted atomically under a per-email advisory lock.

    How it's tested

    • Deterministic interleavings. A test pauses one operation right after it takes its locks, starts a competing one and asserts it waits — one test per lock, plus the deadlock case.
    • Bursts. 20 simultaneous marks of one lesson, 10 identical webhook deliveries, 50 parallel login guesses: the ledger and the limits come out exact.
    • Randomized ledger invariants. Seeded runs of 200 random operations, five at a time in parallel, checking nine invariants after every batch.
    • Mutation check. A script removes each defence in turn — either lock, the cancelled-lesson guard, the one-reversal-per-charge constraint, the idempotency key, the dummy bcrypt compare and others — and the suite has to fail for all 15.

    A bug the randomized test caught

    The first run failed on "a cancelled lesson nets to zero for every student". A student was charged, the lesson was cancelled (charge reversed), then the attendance mark was cleared — reversing the charge a second time. The student was credited for a lesson they were never charged for.

    The fix: clearing and cancelling both compute the reversal from the lesson's current net, under the lesson's lock, so a clear after a cancellation finds nothing to reverse. Clearing also refuses a cancelled lesson outright, as a business rule. Both the plain sequence and the race are now tests.

    After publishing

    A reader suggested moving the guarantee from the code into the schema. Every reversal now carries the id of the charge it reverses, with a UNIQUE constraint on that column, plus a trigger that the reversal matches its charge: same student, same lesson, opposite amount. A test pauses a clear after its locks, reverses the same charge from another path, and the clear fails at insert instead of refunding twice.