If you build anything that touches money (invoicing, a marketplace, a POS, a SaaS billing page), you will eventually be asked "what's the balance?" and "why is it that number?". A single balance column can answer the first question. Only a ledger can answer the second.
Double-entry bookkeeping is the ledger accountants have used for centuries. It turns out to be a very good data model: append-only, self-checking and auditable. This article explains the rules in developer terms and sketches how to store them. The schema and code are illustrative examples, not a production design.
The one rule
Every transaction moves value from somewhere to somewhere. Double entry records both sides:
- Each journal entry has two or more lines.
- Each line hits one account with a debit or a credit.
- In every entry, total debits = total credits.
That's it. Because every entry balances, the whole ledger balances, and an entry that doesn't balance is rejected the moment it is created.
Debit and credit are not plus and minus
This is the part that confuses developers. Debit means "left column", credit means "right column". Whether a debit increases or decreases an account depends on the account's type:
| Account type | Increased by | Examples |
|---|---|---|
| Asset | Debit | Bank, cash, receivables, stock |
| Expense | Debit | Salaries, rent, cost of goods sold |
| Liability | Credit | Payables, tax owed, salaries payable |
| Equity | Credit | Owner's capital, retained earnings |
| Income | Credit | Sales, interest income |
A cash sale of 1,000: debit Bank 1,000 (asset up), credit Sales 1,000 (income up). Paying rent of 300: debit Rent 300 (expense up), credit Bank 300 (asset down). Balanced both times.
A minimal schema
Example in SQL (illustrative):
CREATE TABLE account ( id INTEGER PRIMARY KEY, code TEXT UNIQUE NOT NULL, -- e.g. '1100' name TEXT NOT NULL, -- e.g. 'Bank - Current' type TEXT NOT NULL CHECK (type IN ('asset','liability','equity','income','expense')) ); CREATE TABLE journal_entry ( id INTEGER PRIMARY KEY, entry_date DATE NOT NULL, -- the accounting period it belongs to description TEXT NOT NULL, source_type TEXT, -- 'invoice', 'bill', 'payroll_run', 'manual' source_id INTEGER, reverses_id INTEGER REFERENCES journal_entry(id), posted_at TIMESTAMP NOT NULL ); CREATE TABLE journal_line ( id INTEGER PRIMARY KEY, entry_id INTEGER NOT NULL REFERENCES journal_entry(id), account_id INTEGER NOT NULL REFERENCES account(id), debit BIGINT NOT NULL DEFAULT 0 CHECK (debit >= 0), credit BIGINT NOT NULL DEFAULT 0 CHECK (credit >= 0), CHECK ((debit = 0) <> (credit = 0)) -- exactly one side per line ); Design notes:
- Integers, not floats. Store amounts in the smallest unit (paisa, cents) as integers, or use a fixed-point decimal type. Floating point will eventually produce a ledger that is off by 0.0000001 and refuses to balance.
- Two columns, not a signed amount. A signed
amountworks too, but separatedebitandcreditcolumns map directly to how accountants read reports, and make the balance check obvious. - Link to the source document.
source_typeandsource_idanswer "why is this number?" without guesswork.
Enforce the balance
The rule "debits = credits" must hold per entry. Databases don't express cross-row constraints neatly, so most systems enforce it in the posting code, inside one transaction:
function post(entry, lines): assert len(lines) >= 2 assert sum(l.debit for l in lines) == sum(l.credit for l in lines) assert period_is_open(entry.entry_date) begin transaction insert entry insert all lines commit All lines are written, or none are. A half-posted entry is worse than no entry.
Balances are derived, not stored
An account's balance is a query, not a field you update:
SELECT a.code, a.name, SUM(l.debit) - SUM(l.credit) AS net_debit FROM journal_line l JOIN account a ON a.id = l.account_id JOIN journal_entry e ON e.id = l.entry_id WHERE e.entry_date <= :as_of GROUP BY a.code, a.name; For asset and expense accounts, a positive net_debit is the normal balance; for liability, equity and income accounts, flip the sign. Run this across all accounts and the debits and credits total the same: that's a trial balance, and it's a free integrity check for your whole system.
At scale you will cache balances (per account per period, say), but the cache must always be rebuildable from the lines. The lines are the truth.
Never update, never delete: reverse
A posted entry is history. If it's wrong, you post a reversal (the same lines with debit and credit swapped) and then the correct entry. Both stay visible. Auditors want exactly this, and so will you the first time someone asks why last quarter's numbers moved.
Pair this with closed periods: once a month is closed and reported, nothing may be posted into it. A correction to a closed month is posted in the current, open period instead.
Documents post entries; people rarely write them
In a real business app, users don't type debits and credits. They create documents, and each document type knows its posting:
| Document | Debit | Credit |
|---|---|---|
| Sales invoice (credit sale) | Receivables | Sales, Tax payable |
| Customer payment | Bank | Receivables |
| Supplier bill | Stock or Expense, Input tax | Payables |
| Payroll run | Salary expense | Salaries payable, Tax withheld payable, Social-security payable |
A useful trick is to post to roles ("receivables", "default sales", "salaries payable") rather than hard-coded account IDs, and let each company map roles to its own chart of accounts. The posting logic stays generic while every business keeps its own account structure.
Manual journal entries still exist for things with no document: accruals, prepayments, corrections between expense accounts.
A worked example: payroll
Payroll is a good test of the model because one run creates many obligations. Suppose (illustrative figures) gross salaries are 500,000, income tax withheld is 20,000, employee social-security contributions are 5,000, and a loan instalment of 10,000 is recovered:
Dr Salary expense 500,000 Cr Salaries payable 465,000 Cr Income tax withheld payable 20,000 Cr Social security payable 5,000 Cr Employee loans receivable 10,000 Debits 500,000, credits 500,000. When salaries are paid, a second entry debits Salaries payable and credits Bank. When tax is remitted, Tax withheld payable is debited and Bank credited. After everything is paid, each payable is back to zero, and any payable that isn't is a list of what's still owed. The ledger becomes a to-do list.
Note the date: the payroll entry belongs to the period worked, even if the bank payment happens next month.
How RBTERP applies this
In RBTERP (an offline-first ERP for small businesses), every invoice, bill, payment and stock movement posts to a double-entry general ledger as it is entered, through posting roles mapped to the company's chart of accounts. A manual journal must balance before it can be posted, a date in a closed month is refused, and the reversal of an entry that sits in a closed month is made as a contra entry dated today, so the closed month stays as reported. Payroll runs post the expense, net pay and each deduction to their own accounts, dated the last day of the period.
Trade-offs
- More rows. Every event writes at least two lines. Storage is cheap; reconstructing a lost history is not.
- Reporting needs aggregation. Plan indexes on
(account_id, entry_date)and period-level caches early. - Domain learning curve. Developers must learn debit/credit conventions. It takes an afternoon and pays back for years.
If you're modelling money, start with a ledger. You'll get balances, history and a built-in consistency check for the price of one extra table.
For a non-technical explanation of journals, debits and credits (useful to share with your product team), see the guide: https://rbterp.com/guides/journal-entries-explained?utm_source=devto