Double-entry accounting database design: rules to enforce
Double-entry accounting database design for small business apps: refuse unbalanced vouchers, log every skipped posting, reverse and repost edits, cap refunds.
By Hamza Ghouri
Double-entry accounting database design looks simple on paper: every transaction is a voucher, every voucher has lines, and the debits equal the credits. The schema for that fits on a napkin. What the schema does not do is stop your own code from writing a voucher that breaks the rules. I learned that on a point of sale I built for a retail shop, which keeps its own ledger. This post covers the rules the application code has to enforce, each one tied to a bug I found or a decision I made, and where I'd add a database-level guard on top.
How do you design a database for double-entry accounting?
Use three core tables: accounts, vouchers (journal entries), and voucher lines that each debit or credit one account. Every voucher must balance, meaning its debits sum to its credits, and posted vouchers are never edited in place: a mistake is fixed by a reversing voucher and a new one. Balances and reports are derived from the lines. The hard part is the code around that schema, which must refuse anything that breaks those rules.
Square's engineering team describes the same model in Books, their immutable double-entry accounting database. Their journal entries must balance to zero, the entry tables are append-only, and a mistake is corrected by writing a new entry, so there is always a trace of what happened. A small shop's ledger has none of Square's scale problems, but the same two rules carry most of the weight.
Rule 1: refuse a voucher whose debits and credits differ
The save path for vouchers checked that a voucher had two lines. It never checked that its debits equalled its credits. So if a bug dropped one line of a three-line voucher, the save would go through with a lopsided voucher and corrupt every report built on the ledger.
It now refuses, and says so. The check is a few lines, and the detail that matters is doing the sum in integer minor units so floating point cannot produce a false mismatch:
type Line = { accountId: string; debit: number; credit: number }; // amounts in minor units
export function assertBalanced(lines: Line[]): void {
if (lines.length < 2) throw new Error("A voucher needs at least two lines");
const debits = lines.reduce((sum, l) => sum + l.debit, 0);
const credits = lines.reduce((sum, l) => sum + l.credit, 0);
if (debits !== credits) {
throw new Error(`Voucher does not balance: debits ${debits}, credits ${credits}`);
}
}
The application check gives a clear error at the point of the mistake. If you want the database to hold the line too, Postgres supports constraint triggers that can be deferred to the end of the transaction, described in the CREATE TRIGGER documentation. A deferred trigger lets you insert the lines one by one and still reject the commit if the voucher does not balance. My default is the application check first, then the trigger once the posting code has settled, plus a reconciliation query that lists any voucher whose lines do not sum to zero.
Rule 2: no posting gets skipped silently
The worst ledger bug I found in this app made no noise at all. Customers created after a certain migration never got a ledger account. Every credit sale to one of those customers failed to post, and the sale was silently dropped from the books. The till showed the sale. The ledger never heard of it.
Two changes fixed it. New customers now get their ledger account at creation, and a backfill migration created accounts for every customer who was missing one. Separately, a skipped posting used to be silent. It now logs which document went unposted, so the next gap of this kind shows up in the logs the first time it happens.
The general rule I took from this: anything that must exist before a posting can succeed should be created in the same transaction as the thing that needs it. And a document that fails to post should be loud, because a ledger with a missing entry still balances. Balanced books can still be incomplete books.
Rule 3: change the books by reversing and reposting
Sales change after the fact. They get voided, un-voided, or corrected. The sale edit path used to update the sale and leave the ledger untouched, so the books still showed the original amount.
Now, when a sale is voided, un-voided, or its amount changes, the code reverses the sale's voucher and posts a new one. The history stays readable: the original entry, its reversal, and the corrected entry are all there. That matches the append-only approach in Square's write-up. The same change also made the edit path check that the caller has access to the shop the sale belongs to before it changes anything, the same scoping I describe in multi-tenant SaaS architecture.
Rule 4: money going back out has limits
Refunds and payments are where a ledger meets real customers, and each needed explicit limits:
- A refund is tied to the sale it undoes. It is paid as store credit, never cash.
- No book can be refunded beyond what the sale sold, counting earlier refunds against the same sale.
- A credit refund without a customer is refused, because there is no account to hold the credit.
- Customer payments are capped at what is owed, so an overpayment cannot leave a negative balance nobody asked for.
- Store credit can pay for a sale. The invoice keeps its full value and the customer's balance settles part of it, so sales reports still show what was sold.
Books sent out on approval needed their own state. A sale-or-return is saved with an on-approval status, stays out of every report and posts nothing until the customer settles. If the customer returns everything, the document is voided, which is cleaner than leaving a zero-value invoice in the register.
The pattern behind all of these: decide what each document means to the ledger before writing the posting code. A document that has not created a financial fact yet should not post anything.
Invoice numbers and shared code paths
Two smaller fixes kept day-to-day use from breaking.
A sale whose invoice number had been taken since the screen opened used to fail with no way forward. Now the save takes the next free number and posts again. Uniqueness itself belongs in the database; I covered that pattern in fixing race condition duplicate rows with a unique index. The application's job is to recover from the conflict without bothering the user.
Stock adjustments, single and bulk, go through one shared code path, and the bulk version applies many adjustments in one transaction. One path means one set of rules, so a fix to the single case cannot miss the bulk case.
Where I'd start
If you are building or auditing a ledger inside an app:
- Add a balance check to the voucher save path, in integer minor units, and run a query for vouchers that already fail it.
- Find every place a posting can be skipped, and make each one log the document it skipped.
- Make sure every customer or supplier who can carry a balance gets a ledger account when they are created.
- Replace in-place edits of posted vouchers with reverse and repost.
- Write down the limits on refunds and payments and enforce each one in code.
The same point of sale also had to work through dropped connections, which I wrote up in offline-first point of sale with IndexedDB and Dexie. If you need a ledger built into a product, it is the kind of work I take on through my services.