Double-entry bookkeeping for engineers
A balance column is a number nobody can explain. Store every movement as debits and credits that sum to zero, derive the balance, and the books can check themselves
A customer of Owoleaf, a wallet company, funds their wallet with ₦10,000 by bank transfer. The money arrives in Owoleaf's account at its partner bank. Which pair of postings records it?
An engineer’s first model of a wallet is a table with a balance column. It is easy to write and easy to read, and it fails in four ways. A crash between “subtract from one wallet” and “add to the other” destroys money. Two requests that read the same balance both write back, and one update is lost. A bug writes the wrong number and leaves no trace of the right one. And when the total is wrong, there is nothing to search: every row is a result, and no row is a reason. This chapter replaces the column with a record of movements, and treats the balance as something you compute.
A ledger is movements, not balances
A ledger has three kinds of record, and the lab’s database has all three.
- An account is a named place where value is counted: a customer’s wallet, the company’s bank account at its partner bank, the fees it has earned. Owoleaf has 2,005 accounts: 2,000 wallets and five of its own.
- A transaction is one business event: a funding, a payout, a transfer between wallets. It has a kind, a status, an amount and a reference, and the lab keeps failed attempts too. A failed attempt moved no money, so it has no entries.
- An entry is one leg of one transaction: this account, this direction, this amount in kobo. Every posted transaction has two or more entries.
The rule that makes it a double-entry ledger is short. For every transaction, the debits equal the credits. Money is never created or destroyed by a posting. It moves from somewhere to somewhere, and the entries say where. The lab’s entries table stores each as a row with direction of debit or credit and a positive integer amount_kobo. The positive amount matters: the sign lives in the direction, never in the number, so there is no way to write “minus ₦500 debit” and confuse the next reader.
Kleppmann, writing for computer scientists, describes accounting as a graph: accounts are the nodes, and every transaction is a set of edges that carry value between them. That picture helps. A balance is not a property of a node you edit. It is what the edges into and out of the node add up to.
Debit and credit are directions, not good and bad
The words cause more trouble than the idea. A debit is an entry on the left side of an account, and a credit is an entry on the right. Neither is good or bad, and neither means “money out”. What each does to an account’s balance depends on the account’s type, and there are five types:
| Type | What it is | Example in the lab | A debit… | A credit… |
|---|---|---|---|---|
| Asset | Something the company holds or is owed | settlement_bank, card_clearing |
increases it | decreases it |
| Liability | Something the company owes | each wallet:<id> |
decreases it | increases it |
| Equity | What the owners put in or left in | share_capital |
decreases it | increases it |
| Income | What the company earned | fee_revenue |
decreases it | increases it |
| Expense | What the company spent | processing_expense |
increases it | decreases it |
Read the table by columns. Assets and expenses grow on the debit side. Liabilities, equity and income grow on the credit side. That one fact gives you the whole sign convention.
The wallet row surprises engineers, so check it twice. When a customer holds ₦51,904.87 in a wallet, that money is not Owoleaf’s. The company is holding it for the customer and must hand it back on request. In the books it is a liability: a credit balance that Owoleaf owes. If you model wallets as assets, every inward payment looks like a gain and the company appears to be richer than it is. Which side of the line customer money sits on, and what the company must do to protect it, is a regulatory question that the wallets chapter in module 2 takes up. The books only need the type to be right.
The same five types give the accounting equation, in the expanded form the lab checks:
assets + expenses = liabilities + equity + income
Assets and expenses carry debit balances, and the other three types carry credit balances. Every posting adds as much to debits as to credits, so the total of the debit balances always equals the total of the credit balances, and the equation holds after every posting. If it ever fails, a posting was half-written. That is the property Kehinde’s tracker lacks, and the next sections show it on real rows.
Postings read from the lab’s data
Wallet 36 belongs to customer C0000036, an individual in Lagos on KYC tier 2. Owoleaf, the lab’s fictional company, posted its history in the lab’s entries table. Here are four of its transactions, with every leg:
| Transaction | What happened | Legs |
|---|---|---|
#49972 funding_transfer |
A bank transfer in of ₦15,539.00 | debit settlement_bank 1,553,900; credit wallet:36 1,553,900 |
#47123 funding_card |
A card funding of ₦4,617.00 with a fee of ₦69.26 | debit card_clearing 461,700; credit wallet:36 454,774; credit fee_revenue 6,926 |
#53154 payout_nip |
A payout to a bank of ₦26,607.89 with a fee of ₦25.00 | debit wallet:36 2,663,289; credit settlement_bank 2,660,789; credit fee_revenue 2,500 |
#50428 p2p_transfer |
Another customer sends ₦4,686.00 to wallet 36 | debit wallet:1054 468,600; credit wallet:36 468,600 |
The amounts are in kobo, as the table stores them. Work each one by hand, because the point is that you can.
The funding is the one from the Predict. Cash arrives, so the asset settlement_bank is debited. The customer is owed it, so the liability wallet:36 is credited. One debit, one credit, 1,553,900 each.
The card funding has three legs, and that is normal. The customer paid ₦4,617.00 by card. Owoleaf has not received that money yet: the card processor owes it, and the processor pays it into the bank the next morning. Until then it is an asset called card_clearing, debited for the full 461,700. The customer is credited only 454,774, because Owoleaf charges a fee of 1.5% (6,925.50 kobo, which the generator rounds to 6,926). The fee is Owoleaf’s income, so fee_revenue is credited 6,926. The check: 454,774 + 6,926 = 461,700. One debit equals two credits.
The payout runs the other way. The wallet loses the amount sent and the fee: 2,660,789 + 2,500 = 2,663,289, a debit to the liability. The bank account loses 2,660,789 (an asset credited), and the fee becomes income. Again the debit equals the sum of the credits.
The transfer between wallets moves a liability from one customer to another. The settlement bank account is untouched, because no money entered or left Owoleaf. Both wallets are liabilities, one debited and one credited.
Two more shapes complete the set. When the card processor settles, it pays the bank the gross amount less its own fee, and the lab shows this on transaction #16: it debits settlement_bank 392,436 and processing_expense 3,964, and credits card_clearing 396,400, clearing what was owed. The fee is 1% of 396,400. And when a bank returns a payout, the books do not edit the payout. They post a new transaction. Payout #494 (₦647.26 plus a ₦10.00 fee, for customer 273) was marked reversed, and a separate payout_reversal, #632, debits settlement_bank 64,726, debits fee_revenue 1,000 and credits wallet:273 65,726, reversing each leg of the first. The original rows are still there. The history says what happened, in order.
Balances are derived
Look at what the lab’s database does not have: a balance column. A wallet’s balance is the sum of its entries, credits minus debits, because a wallet is a liability. For wallet 36 the twelve entries add up to 5,190,487 kobo (₦51,904.87). The lab step has you print them one at a time with the running total, and then recompute the same figure from the transactions table by a separate route. The two agree for all 2,000 wallets.
This gives you three things a balance column cannot.
- A reason for every number. When a customer asks why they have ₦51,904.87, you list twelve rows.
- A balance at any time. Sum the entries up to a timestamp and you have the balance then. An update in place has overwritten the past.
- A test. The same balance computed by two independent routes is a check on both.
The price is that summing every entry on every read does not scale. Real systems keep a cached balance and update it in the same database transaction as the entries, or take periodic snapshots and sum only what came after. The ledger-at-scale chapter in module 3 compares the options. The rule that does not change is that the entries are the truth and the balance is a copy. If they disagree, you trust the entries and repair the copy.
Entries are also append-only. When Kehinde finds a wrong posting, he does not update or delete it. Editing destroys the evidence and makes the earlier month’s report impossible to reproduce. He posts a correction that reverses the wrong transaction, and a new one if needed. Fowler’s accounting patterns call these a reversal adjustment (keep the wrong entries and post opposite ones) and a replacement adjustment (delete them and post new ones). Replacing is simpler and loses history; reversing keeps it. In a ledger that people will audit, keep the history.
Posting is one atomic act
A posting function takes the legs of a transaction and either saves all of them or none. Here is the smallest useful version, in Python and SQLite, standard library only. It refuses a transaction whose debits and credits differ, and it writes the legs inside one database transaction so a crash between legs cannot leave half of them:
import sqlite3
db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE entries (
id INTEGER PRIMARY KEY, transaction_id INTEGER NOT NULL, account TEXT NOT NULL,
direction TEXT NOT NULL CHECK (direction IN ('debit', 'credit')),
amount_kobo INTEGER NOT NULL CHECK (amount_kobo > 0));
""")
def post(transaction_id, legs):
"""legs: list of (account, 'debit' | 'credit', integer kobo). All or nothing."""
debits = sum(k for _, d, k in legs if d == "debit")
credits = sum(k for _, d, k in legs if d == "credit")
if debits != credits:
raise ValueError(f"unbalanced: debits {debits} != credits {credits}")
with db: # one database transaction: every leg is saved, or none is
db.executemany(
"INSERT INTO entries (transaction_id, account, direction, amount_kobo) VALUES (?, ?, ?, ?)",
[(transaction_id, a, d, k) for a, d, k in legs])
# A NIP payout of ₦26,607.89 with a ₦25 fee, as transaction 53154 posted it.
post(1, [("wallet:36", "debit", 2_663_289),
("settlement_bank", "credit", 2_660_789),
("fee_revenue", "credit", 2_500)])
try:
post(2, [("wallet:36", "debit", 2_663_289), ("settlement_bank", "credit", 2_660_789)])
except ValueError as e:
print("refused:", e)
print("entries saved:", db.execute("SELECT COUNT(*) FROM entries").fetchone()[0])
Run it and you get:
refused: unbalanced: debits 2663289 != credits 2660789
entries saved: 3
The second call forgot the fee leg, which is the commonest way a real posting goes wrong: someone adds a new fee and updates the debit but not the credit side. The function stops it at the door. The three entries from the first call are the only ones saved. Notice that every amount is an integer number of kobo. A float for money would make “debits equal credits” a comparison of numbers that are almost equal, and the lessons on floating-point money and minor units show why that fails. The project at the end of this module has you build the full version, with accounts, balance checks and a replay of the lab’s data.
What the ledger proves, and what it cannot
A balanced ledger proves a lot, and much less than people hope. check.py in the lab tests six properties. Three of them are properties of double entry itself:
- Every posted transaction balances.
- Failed transactions have no entries, and posted ones have some.
- The trial balance holds: assets + expenses = liabilities + equity + income. A trial balance is the list of every account’s balance, summed by type, to see whether the books balance.
The others are about the business: no wallet ever goes below zero when you replay entries in time order, every payout return points at a payout marked reversed, and the settlement bank account in the ledger differs from the partner bank’s statement by exactly what the planted breaks explain.
Now the limit. The first three checks look only inside the ledger. A posting that sends ₦15,539.00 to the wrong wallet balances. A posting made twice balances, twice. A fee posted at the wrong rate balances. Each is a balanced error, and no amount of checking the ledger against itself finds one. What finds it is a record from outside: the bank’s statement, the card processor’s settlement report, the customer’s complaint. The sixth check is the first example of that, and the lab’s break step shows it catching a balanced duplicate that checks 1 to 5 let through. Matching the ledger against outside records is reconciliation, and module 2 has a full chapter on it. The lesson on reconciliation is the short version.
Watching the failure and the fix
The simulation below runs the failure that the balance column cannot survive. Three accounts, two transfers, one lost response and one crash, played against three designs: balances updated in place, journal entries in a transaction with no key, and the design this chapter describes, a journal with an idempotency key.
-- one autocommit statement per leg, no key
UPDATE accounts SET balance = balance - 30 WHERE id = 'alice';
-- crash here: $30 is gone
UPDATE accounts SET balance = balance + 30 WHERE id = 'bob';
-- response lost here: the client retries and both run againBEGIN;
INSERT INTO idempotency_keys (key, result) VALUES ('k-7f3a', 'ok')
ON CONFLICT (key) DO NOTHING RETURNING key;
-- no row back: a retry. ROLLBACK and return the stored result instead
SELECT balance FROM accounts WHERE id = 'alice' FOR UPDATE;
-- funds check: locking the account row serializes transfers from alice
-- (row locks on entries would not stop a concurrent INSERT)
INSERT INTO entries (txn, account, amount) VALUES
('k-7f3a', 'alice', -30),
('k-7f3a', 'bob', +30); -- the legs of one transfer always sum to 0
UPDATE accounts SET balance = balance - 30 WHERE id = 'alice';
UPDATE accounts SET balance = balance + 30 WHERE id = 'bob';
-- cached balance = SUM(amount), kept in the same txn
COMMIT; -- both legs and the key, or none of them The simulation counts in dollars, while this course counts in naira and integer kobo, so read its amounts as plain units and not as ₦.
Run the in-place design first and watch the sum of all balances. It turns red between the two statements of every transfer, because for that instant one account has lost money and the other has not gained it yet. Then the lost response makes the client retry, and the first transfer happens twice. Now run the journal design. Both legs go in one database transaction, so the crash leaves all or nothing, and the retry meets a stored key and returns the first answer. The sum stays constant, and each transfer is applied once.
Two lessons come out of it. Double entry makes the invariant checkable: the sum is a number you can compute at any moment. It does not, by itself, make a retry safe. A transaction makes one attempt all-or-nothing, and nothing in it knows that a second attempt is the same transfer. The idempotency chapter in module 2 teaches the key. If you want to push on the failure yourself, this exercise gives you the broken ledger:
Balances updated in place, one statement per leg, a client that retries on timeout. Inject one fault so that money is created or destroyed, or a transfer is applied twice.
GOAL: the sum of balances changes, or a transfer is applied twice
Where it goes wrong in practice
Six mistakes recur, and each one has shown up in the first year of someone’s ledger.
- Storing signed amounts. A column of
+500and-500with no direction looks simpler. Then “debit” means different things in different reports. Store a positive amount and a direction, as the lab does. - Treating wallets as assets. The books show the company as richer than it is by the whole of its customers’ money.
- Editing instead of reversing. The month-end report you gave the auditor cannot be reproduced after you edit March.
- One leg per statement. Two autocommit statements for a transfer give a crash window between them, and a reader who sees one leg without the other.
- A balance column with no entries behind it. The number is wrong sooner or later, and then nothing explains it.
- Believing the trial balance. It catches half-written postings. It cannot catch a balanced one that is wrong.
None of these needs clever code to avoid. They need the structure decided before the first posting is written, which is why this chapter comes before the project.
You work in labs/finance. If you have not generated the data, run python3 generate.py; it takes about 3 seconds. Every step is Python using the standard sqlite3 module against data/finance.sqlite, so you do not need the sqlite3 command. Break steps use a copy of the database and never touch the original.
1. Run the trial balance. Sum every account’s debits and credits, grouped by account type, and test the accounting equation.
python3 - <<'PY'
import sqlite3
db = sqlite3.connect("data/finance.sqlite")
def naira(kobo):
sign = "-" if kobo < 0 else ""
kobo = abs(kobo)
return f"{sign}₦{kobo // 100:,}.{kobo % 100:02d}"
rows = db.execute("""
SELECT a.type,
COUNT(DISTINCT a.id),
COALESCE(SUM(CASE e.direction WHEN 'debit' THEN e.amount_kobo END), 0),
COALESCE(SUM(CASE e.direction WHEN 'credit' THEN e.amount_kobo END), 0)
FROM accounts a LEFT JOIN entries e ON e.account_id = a.id
GROUP BY a.type ORDER BY a.type""").fetchall()
print(f"{'type':<10} {'accounts':>8} {'debits (kobo)':>18} {'credits (kobo)':>18} {'balance':>20}")
totals = {}
for typ, n, dr, cr in rows:
# Assets and expenses have a debit balance; the other three a credit balance.
balance = dr - cr if typ in ("asset", "expense") else cr - dr
totals[typ] = balance
print(f"{typ:<10} {n:>8,} {dr:>18,} {cr:>18,} {balance:>20,}")
all_dr = sum(r[2] for r in rows)
all_cr = sum(r[3] for r in rows)
print(f"{'all':<10} {'':>8} {all_dr:>18,} {all_cr:>18,}")
left = totals["asset"] + totals["expense"]
right = totals["liability"] + totals["equity"] + totals["income"]
print()
print(f"assets + expenses = {left:>20,} kobo ({naira(left)})")
print(f"liabilities + equity + income = {right:>20,} kobo ({naira(right)})")
print(f"difference = {left - right:>20,} kobo")
PYtype accounts debits (kobo) credits (kobo) balance
asset 2 108,474,556,895 91,119,502,006 17,355,054,889
equity 1 0 5,000,000,000 5,000,000,000
expense 1 110,590,267 0 110,590,267
income 1 237,500 222,019,821 221,782,321
liability 2,000 88,553,180,302 100,797,043,137 12,243,862,835
all 197,138,564,964 197,138,564,964
assets + expenses = 17,465,645,156 kobo (₦174,656,451.56)
liabilities + equity + income = 17,465,645,156 kobo (₦174,656,451.56)
difference = 0 koboTotal debits equal total credits to the kobo: 197,138,564,964 on each side, across about 191,000 entries. The 2,000 wallets are the liability, ₦122,438,628.35 owed to customers. The share capital is ₦50,000,000.00. Add the balances yourself: 17,355,054,889 + 110,590,267 = 17,465,645,156, and 12,243,862,835 + 5,000,000,000 + 221,782,321 = 17,465,645,156.
2. Recompute one wallet’s balance two ways. The first way sums the wallet’s entries. The second ignores entries and rebuilds the balance from transactions, using what each kind of transaction means. Then it does both for every wallet. The last step takes about ten seconds.
python3 - <<'PY'
import sqlite3
db = sqlite3.connect("data/finance.sqlite")
def naira(kobo):
return f"₦{kobo // 100:,}.{kobo % 100:02d}"
# 1. One wallet, entry by entry. A wallet is a liability: credits add, debits subtract.
print("wallet:36, entry by entry")
running = 0
for tid, kind, d, amount, at in db.execute("""
SELECT e.transaction_id, t.kind, e.direction, e.amount_kobo, e.posted_at
FROM entries e
JOIN accounts a ON a.id = e.account_id
JOIN transactions t ON t.id = e.transaction_id
WHERE a.code = 'wallet:36' ORDER BY e.posted_at, e.id"""):
running += amount if d == "credit" else -amount
print(f" {at[:16]} #{tid:<6} {kind:<17} {d:<6} {amount:>10,} balance {running:>10,}")
print(f"balance from entries: {running:,} kobo = {naira(running)}")
# 2. The same balance from the transactions table, using what each kind means.
def from_transactions(cid):
total = 0
for kind, status, cust, other, amount, fee in db.execute("""
SELECT kind, status, customer_id, counterparty_customer_id, amount_kobo, fee_kobo
FROM transactions WHERE (customer_id = ? OR counterparty_customer_id = ?)
AND status <> 'failed'""", (cid, cid)):
if kind == "funding_transfer":
total += amount
elif kind == "funding_card":
total += amount - fee
elif kind == "p2p_transfer":
total += amount if other == cid else -amount
elif kind == "payout_nip":
total -= amount + fee
elif kind == "payout_reversal":
total += amount + fee
return total
print(f"balance from transactions: {from_transactions(36):,} kobo")
# 3. Every wallet, both ways.
by_entries = dict(db.execute("""
SELECT a.customer_id,
SUM(CASE e.direction WHEN 'credit' THEN e.amount_kobo ELSE -e.amount_kobo END)
FROM accounts a JOIN entries e ON e.account_id = a.id
WHERE a.type = 'liability' GROUP BY a.customer_id"""))
wallets = db.execute("SELECT COUNT(*) FROM accounts WHERE type = 'liability'").fetchone()[0]
differ = sum(1 for cid in range(1, wallets + 1) if by_entries.get(cid, 0) != from_transactions(cid))
print(f"wallets checked: {wallets:,}, wallets with no entries: {wallets - len(by_entries)}, differences: {differ}")
print(f"all wallets together: {sum(by_entries.values()):,} kobo = {naira(sum(by_entries.values()))}")
PYwallet:36, entry by entry
2026-04-10T07:47 #20268 p2p_transfer credit 1,732,900 balance 1,732,900
2026-04-22T12:07 #26915 p2p_transfer debit 918,700 balance 814,200
2026-04-22T13:49 #26984 p2p_transfer credit 728,800 balance 1,543,000
2026-05-05T15:14 #35210 p2p_transfer credit 562,800 balance 2,105,800
2026-05-21T16:33 #47123 funding_card credit 454,774 balance 2,560,574
2026-05-25T06:08 #49972 funding_transfer credit 1,553,900 balance 4,114,474
2026-05-25T15:58 #50428 p2p_transfer credit 468,600 balance 4,583,074
2026-05-28T20:03 #53154 payout_nip debit 2,663,289 balance 1,919,785
2026-06-02T06:34 #56866 p2p_transfer credit 310,200 balance 2,229,985
2026-06-08T15:06 #62723 funding_transfer credit 1,300,400 balance 3,530,385
2026-06-18T16:45 #72553 p2p_transfer credit 744,402 balance 4,274,787
2026-06-28T19:25 #82614 p2p_transfer credit 915,700 balance 5,190,487
balance from entries: 5,190,487 kobo = ₦51,904.87
balance from transactions: 5,190,487 kobo
wallets checked: 2,000, wallets with no entries: 4, differences: 0
all wallets together: 12,243,862,835 kobo = ₦122,438,628.35Twelve entries make ₦51,904.87, and the transactions table gives the same figure by a different route. The four postings from the chapter’s table are in the list: #47123, #49972, #53154 and #50428. The balance never goes below zero (its lowest point is 814,200 kobo, after the debit in #26915). All 2,000 wallets agree both ways, and the wallet total, 12,243,862,835 kobo, is the liability figure from step 1. Four wallets have no entries: they were opened and never used.
3. Break the books with one unbalanced entry. Copy the database next to the answer key (so check 6 can run), add one debit of 100 kobo (₦1.00) to the payout #53154, and run check.py on the copy.
cp data/finance.sqlite data/copy.sqlite
python3 - <<'PY'
import sqlite3
db = sqlite3.connect("data/copy.sqlite")
wallet = db.execute("SELECT id FROM accounts WHERE code = 'wallet:36'").fetchone()[0]
db.execute("""INSERT INTO entries (transaction_id, account_id, direction, amount_kobo, posted_at)
VALUES (53154, ?, 'debit', 100, '2026-05-28T20:03:39+01:00')""", (wallet,))
db.commit()
print("inserted entry", db.execute("SELECT MAX(id) FROM entries").fetchone()[0])
PY
python3 check.py --db data/copy.sqliteinserted entry 191104
accounts by type (debit-positive kobo): {'asset': 17355054889, 'equity': -5000000000, 'expense': 110590267, 'income': -221782321, 'liability': -12243862735}
settlement_bank in ledger 17,189,646,589 kobo; on the statement 17,192,741,324 kobo
FAIL
1. 1 transactions do not balance, e.g. [(53154,)]
3. trial balance is off by 100 kobo: {'asset': 17355054889, 'equity': -5000000000, 'expense': 110590267, 'income': -221782321, 'liability': -12243862735}check.py exits with status 1. Check 1 names the transaction, 53154, and check 3 says the whole trial balance is off by exactly 100 kobo, the amount you added. The liability balance moved from -12,243,862,835 to -12,243,862,735: the wallet was debited an extra ₦1.00 with nothing credited against it. Checks 2, 4, 5 and 6 still pass, because the wallet stays positive and the bank account is untouched. If you ran loans.py earlier, check.py also prints a loan-book line.
4. Repair it with a correction, not a delete. The chapter’s rule is to post a correction and never to edit or delete. Your stray entry is half a posting: a debit with no credit. A reversing transaction is a new, balanced posting, and it cannot cancel a one-legged entry by itself, because any balanced posting leaves #53154 still unbalanced. So you repair in two appended steps. First add the leg the entry was missing, a ₦1.00 credit to fee_revenue, to the same transaction. That makes it a complete but wrong posting: the wallet was charged an extra ₦1.00 fee. Then reverse that fee in a new transaction that debits fee_revenue and credits the wallet, the same shape as payout reversal #632. The new transaction has kind adjustment and points back at #53154 through related_transaction_id. No row is edited or deleted. It works on the copy from step 3, then runs the check and removes the copy.
python3 - <<'PY'
import sqlite3
db = sqlite3.connect("data/copy.sqlite")
acct = lambda code: db.execute("SELECT id FROM accounts WHERE code = ?", (code,)).fetchone()[0]
wallet, fees = acct("wallet:36"), acct("fee_revenue")
# 1. The stray debit is half a posting. Append the leg it was missing to the same transaction.
# Nothing is edited or deleted, and #53154 balances again.
db.execute("""INSERT INTO entries (transaction_id, account_id, direction, amount_kobo, posted_at)
VALUES (53154, ?, 'credit', 100, '2026-05-28T20:03:39+01:00')""", (fees,))
# 2. Reverse that wrongly posted ₦1.00 as a new, balanced transaction: debit fee_revenue, credit the wallet.
new = db.execute("SELECT MAX(id) + 1 FROM transactions").fetchone()[0]
db.execute("""INSERT INTO transactions SELECT ?, 'adjustment', 'succeeded', NULL, customer_id, NULL, 100, 0, 'internal',
external_ref, NULL, id, '2026-05-29T09:00:00+01:00'
FROM transactions WHERE id = 53154""", (new,))
db.executemany("""INSERT INTO entries (transaction_id, account_id, direction, amount_kobo, posted_at)
VALUES (?, ?, ?, 100, '2026-05-29T09:00:00+01:00')""",
[(new, fees, "debit"), (new, wallet, "credit")])
db.commit()
print("correction is transaction", new)
for e_id, tid, who, d, k in db.execute("""SELECT e.id, e.transaction_id, a.code, e.direction, e.amount_kobo
FROM entries e JOIN accounts a ON a.id = e.account_id WHERE e.id > 191103 ORDER BY e.id"""):
print(f" entry {e_id}: #{tid} {d:<6} {who:<12} {k}")
balance = db.execute("""SELECT SUM(CASE direction WHEN 'credit' THEN amount_kobo ELSE -amount_kobo END)
FROM entries WHERE account_id = ?""", (wallet,)).fetchone()[0]
print("wallet:36 balance", f"{balance:,}", "kobo")
PY
python3 check.py --db data/copy.sqlite
rm data/copy.sqlitecorrection is transaction 83888
entry 191104: #53154 debit wallet:36 100
entry 191105: #53154 credit fee_revenue 100
entry 191106: #83888 debit fee_revenue 100
entry 191107: #83888 credit wallet:36 100
wallet:36 balance 5,190,487 kobo
accounts by type (debit-positive kobo): {'asset': 17355054889, 'equity': -5000000000, 'expense': 110590267, 'income': -221782321, 'liability': -12243862835}
settlement_bank in ledger 17,189,646,589 kobo; on the statement 17,192,741,324 kobo
OK: all invariants holdEvery row from step 3 is still there, and the history shows the mistake and its fix: the stray debit (entry 191104), the leg that completes it (191105), and a balanced reversal, transaction 83888 (191106 and 191107). The two ₦1.00 legs on the wallet cancel, so wallet 36 is back to 5,190,487 kobo and the liability is back to -12,243,862,835, the figure before you broke anything. Income nets to no change too, because it was credited and then debited 100 kobo. The order of repair is the lesson: a correction reverses a posting that was complete, and a half-written one has to be completed first. Better still, a posting function like the chapter’s would never have accepted it.
Break it in a way the balance checks cannot see. A retry posts the funding #49972 a second time: a new transaction with the same reference and the same two legs. Every new debit has a matching credit, so the ledger balances.
cp data/finance.sqlite data/copy2.sqlite
python3 - <<'PY'
import sqlite3
db = sqlite3.connect("data/copy2.sqlite")
new = db.execute("SELECT MAX(id) + 1 FROM transactions").fetchone()[0]
db.execute("""INSERT INTO transactions SELECT ?, kind, status, failure_reason, customer_id, counterparty_customer_id,
amount_kobo, fee_kobo, rail, external_ref, counterparty_bank, related_transaction_id, created_at
FROM transactions WHERE id = 49972""", (new,))
db.execute("""INSERT INTO entries (transaction_id, account_id, direction, amount_kobo, posted_at)
SELECT ?, account_id, direction, amount_kobo, posted_at FROM entries WHERE transaction_id = 49972""", (new,))
db.commit()
print("duplicate is transaction", new)
PY
python3 check.py --db data/copy2.sqlite
rm data/copy2.sqliteYou get duplicate is transaction 83888 and then FAIL with one line only:
6. bank minus ledger is 1540835 kobo; the planted breaks explain 3094735Checks 1 to 5 pass: the duplicate balances, the trial balance holds and no wallet goes negative (wallet 36 only gained money). Only check 6 fails, because the ledger now claims ₦15,539.00 (1,553,900 kobo) of cash that the partner bank’s statement does not show. The gap between bank and ledger was 3,094,735 kobo and the planted breaks explain exactly that; now it is 1,540,835, and 3,094,735 − 1,553,900 = 1,540,835. Wallet 36 now holds ₦51,904.87 + ₦15,539.00 = ₦67,443.87 of money that never arrived. Ask which of the two records you would believe, and who would have noticed if the statement had not been there. That is why the books are checked against an outside record.
Template
# Posting specification: <event name>
Written by <engineer> · Reviewed and signed by <finance controller> · Date <date>
## The event
<One sentence: what happens in the product, and what triggers it.>
## Accounts touched
| Account | Type | Why it is touched |
|---|---|---|
## Postings
| Posting | Debit (account, kobo) | Credit (account, kobo) | Totals match? |
|---|---|---|---|
| <event> | | | |
| <reversal of the event> | | | |
## Invariants
- <A statement that must be true after every posting, and the query that checks it>
## Corrections
<How a wrong posting is fixed by appending new ones. Which transaction kind. What points back at the original.>
## Out of scope
<What this spec does not decide.>
## Could be wrong if
<One way this spec fails, and the check that would show it.> WORKED EXAMPLE
Posting specification: fee refund on a card funding. Written by an Owoleaf engineer, signed by Owoleaf’s finance controller. At a real company the engineer who builds the event writes the spec and the finance controller signs it. The figures come from the lab’s Owoleaf books, which you can practise on.
The event. Owoleaf refunds the ₦69.26 fee on card funding #47123 to wallet 36.
Accounts. fee_revenue (income): where the fee was earned. wallet:36 (liability): money Owoleaf owes the customer.
Postings. The refund debits fee_revenue 6,926 and credits wallet:36 6,926. Debits 6,926, credits 6,926. Its reversal, if the refund was sent by mistake, debits wallet:36 6,926 and credits fee_revenue 6,926.
Invariants. The trial balance difference stays 0 kobo, as step 1 of the lab printed. Wallet 36 never goes below zero: its lowest point is 814,200 kobo, and the refund only raises it. A refund cannot exceed the fee charged, 6,926 kobo.
Corrections. Nothing is edited. A wrong refund is cancelled by the reversal above, a new transaction of kind adjustment pointing at the original through related_transaction_id, as transaction 83888 did in step 4.
Out of scope. Who is eligible, and whether a fee refund is allowed at all.
Could be wrong if the refund is posted twice. It would balance, so only the card processor’s report would show it.
Now you
A month later, Owoleaf wants to pay customers cashback on card fundings. For this exercise assume the product team asks for 1% of the amount funded, paid into the customer’s wallet, and that it is a marketing cost and not a reduction of fees. Write the posting specification for one cashback event.
Use the lab: card funding #47123 was ₦4,617.00 (461,700 kobo), and wallet 36 held 5,190,487 kobo (₦51,904.87) in step 2. You need an account for the cost, and its type is your decision to justify. Write the reversal for a cashback paid on a funding that is later reversed, and show how a cashback posted to the wrong wallet is corrected. Use step 3 and step 4 of the lab as your pattern. State the 1% as an assumption, not as a rule.
Your reader is the finance controller, who signs it, and the decision it supports is whether the engineer may build the posting.
Self-check
Crustwell's distributor tracker has one balance column per distributor. Kehinde and Rakiya find that the total is ₦1,850,000 off the bank, and two services write to the table. Kehinde has two weeks before the next month end. What does he do first?
- POST Accounting for Developers, Part I: The Fundamentals Modern Treasury, 2022
A three-part introduction to double entry written for software engineers, from a payments-operations vendor. Read Part I for debits, credits and account types. Treat any product mentions as the vendor's own.
- POST Accounting for Developers, Part II Modern Treasury
Builds a ledger for a Venmo-style app step by step: the chart of accounts, then the postings. Read it for a second worked example of wallets as liabilities. Skip the product sections.
- POST Accounting for Developers, Part III Modern Treasury
Applies the same model to a lending marketplace, where entries have to carry interest and fees over time. Read it after the lending chapters if you take that course.
- POST Accounting for Computer Scientists Martin Kleppmann, 2011
The graph view of accounting: accounts as nodes, transactions as edges. Read all of it, it is short.
- DOC Patterns for Accounting Martin Fowler
Fowler's narrative on accounts, entries and transactions as software objects, with reversal and replacement adjustments for fixing errors. Read the narrative and the adjustment pages; the rest is optional.
- DOC Debit / Credit (TigerBeetle docs) TigerBeetle
A short explanation of debits and credits from a database built only for ledgers. Read it to see the same convention with the two directions written as columns. It is one vendor's own documentation.
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.