Airline booking: away/return directions, a double-entry ledger and change history
Airline case study, part 3: splitting a booking into directions and money lines, storing money properly, tickets and passengers, a double-entry ledger with a balance constraint in PostgreSQL, optimistic locking with a version column and a booking_history table, and other ways to keep history.
On this page
1. The problem
Version 1 crammed everything into one booking table with an amount. Refunding just the return flight was impossible; daily reconciliation was off by one dong because VAT was rounded two ways; an IPN marked a booking PAID, then the expiry job overwrote it with EXPIRED, cancelling a paid ticket.
2. Key idea
Split the booking into three levels: the header (who booked, status, the total fixed at checkout, version), booking_direction (one row per direction), booking_line (fare, fees, VAT). The header total is deliberate denormalization: the number sent to the gateway, watched by a reconciliation query.
Money goes through a double-entry ledger: every transaction has at least two entries (debits positive, credits negative) summing to 0, never updated or deleted; mistakes get a reversing transaction.
| Event | Entries |
|---|---|
| Customer pays 6,820,000 VND via the gateway | Debit GATEWAY_CLEARING / Credit CUSTOMER_PREPAID |
| Gateway pays out minus a 1.1% fee | Debit BANK 6,744,980, Debit GATEWAY_FEE 75,020 / Credit GATEWAY_CLEARING 6,820,000 |
| Refund of the return leg, 3,410,000 VND | Debit CUSTOMER_PREPAID / Credit GATEWAY_CLEARING |
2.1 What prevents lost updates?
| Approach | Use when | Don't use when |
|---|---|---|
Optimistic locking (version) |
bookings: a few parties occasionally edit at once | seat counters: hundreds of requests read the same version |
Conditional UPDATE (booked + q <= limit) |
counters, stock | you need to know who changed what |
| History table written in the same transaction | history for support and reconciliation | you only need "last modified by" |
3. In SQL
CREATE TABLE entry (
txn_id bigint NOT NULL REFERENCES ledger_transaction,
account_id int NOT NULL REFERENCES account,
amount bigint NOT NULL CHECK (amount <> 0) -- debit positive, credit negative, minor units
);
CREATE FUNCTION check_txn_balanced() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF (SELECT coalesce(sum(amount), 0) FROM entry WHERE txn_id = NEW.txn_id) <> 0 THEN
RAISE EXCEPTION 'ledger transaction % is not balanced', NEW.txn_id;
END IF;
RETURN NULL;
END $$;
CREATE CONSTRAINT TRIGGER entry_balanced AFTER INSERT ON entry
DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION check_txn_balanced();
-- a single +100 entry fails at COMMIT. Add REVOKE UPDATE, DELETE ON entry.A CHECK sees one row; a deferred trigger runs at COMMIT, once every entry is inserted. MySQL lacks it, so reconcile with GROUP BY txn_id HAVING sum(amount) <> 0. In JPA, @Version adds AND version = ? and increments it; conflicts throw ObjectOptimisticLockingFailureException.
VAT rounding, tickets and passenger data
- VAT: 10% on three lines of 333,333 VND is 99,999 when rounded per line and 100,000 on the total. Pick one rule in one place and store the rounded values in
booking_line. - Tickets repeat
flight_idon purpose, so a partial unique index(flight_id, seat_code) WHERE status <> 'VOID'stops one seat being sold twice when the seat-holding code has a bug. - Passengers are travelers, not accounts; ID and passport numbers are sensitive data (Vietnam's Decree 13/2023, GDPR): encrypt the columns with a KMS key, mask them in logs.
- A booking takes two transactions: TX1 at checkout (booking, seat hold, history v1); TX2 when the IPN confirms payment (version+1
PAID, seatsBOOKED, ledger). Ticket issuance and email go through an outbox.
4. Working with AI
Hand to AI: DDL from the ERD, sample data for refund cases, a header-versus-lines reconciliation query, version-conflict tests.
Check yourself in AI-written code:
- Money is a
bigintin minor units with acurrency, notfloat,doubleor unboundednumeric. - Every ledger posting has at least two entries summing to 0, and the DB enforces it.
-
entryhas no UPDATE or DELETE path; corrections are reversing transactions. - Every path that changes booking status (jobs and scripts included) bumps
versionand writes history. - Each gateway transaction is posted once (
external_refUNIQUE).
5. Exercises
Exercise 1: Review a booking expiry job
The AI wrote a job that runs every minute and says "safe because the booking has @Version". In the first week, 3 paying customers had tickets EXPIRED, and booking_history has no rows for any expiry. Find the bug and fix it.
@Modifying
@Query("update Booking b set b.status = 'EXPIRED' where b.status = 'PENDING' and b.payBy < :now")
int expireOverdue(@Param("now") Instant now);Solution 1
- A JPQL bulk UPDATE bypasses the persistence context: no
AND version = ?, no version bump, no history. The IPN reads version 1, the job setsEXPIREDleaving version at 1, and the IPN'sPAIDwrite succeeds on top, or the reverse depending on order. - Fix:
UPDATE booking SET status = 'EXPIRED', version = version + 1 WHERE status = 'PENDING' AND pay_by < now() RETURNING booking_id, version, then writebooking_historyfor each returned row in the same transaction. Or use a DB trigger that records history for every UPDATE. - An IPN arriving after
EXPIREDwith money already taken must not be ignored: post it to the ledger and queue a refund or manual handling.
Exercise 2: Choose a ledger schema
The AI proposes ledger(txn_id, debit_account, credit_account, amount), one row per transaction, "simpler than an entry table". Choose between that and the entry table, and explain.
Solution 2
Pick the entry table. A gateway payout minus fees has three legs (bank, fee, gateway); a two-column row can't express it, so you'd split it into two fake transactions and lose the link. With entry, any number of legs works and the "sums to 0" rule is enforced in the DB.
The two-column table only works when every transaction has exactly two legs and there are no fees, splits or partial refunds; real payment systems almost never look like that.
Summary
- A three-level booking: header, directions, money lines; the header total is reconciled.
- Money is a
bigintin minor units; VAT rounding in one place. - Ledger: ≥ 2 entries summing to 0, append-only; the DB enforces it at COMMIT.
- Optimistic locking plus history in the same transaction; bulk UPDATEs must bump the version themselves.
- Seat counters use conditional UPDATEs, not optimistic locking.
Further reading: Holding seats under concurrent booking.
Practice interview questions on this topic
- How do you design a double-entry ledger for a payment or booking system?
- How does optimistic locking with a version column work, and why not use a timestamp?
All Data Modeling & Scaling questions →All Transactions & Locking questions →
Comments
Community rules