PRINCIPALCHAPTER 40

Ledger design: TigerBeetle, Square's Books and the research

A ledger database fixes the rules you would otherwise write yourself: ids chosen by the client, balances that cannot go below zero, holds that expire. Build them over SQLite, replay 79,827 transactions and match every balance

60 MINPAYMENTSUPDATED 2026-11-14
PREDICT

You replay Owoleaf's 79,827 posted transactions as transfers. Each transfer carries an id that you derived from the transaction id, and every one is accepted. You then send the whole file a second time, with the same ids. What does the ledger do?

Two payments companies and one database vendor have written down how they keep a ledger. They differ about the machinery and agree about the rules. This chapter takes the rules. It assumes you can post a transaction (double entry for engineers), that you know why a retry needs a key (idempotency and moving money exactly once), and that you have seen what a hot account costs (a ledger at scale). It does not re-teach them. It asks a different question: which rules do you want the ledger to enforce, so that no service above it has to remember them?

Three published designs and two older ideas

Source What it is The part to take
Square, “Books” (2019) An engineering post on its in-house ledger service Balances change only through accounting transactions
Stripe, “Ledger” An engineering post on its system of record for money movement A ledger is measured: how much of the money movement can it explain?
TigerBeetle An open-source database whose only records are accounts and transfers The rules live in the database: client ids, holds, balance flags
Gray, “The transaction concept” (1981) A paper What a transaction promises, and where the promise stops
Helland, “Immutability changes everything” (2015) A paper Append, never erase: the accountant’s habit as a design rule

Read each company’s claims as its own claims about its own system. Square’s 2019 post describes Books as an immutable double-entry accounting database service whose balances change only by taking part in an accounting transaction, and says double-entry accounting makes every change record why it happened as well as what changed (this rests on a search summary of the post; the post is Square’s own description of its own service)as of 2026-11. Stripe’s post describes Ledger as an immutable log of events built on double-entry bookkeeping and as the foundation for its data quality platform, and says the two together keep money movement more than 99.9999% explainable while data volume grew tenfold; the search results do not show how explainability is measured, and this is a vendor’s claim about its own systemas of 2026-11.

TigerBeetle differs from the other two in one way that matters here: it is a database you can download, so you can test what it says. Its documentation, as search results summarise it, describes a state machine that executes the transfers in a request one by one on a single core, batches many events into each request (the default configuration allows 8,189 per request), and offers strict serializability, meaning every operation appears to happen one after another in an order consistent with real time; adding nodes adds reliability, not throughputas of 2026-11. Jepsen’s analysis of version 0.16.11, published in June 2025 and funded by TigerBeetle, Inc., as the report states, notes that all writes go through one core on the primary, so the design scales up and not out (this rests on a search summary; the report was not read in full)as of 2026-11. That is the trade: you give up spreading writes over many machines and get rules that are simple to state and to test.

Gray’s paper is the first statement of the promise every ledger relies on: a transaction either happens completely or not at all. Helland’s gives the second, which accountants had already: you do not erase an entry, you add a correcting one. Both ideas are in everything below.

Two records and four counters

A ledger database in this style stores two kinds of record, and nothing else. An account is a place where value is counted. A transfer moves an amount from one account to another, and it is never changed once written.

TigerBeetle’s account reference describes four balance fields on each account: debits_pending, debits_posted, credits_pending and credits_posted, where the pending fields hold amounts reserved by pending transfers and drop out when a transfer posts, voids or times out; it also describes account flags that include linked, debits_must_not_exceed_credits and credits_must_not_exceed_debitsas of 2026-11. Its transfer reference says transfers are immutable, that there is at most one transfer with a given id, and that user_data fields can link a transfer to an external recordas of 2026-11.

Notice what is missing. There is no balance column to update and no signed number. A balance is derived from two running totals, debits and credits, in two states, pending and posted. For a wallet, which is a liability and so credit-normal (the double-entry chapter explains why), what a seller can spend is credits posted, minus debits posted, minus debits pending. That last term is the whole idea of a hold.

The lab’s engine, tbledger.py, has the same two records and the same four counters on SQLite. Owoleaf’s generated books map onto it like this.

Owoleaf Becomes Why
accounts.id account id Already unique
accounts.type (asset, liability, equity, income, expense) account code 1 to 5 A code classifies an account within a ledger
Naira ledger 1 A ledger is one currency: a transfer needs both accounts on the same one
A wallet the flag DEBITS_MUST_NOT_EXCEED_CREDITS A customer’s wallet must never go negative
transactions.id user_data on every transfer Links each transfer back to the business record
transactions.kind transfer code Why the money moved

One caution about what this engine is. It keeps four counters in rows that every transfer updates, which is the hot-row design the ledger-at-scale chapter measured. SQLite has one writer, so here that costs nothing extra, and a purpose-built ledger avoids the problem with its single-threaded core. The lab teaches the rules, not the throughput.

Ids are the idempotency key

In the idempotency chapter the key lived in your service: a reserved row, then one transaction. A ledger of this kind moves the check into the ledger, onto every transfer. The client chooses the transfer’s id, and the ledger refuses to create a second transfer with it.

Three answers cover a retry.

  • Same id, same fields: exists. The retry succeeded in the sense that matters. The first attempt did happen, and nothing changes.
  • Same id, a different field: exists_with_different_amount, or the same for the accounts, flags or code. Your service sent two different instructions under one id. That is a bug in the service, and the ledger names the field.
  • A new id: a new transfer. The ledger cannot know that you meant a retry.

The third answer is where the money is lost, so three rules follow from it.

Derive the id from the thing you are doing, and store it before you send. The lab uses the transaction id times ten, plus the leg’s position in its chain. A client that crashes and starts again computes the same ids and cannot pay twice.

A payment reference is not an id. Owoleaf’s schema says that a return reuses the original payment’s reference, and the data shows it: 98 payouts were reversed, and their 98 reversals carry the same external_ref. The 79,827 posted transactions have only 79,729 distinct references. Using the reference as the transfer id would make every reversal collide with its payout, and the ledger would answer with an exists_with_different_ code naming the first field that differs. The payment has one reference. Each transfer in its life has its own id.

A failed id is burned. TigerBeetle’s create_transfers reference, as search results summarise it, says an id that failed with a transient error (one that depends on the ledger’s state, such as too little balance or a missing account) is remembered, and a later request with the same id answers id_already_failed, so a transfer that is submitted again after such a failure needs a new id; the reference adds that releases before 0.16.4 did not check failed ids, so a retry could then succeedas of 2026-11. Picture it. A payout fails with exceeds_credits because the seller had ₦4,000. An hour later she has ₦9,000, and a retry loop sends the payout again under the same id. The ledger refuses. An id then has one meaning for ever: it names a transfer that exists, or a request that was refused. Your code has to choose: this is a new decision, so mint a new id.

Here is the discipline that keeps this from becoming the double-payment bug. Resend the same id when the outcome is unknown. Mint a new id only after a definite refusal, and only when you have decided to try again. A timeout is not a refusal. Step 1 of the lab runs this: the double tap fails with exceeds_credits, the retry under the same id answers id_already_failed, and the same hold under a new id succeeds.

Pending, post, void, timeout

A single transfer moves money at once. A pending transfer reserves it. It raises the pending counters and leaves the posted ones alone. A second transfer, which names the first by its pending_id, resolves it. Post turns the reservation into a real movement, for all of the amount or part. Void releases it. A pending transfer may also carry a timeout, in seconds, after which the ledger releases it by itself.

TigerBeetle’s two-phase transfers page, as search results summarise it, says a pending transfer can be resolved by a post, a void or a timeout, that posting and voiding must reference the original pending transfer, that pending balances are removed at their expiry (the transfer’s timestamp plus its timeout), and that an expired transfer cannot be posted or voidedas of 2026-11.

The floor flag counts reservations. The account reference defines debits_must_not_exceed_credits as rejecting a transfer when the account’s debits pending, plus its debits posted, plus the transfer’s amount, would exceed its credits postedas of 2026-11. Follow Ojaline’s seller through it. She has ₦10,000 posted. A payout hold of ₦6,000 leaves her ₦4,000 spendable: 10,000 minus 0 posted minus 6,000 pending. A second ₦6,000 hold fails, because 6,000 + 0 + 6,000 is 12,000, which is more than 10,000. If the first hold is posted, the ₦6,000 moves from pending to posted and she still has ₦4,000. If it is voided, or times out, it goes back and she has ₦10,000. Money credited to her as pending, such as earnings for a parcel still in transit, does not count, because only posted credits do. A seller cannot withdraw what has not been delivered.

A post may be for less than the hold. Posting ₦2,500 against a ₦3,000 hold moves ₦2,500, and the other ₦500 goes back. Posting more than was held is refused. Step 1 of the lab shows each case on tbledger.py. Step 6 runs fifteen of those operations on a real TigerBeetle server as well, and the answers agree on every one.

The clock decides, not the switch

▶ SIMULATION
COORDINATOR
state: init
decision (memory): —
decision (log on disk): empty
up
PARTICIPANT P1
state: working
vote: —
locks: none
outcome: —
PARTICIPANT P2
state: working
vote: —
locks: none
outcome: —
t = 0Transaction T1 updates rows on P1 and P2
✓ every participant reaches the same decision✓ no participant holds locks forever
SCHEDULE
01[Coord]Coord: send PREPARE(T1) to P1, P2
02[P1]P1: force-write prepare record, hold row locks, vote YES
03[P2]P2: force-write prepare record, hold row locks, vote YES
04[Coord]Coord: count votes, decide (in memory)
05[Coord]Coord: force-write decision to its log (fsync)
06[Coord]Coord: send decision to P1
07[Coord]Coord: send decision to P2
Start of all yes → commit scenario. 7 steps.
// Coordinator, after collecting votes:
decision = allYes(votes) ? COMMIT : ABORT
send(decision, participants)   // 1. tell everyone
log.write(decision)            // 2. then make it durable

// Participant on PREPARE:
lockRows()
reply(YES)                     // 1. promise
log.write({ vote: YES })       // 2. then remember the promise

// A crash between 1 and 2 (either side) leaves one node
// that acted on a decision nobody else can reconstruct.

Run COORDINATOR CRASH and watch the locks line. In two-phase commit, a participant that has voted YES has promised to do whatever it is told and cannot decide alone. If the coordinator dies, its locks stay held, and the tick count only climbs. FIX: DURABLE LOG + RESTART shows the cure: the coordinator writes its decision down before it sends it, so a restart can answer. (The distributed transactions chapter and the two-phase commit lesson go further.)

A pending transfer is the participant’s half. The reservation is the promise: the funds are held and the seller cannot spend them. The coordinator is whatever decides the outcome from outside the ledger, which for a payout is your payout service and the NIP switch behind it (Nigeria’s rails covers the switch). The post or void is the decision. If your service crashes after sending the payout and before posting, the seller’s funds sit in a hold.

Two things differ from two-phase commit, and both matter for design.

First, the timeout lets the ledger decide alone. That removes the blocking in the sim: the hold cannot be held hostage for ever. Second, this is a reservation inside one ledger, not an atomic commit across two systems. Nothing makes the ledger and the switch agree. If the switch paid and your service never posted, then when the timeout fires the ledger releases the money that has left, and a late post is refused with pending_transfer_expired. The clock turned an unknown into a decision, and it may have decided wrongly.

Step 5 of the lab measures it on Owoleaf’s payouts, with illustrative timings: a 15-minute timeout, a switch answer after 3 seconds, and one answer in 40 lost. That is 512 of the 20,897 payouts that went out. Every one expires. A day later reconciliation finds that the switch paid, the late post is refused, and the repair is a new transfer under a new id. Across the 512, ₦19,994,056.54 came back into sellers’ spendable balances after it had left. For up to a day, a seller could spend it again. The repair succeeded in the lab only because nobody did.

So a timeout is a business decision, with two numbers behind it. Set it longer than the slowest answer you can usually expect from the switch, and shorter than a seller will tolerate not seeing the money. Then design the repair path: requery the switch for the real outcome (idempotency calls this the step you cannot put in your transaction) and reconcile (reconciliation).

Linked transfers: all or nothing in one request

A transfer has exactly one debit account and one credit account. A business event often has more. A card top-up debits card clearing once, and credits the customer’s wallet and the fee income. Linked transfers solve it: the flag chains a transfer to the next, and the chain succeeds or fails as a whole.

Owoleaf’s books have 79,827 posted transactions. 31,449 have three legs, which are the 10,280 card top-ups, the 20,897 payouts (wallet, settlement, fee), the 174 daily card settlements and the 98 reversals. Each becomes two linked transfers. The replay therefore sends 79,827 + 31,449 = 111,276 transfers, and writes 222,552 entries where the original had 191,103. The pairing is greedy: take the first debit and the first credit, move the smaller amount, and carry on.

When a chain fails, the failing transfer carries its own code and every other transfer in it answers linked_event_failed. The same happens when you replay a chain that already exists: the first transfer answers exists and the rest of the chain answers linked_event_failed. Both tbledger.py and the real server gave that pair when this chapter ran it. Nothing is applied twice.

Replaying history

A migration is the test of a ledger design, so use one as the test of this one. Replay a period’s transactions through the new model, then compare every account with the old books. Compare debits and credits separately, not only the net, because a net hides two errors that cancel.

Step 2 does it for the whole generated ledger. 111,276 transfers are accepted, none is refused by the floor, and every one of the 2,005 accounts ends with the debits and credits the generated entries have. The floor refusing nothing is itself a check: check.py’s fourth invariant already says no wallet goes below zero in time order, and the replay applies transactions in id order, which is also time order in this data. Step 3 exports the replayed transfers as entries and runs check.py against them, which is the one command that tests your own ledger by the lab’s own rules.

The floor is a safety net with holes in it. Step 4 sends each payout twice, the second under a new id, as a retry bug would. The floor refuses most second payouts, because a payout takes a large share of the wallet. It does not refuse all of them: 6,502 of the 20,897 second payouts, 31.1%, found enough money and went through. The floor guards against overdraft. The id guards against the duplicate. You need both.

Where it goes wrong

  • The id comes from a business reference. Covered above: reversals reuse the payout’s reference. Test your candidate ids for uniqueness over history before you trust them.
  • A new id for an unknown outcome. Every timeout handler that mints a fresh id is a double payment waiting for a slow day. Keep the id with the intention, not with the attempt.
  • A floor on the wrong account. A wallet must not go negative. The settlement account at a partner bank may be overdrawn, and a floor there turns a treasury problem into refused customer payments. Put the flag where the business rule is.
  • A timeout nobody chose. The default or the first number someone typed. Measure the switch’s real answer times and decide.
  • Showing one number. A seller’s balance has four parts. Showing credits posted hides holds; showing credits minus debits posted ignores pending ones. Decide which number each screen shows, and name it.
  • A ledger with no names. A transfer has no seller name, order or parcel. The user_data fields link to the records that do, which live in another database. The two stores then need a standing comparison, or one of them drifts. This is reconciliation inside your own walls.
  • Cutting over without a replay. Dual-writing for weeks proves little if nobody compares. Replay history, then compare live postings daily until the difference is zero for as long as finance needs to see.
  • Reading a vendor’s number as yours. 99.9999% explainability, a batch of thousands, a transfers-a-second figure: each is measured on the vendor’s data on the vendor’s machine. Measure your own shape, as the ledger-at-scale chapter did.

None of this tells you which ledger to run. It tells you which questions to put to any of them, and the lab lets you check the answers.

LAB Build TigerBeetle-style transfers on SQLite and replay Owoleaf's ledger ~60 MIN
YOU NEEDPython 3.9 or later (standard library only)labs/finance with the data generated (python3 generate.py, scale 0.1, seed 42)No Docker, no packages and no sqlite3 program for steps 1 to 5Optional step 6: about 7 MB to download, 1.1 GB of free disk for the server's data file, and one package (the TigerBeetle Python client)

You work in labs/finance and create five files there: tbledger.py, walkthrough.py, replay.py, holds.py and, for the optional step, tbreplay.py. Money is integer kobo in every file; naira() only formats for display. Nothing writes to data/. The files are the ones this chapter ran, on Python 3.13.18. Timings differ on your machine; the counts and balances do not.

1. Build the engine and run one seller through every rule. Save tbledger.py. It is about 210 lines. Read it before you run anything: it is the chapter in code.

"""TigerBeetle-style accounts and transfers over SQLite. Integer kobo, standard library only.

The rules are the ones TigerBeetle's documentation describes, re-implemented so you can read them:
  * a transfer moves an amount from one account to another; its id is chosen by the CLIENT and is unique
  * the same id with the same fields answers 'exists'; with different fields, 'exists_with_different_<field>'
  * an id that failed for a reason that depends on the ledger's state is burned: 'id_already_failed'
  * pending reserves an amount; post (all or part) or void resolves it; a timeout voids it by itself
  * an account may forbid its debits from exceeding its credits (or the reverse), counting reserved amounts
  * transfers flagged LINKED succeed or fail together
This is a model for learning. It is one writer on one SQLite file, not a replicated database.
"""
import sqlite3

AMOUNT_MAX = 2**128 - 1
# account flags
DEBITS_MUST_NOT_EXCEED_CREDITS, CREDITS_MUST_NOT_EXCEED_DEBITS = 1, 2
# transfer flags
LINKED, PENDING, POST, VOID = 1, 2, 4, 8
OK = "created"
# failures that depend on the ledger's current state: the id is burned (this model's list)
TRANSIENT = {"exceeds_credits", "exceeds_debits", "debit_account_not_found",
             "credit_account_not_found", "pending_transfer_not_found"}

SCHEMA = """
CREATE TABLE IF NOT EXISTS accounts (id INTEGER PRIMARY KEY, ledger INT, code INT, flags INT,
  debits_pending INT NOT NULL DEFAULT 0, debits_posted INT NOT NULL DEFAULT 0,
  credits_pending INT NOT NULL DEFAULT 0, credits_posted INT NOT NULL DEFAULT 0, user_data INT NOT NULL DEFAULT 0);
CREATE TABLE IF NOT EXISTS transfers (id INTEGER PRIMARY KEY, debit_account_id INT, credit_account_id INT,
  amount INT, pending_id INT, timeout INT, ledger INT, code INT, flags INT, user_data INT, timestamp INT);
CREATE TABLE IF NOT EXISTS pending (id INTEGER PRIMARY KEY, expires_at INT, state TEXT);
CREATE TABLE IF NOT EXISTS failed (id INTEGER PRIMARY KEY);
CREATE INDEX IF NOT EXISTS pending_due ON pending (state, expires_at);
"""


class Transfer:
    def __init__(self, id, debit=0, credit=0, amount=0, ledger=1, code=1, flags=0,
                 pending_id=0, timeout=0, user_data=0):
        self.id, self.debit, self.credit, self.amount = id, debit, credit, amount
        self.ledger, self.code, self.flags = ledger, code, flags
        self.pending_id, self.timeout, self.user_data = pending_id, timeout, user_data


class Ledger:
    def __init__(self, path=":memory:", clock=lambda: 0):
        self.db = sqlite3.connect(path, isolation_level=None)
        self.db.executescript(SCHEMA)
        self.clock = clock          # seconds; the tests move it by hand
        self.now = clock()

    # --- accounts ---------------------------------------------------------------
    def create_accounts(self, accounts):
        """accounts: (id, ledger, code, flags, user_data) tuples. Returns one result per account."""
        out = []
        self.db.execute("BEGIN")
        for a in accounts:
            if a[0] == 0:
                out.append("id_must_not_be_zero")
            elif self.db.execute("SELECT 1 FROM accounts WHERE id = ?", (a[0],)).fetchone():
                out.append("exists")
            else:
                self.db.execute("INSERT INTO accounts (id, ledger, code, flags, user_data) VALUES (?,?,?,?,?)", a)
                out.append(OK)
        self.db.execute("COMMIT")
        return out

    def account(self, id):
        r = self.db.execute("SELECT debits_pending, debits_posted, credits_pending, credits_posted "
                            "FROM accounts WHERE id = ?", (id,)).fetchone()
        return dict(zip(("debits_pending", "debits_posted", "credits_pending", "credits_posted"), r)) if r else None

    # --- transfers --------------------------------------------------------------
    def create_transfers(self, batch):
        """One database transaction per call, like one request. Returns one result string per transfer."""
        self.now = self.clock()
        self.db.execute("BEGIN")
        self._expire()
        results, i, burned = [None] * len(batch), 0, []
        while i < len(batch):
            j = i
            while j < len(batch) and batch[j].flags & LINKED:
                j += 1                                   # the chain is i..j; the last one has no LINKED flag
            chain = range(i, min(j, len(batch) - 1) + 1)
            self.db.execute("SAVEPOINT chain")
            bad = None
            for k in chain:
                r = "linked_event_chain_open" if j >= len(batch) and k == chain[-1] else self._one(batch[k], burned)
                results[k] = r
                if r != OK:
                    bad = k                              # the rest of the chain does not run
                    break
            if bad is None:
                self.db.execute("RELEASE chain")
            else:
                self.db.execute("ROLLBACK TO chain")
                self.db.execute("RELEASE chain")
                for k in chain:
                    if k != bad:
                        results[k] = "linked_event_failed"
            i = j + 1
        for tid in burned:                               # recorded outside the chain, so a rollback keeps them
            self.db.execute("INSERT OR IGNORE INTO failed (id) VALUES (?)", (tid,))
        self.db.execute("COMMIT")
        return results

    def _expire(self):
        for pid, amount, d, c in self.db.execute(
                """SELECT p.id, t.amount, t.debit_account_id, t.credit_account_id FROM pending p
                   JOIN transfers t ON t.id = p.id WHERE p.state = 'pending' AND p.expires_at <= ?""",
                (self.now,)).fetchall():
            self.db.execute("UPDATE accounts SET debits_pending = debits_pending - ? WHERE id = ?", (amount, d))
            self.db.execute("UPDATE accounts SET credits_pending = credits_pending - ? WHERE id = ?", (amount, c))
            self.db.execute("UPDATE pending SET state = 'expired' WHERE id = ?", (pid,))

    def _one(self, t, burned):
        q = self.db.execute
        if t.id == 0:
            return "id_must_not_be_zero"
        row = q("SELECT debit_account_id, credit_account_id, amount, pending_id, timeout, ledger, code, flags, user_data "
                "FROM transfers WHERE id = ?", (t.id,)).fetchone()
        if row:
            return self._exists(row, t)
        if q("SELECT 1 FROM failed WHERE id = ?", (t.id,)).fetchone():
            return "id_already_failed"
        r = self._apply(t)
        if r in TRANSIENT:
            burned.append(t.id)
        return r

    @staticmethod
    def _exists(row, t):
        d, c, amount, pending_id, timeout, ledger, code, flags, user_data = row
        for name, stored, given in (("flags", flags, t.flags), ("pending_id", pending_id, t.pending_id),
                                    ("timeout", timeout, t.timeout), ("debit_account_id", d, t.debit),
                                    ("credit_account_id", c, t.credit), ("amount", amount, t.amount),
                                    ("user_data", user_data, t.user_data), ("ledger", ledger, t.ledger),
                                    ("code", code, t.code)):
            if t.flags & (POST | VOID) and name in ("debit_account_id", "credit_account_id", "amount", "ledger", "code"):
                continue                                  # a post or void takes these from the pending transfer
            if stored != given:
                return "exists_with_different_" + name
        return "exists"

    def _apply(self, t):
        q = self.db.execute
        kind = t.flags & (PENDING | POST | VOID)
        if kind not in (0, PENDING, POST, VOID):
            return "flags_are_mutually_exclusive"
        if t.timeout and kind != PENDING:
            return "timeout_reserved_for_pending_transfer"
        if kind in (POST, VOID):
            return self._resolve(t, kind)
        if t.pending_id:
            return "pending_id_must_be_zero"
        if t.debit == t.credit:
            return "accounts_must_be_different"
        d = q("SELECT flags, debits_pending, debits_posted, credits_posted, ledger FROM accounts WHERE id = ?", (t.debit,)).fetchone()
        c = q("SELECT flags, credits_pending, credits_posted, debits_posted, ledger FROM accounts WHERE id = ?", (t.credit,)).fetchone()
        if d is None:
            return "debit_account_not_found"
        if c is None:
            return "credit_account_not_found"
        if d[4] != c[4]:
            return "accounts_must_have_the_same_ledger"
        if d[0] & DEBITS_MUST_NOT_EXCEED_CREDITS and d[1] + d[2] + t.amount > d[3]:
            return "exceeds_credits"
        if c[0] & CREDITS_MUST_NOT_EXCEED_DEBITS and c[1] + c[2] + t.amount > c[3]:
            return "exceeds_debits"
        col = "pending" if kind == PENDING else "posted"
        q(f"UPDATE accounts SET debits_{col} = debits_{col} + ? WHERE id = ?", (t.amount, t.debit))
        q(f"UPDATE accounts SET credits_{col} = credits_{col} + ? WHERE id = ?", (t.amount, t.credit))
        self._store(t, t.debit, t.credit, t.amount)
        if kind == PENDING:
            q("INSERT INTO pending (id, expires_at, state) VALUES (?, ?, 'pending')",
              (t.id, self.now + t.timeout if t.timeout else None))
        return OK

    def _resolve(self, t, kind):
        q = self.db.execute
        if t.pending_id == 0:
            return "pending_id_must_not_be_zero"
        p = q("SELECT t.debit_account_id, t.credit_account_id, t.amount, t.flags, t.ledger, t.code, p.state "
              "FROM transfers t LEFT JOIN pending p ON p.id = t.id WHERE t.id = ?", (t.pending_id,)).fetchone()
        if p is None:
            return "pending_transfer_not_found"
        d, c, amount, flags, ledger, code, state = p
        if not flags & PENDING:
            return "pending_transfer_not_pending"
        if (t.debit and t.debit != d) or (t.credit and t.credit != c):
            return "pending_transfer_has_different_account"
        if state == "posted":
            return "pending_transfer_already_posted"
        if state == "voided":
            return "pending_transfer_already_voided"
        if state == "expired":
            return "pending_transfer_expired"
        if kind == POST:
            if t.amount != AMOUNT_MAX and t.amount > amount:
                return "exceeds_pending_transfer_amount"
            final = amount if t.amount == AMOUNT_MAX else t.amount
        else:
            if t.amount not in (0, AMOUNT_MAX, amount):
                return "pending_transfer_has_different_amount"
            final = 0
        q("UPDATE accounts SET debits_pending = debits_pending - ?, debits_posted = debits_posted + ? WHERE id = ?", (amount, final, d))
        q("UPDATE accounts SET credits_pending = credits_pending - ?, credits_posted = credits_posted + ? WHERE id = ?", (amount, final, c))
        q("UPDATE pending SET state = ? WHERE id = ?", ("posted" if kind == POST else "voided", t.pending_id))
        self._store(t, d, c, final)
        return OK

    def _store(self, t, d, c, amount):
        self.db.execute("INSERT INTO transfers VALUES (?,?,?,?,?,?,?,?,?,?,?)",
                        (t.id, d, c, amount, t.pending_id, t.timeout, t.ledger, t.code, t.flags, t.user_data, self.now))

Save walkthrough.py. It posts to a seller wallet with the floor flag, then tries each rule in turn.

"""One seller wallet through every rule of tbledger.py. Amounts are integer kobo; naira() only formats."""
from tbledger import (Ledger, Transfer, AMOUNT_MAX, DEBITS_MUST_NOT_EXCEED_CREDITS as FLOOR,
                      PENDING, POST, VOID, LINKED)

naira = lambda k: f"₦{k // 100:,}"
clock = [0]
L = Ledger(clock=lambda: clock[0])
ESCROW, SELLER, CLEARING, FEES = 1, 2, 3, 4
print(L.create_accounts([(ESCROW, 1, 1, 0, 0), (SELLER, 1, 2, FLOOR, 0), (CLEARING, 1, 1, 0, 0), (FEES, 1, 4, 0, 0)]))


def say(label, result):
    a = L.account(SELLER)
    spendable = a["credits_posted"] - a["debits_posted"] - a["debits_pending"]
    print(f"{label:<47}{result:<36}spendable {naira(spendable):>8}   held {naira(a['debits_pending']):>7}")


def one(t):
    return L.create_transfers([t])[0]


K = 100
say("1. delivery confirmed, id 1001, N10,000", one(Transfer(1001, ESCROW, SELLER, 10_000 * K)))
say("2. the same request again (a retry)", one(Transfer(1001, ESCROW, SELLER, 10_000 * K)))
say("3. same id, amount N10,001", one(Transfer(1001, ESCROW, SELLER, 10_001 * K)))
say("4. payout hold N6,000, id 2001, 15 min", one(Transfer(2001, SELLER, CLEARING, 6_000 * K, flags=PENDING, timeout=900)))
say("5. second hold N6,000, id 2002 (double tap)", one(Transfer(2002, SELLER, CLEARING, 6_000 * K, flags=PENDING, timeout=900)))
say("6. N5,000 arrives, id 1002", one(Transfer(1002, ESCROW, SELLER, 5_000 * K)))
say("7. retry id 2002 now that there is money", one(Transfer(2002, SELLER, CLEARING, 6_000 * K, flags=PENDING, timeout=900)))
say("8. same hold under a new id, 2003", one(Transfer(2003, SELLER, CLEARING, 6_000 * K, flags=PENDING, timeout=900)))
say("9. switch says paid: post 2001", one(Transfer(3001, pending_id=2001, amount=AMOUNT_MAX, flags=POST)))
say("10. post 2001 again, id 3002", one(Transfer(3002, pending_id=2001, amount=AMOUNT_MAX, flags=POST)))
say("11. switch says failed: void 2003", one(Transfer(3003, pending_id=2003, flags=VOID)))
say("12. hold N1,000, id 2004, 15 min", one(Transfer(2004, SELLER, CLEARING, 1_000 * K, flags=PENDING, timeout=900)))
clock[0] += 901
say("13. 901 s pass; switch finally says paid", one(Transfer(3004, pending_id=2004, amount=AMOUNT_MAX, flags=POST)))
say("14. hold N3,000, id 2005; post only N2,500", (one(Transfer(2005, SELLER, CLEARING, 3_000 * K, flags=PENDING, timeout=900)),
                                                    one(Transfer(3005, pending_id=2005, amount=2_500 * K, flags=POST)))[1])
say("15. post N3,001 against a N3,000 hold", (one(Transfer(2006, SELLER, CLEARING, 3_000 * K, flags=PENDING, timeout=900)),
                                              one(Transfer(3006, pending_id=2006, amount=3_001 * K, flags=POST)))[1])
r = L.create_transfers([Transfer(4001, SELLER, CLEARING, 500 * K, flags=LINKED),
                        Transfer(4002, SELLER, 999, 20 * K)])
before = L.account(SELLER)
print(f"16. linked payout + fee, fee account missing:   {r}   seller debits_posted still {naira(before['debits_posted'])}")
print("seller:", L.account(SELLER))
cd labs/finance
python3 walkthrough.py
['created', 'created', 'created', 'created']
1. delivery confirmed, id 1001, N10,000        created                             spendable  ₦10,000   held      ₦0
2. the same request again (a retry)            exists                              spendable  ₦10,000   held      ₦0
3. same id, amount N10,001                     exists_with_different_amount        spendable  ₦10,000   held      ₦0
4. payout hold N6,000, id 2001, 15 min         created                             spendable   ₦4,000   held  ₦6,000
5. second hold N6,000, id 2002 (double tap)    exceeds_credits                     spendable   ₦4,000   held  ₦6,000
6. N5,000 arrives, id 1002                     created                             spendable   ₦9,000   held  ₦6,000
7. retry id 2002 now that there is money       id_already_failed                   spendable   ₦9,000   held  ₦6,000
8. same hold under a new id, 2003              created                             spendable   ₦3,000   held ₦12,000
9. switch says paid: post 2001                 created                             spendable   ₦3,000   held  ₦6,000
10. post 2001 again, id 3002                   pending_transfer_already_posted     spendable   ₦3,000   held  ₦6,000
11. switch says failed: void 2003              created                             spendable   ₦9,000   held      ₦0
12. hold N1,000, id 2004, 15 min               created                             spendable   ₦8,000   held  ₦1,000
13. 901 s pass; switch finally says paid       pending_transfer_expired            spendable   ₦9,000   held      ₦0
14. hold N3,000, id 2005; post only N2,500     created                             spendable   ₦6,500   held      ₦0
15. post N3,001 against a N3,000 hold          exceeds_pending_transfer_amount     spendable   ₦3,500   held  ₦3,000
16. linked payout + fee, fee account missing:   ['linked_event_failed', 'credit_account_not_found']   seller debits_posted still ₦8,500
seller: {'debits_pending': 300000, 'debits_posted': 850000, 'credits_pending': 0, 'credits_posted': 1500000}

Check three lines by hand. Line 4: ₦10,000 minus a ₦6,000 hold leaves ₦4,000 spendable. Line 5: 6,000 + 6,000 is more than 10,000, so exceeds_credits. Line 8: after ₦5,000 arrives, the seller has ₦15,000 posted; ₦6,000 is held by 2001 and ₦6,000 by 2003, so spendable is 15,000 minus 12,000, which is ₦3,000 and the held column reads ₦12,000. Line 7 is the burned id: the same hold that the ledger now has the money for is refused because 2002 failed earlier. Line 13 is the timeout: 901 seconds passed, the hold is gone from the held column, and the late post is refused. In line 16 the whole chain fails and the seller’s debits posted stay at ₦8,500.

2. Replay the generated ledger, then replay it again. Save replay.py. It builds a chain of linked transfers for each posted transaction, derives the ids, sends them in batches and compares every account’s debits and credits with the generated entries.

"""Replay the generated ledger (data/finance.sqlite) as TigerBeetle-style transfers and compare balances.

    python3 replay.py                     replay once, compare every account with the generated entries
    python3 replay.py --twice             send every transfer a second time, with the same ids
    python3 replay.py --double-payouts    after each payout, send a second one under a NEW id (a retry bug)
    python3 replay.py --export out.sqlite write the replayed ledger in the lab's own schema, for check.py

One generated transaction has 1 to 3 debit and credit legs. A transfer has one of each, so legs are paired
greedily in entry order: the first debit against the first credit for the smaller amount, and so on. The legs
of one transaction go in one LINKED chain, so a transaction is all or nothing. Transfer id = transaction id
times 10, plus 1 or 2 for the position in the chain. That is the idempotency key.
"""
import sqlite3, sys
from collections import Counter
from tbledger import Ledger, Transfer, DEBITS_MUST_NOT_EXCEED_CREDITS, LINKED, OK

SRC = "file:data/finance.sqlite?mode=ro"
BATCH = 8_000                                  # transfers per request (a real server's batches are of this order)


def load(db):
    types = {"asset": 1, "liability": 2, "equity": 3, "income": 4, "expense": 5}
    accounts = [(i, 1, types[t], DEBITS_MUST_NOT_EXCEED_CREDITS if t == "liability" else 0, 0)
                for i, t in db.execute("SELECT id, type FROM accounts ORDER BY id")]
    kinds = {k: n for n, (k,) in enumerate(db.execute("SELECT DISTINCT kind FROM transactions ORDER BY 1"), 1)}
    kind_of = {i: kinds[k] for i, k in db.execute("SELECT id, kind FROM transactions")}
    txns, last = [], None
    for tx, acct, d, kobo in db.execute("SELECT transaction_id, account_id, direction, amount_kobo FROM entries "
                                        "ORDER BY transaction_id, id"):
        if tx != last:
            txns.append((tx, [], []))
            last = tx
        txns[-1][1 if d == "debit" else 2].append([acct, kobo])
    return accounts, kind_of, txns


def chain(tx, debits, credits, code):
    """Pair the legs of one transaction into transfers, linked so they commit together."""
    debits, credits, out, n = [list(x) for x in debits], [list(x) for x in credits], [], 1
    while debits and credits:
        d, c = debits[0], credits[0]
        amount = min(d[1], c[1])
        out.append(Transfer(tx * 10 + n, d[0], c[0], amount, code=code, user_data=tx, flags=LINKED))
        d[1] -= amount; c[1] -= amount; n += 1
        if d[1] == 0: debits.pop(0)
        if c[1] == 0: credits.pop(0)
    assert not debits and not credits, f"transaction {tx} does not balance"
    out[-1].flags &= ~LINKED
    return out


def send(L, transfers):
    """Send in batches that never split a chain. Returns one result per transfer."""
    i, out = 0, []
    while i < len(transfers):
        j = min(i + BATCH, len(transfers))
        while j < len(transfers) and transfers[j - 1].flags & LINKED:
            j += 1
        out += L.create_transfers(transfers[i:j])
        i = j
    return out


def main():
    twice, doubles = "--twice" in sys.argv, "--double-payouts" in sys.argv
    export = sys.argv[sys.argv.index("--export") + 1] if "--export" in sys.argv else None
    db = sqlite3.connect(SRC, uri=True)
    accounts, kind_of, txns = load(db)
    payout = {i for i, k in db.execute("SELECT id, kind FROM transactions") if k == "payout_nip"}
    L = Ledger()
    L.create_accounts(accounts)
    transfers = []
    for tx, debits, credits in txns:
        transfers += chain(tx, debits, credits, kind_of[tx])
        if doubles and tx in payout:             # the same payout again, under a fresh id (tx*10 + 5, 6)
            transfers += [Transfer(t.id + 4, t.debit, t.credit, t.amount, code=t.code, user_data=t.user_data,
                                   flags=t.flags) for t in chain(tx, debits, credits, kind_of[tx])]
    results = send(L, transfers)
    print(f"{len(accounts):,} accounts, {len(txns):,} posted transactions, {len(transfers):,} transfers sent")
    print("results:", dict(Counter(results)))
    if doubles:
        second = Counter(r for t, r in zip(transfers, results) if t.id % 10 == 5)
        print(f"second payout under a new id, first leg: {dict(second)}")
    if twice:
        print("sent again, same ids:", dict(Counter(send(L, transfers))))
    want = {a: (d, c) for a, d, c in db.execute(
        """SELECT account_id, SUM(CASE direction WHEN 'debit' THEN amount_kobo ELSE 0 END),
                  SUM(CASE direction WHEN 'credit' THEN amount_kobo ELSE 0 END) FROM entries GROUP BY account_id""")}
    wrong = [a for a, _, _, _, _ in accounts
             if (L.account(a)["debits_posted"], L.account(a)["credits_posted"]) != want.get(a, (0, 0))]
    held = L.db.execute("SELECT SUM(debits_pending + credits_pending) FROM accounts").fetchone()[0]
    print(f"accounts whose debits or credits differ from the generated entries: {len(wrong)}   reserved (pending): {held} kobo")
    print("every account matches:", not wrong)
    if doubles:
        paid = sum(t.amount for t, r in zip(transfers, results) if t.id % 10 == 5 and r == OK)
        print(f"principal of the second payouts that went through: {paid:,} kobo")
    if export:
        write_export(L, db, export)


def write_export(L, db, path):
    """The replayed ledger in the lab's schema, so check.py --db can test it."""
    import os
    if os.path.exists(path):
        os.remove(path)
    out = sqlite3.connect(path)
    out.executescript(open("schema.sql").read())
    for table in ("customers", "accounts", "transactions"):
        cols = [r[1] for r in db.execute(f"PRAGMA table_info({table})")]
        out.executemany(f"INSERT INTO {table} ({','.join(cols)}) VALUES ({','.join('?' * len(cols))})",
                        db.execute(f"SELECT {','.join(cols)} FROM {table}"))
    when = dict(db.execute("SELECT id, created_at FROM transactions"))
    n = 0
    for tid, d, c, amount, tx in L.db.execute(
            "SELECT id, debit_account_id, credit_account_id, amount, user_data FROM transfers ORDER BY id"):
        for acct, direction in ((d, "debit"), (c, "credit")):
            n += 1
            out.execute("INSERT INTO entries VALUES (?,?,?,?,?,?)", (n, tx, acct, direction, amount, when[tx]))
    out.commit()
    print(f"wrote {n:,} entries from the replayed transfers to {path}")


if __name__ == "__main__":
    main()
python3 replay.py
python3 replay.py --twice
2,005 accounts, 79,827 posted transactions, 111,276 transfers sent
results: {'created': 111276}
accounts whose debits or credits differ from the generated entries: 0   reserved (pending): 0 kobo
every account matches: True
2,005 accounts, 79,827 posted transactions, 111,276 transfers sent
results: {'created': 111276}
sent again, same ids: {'exists': 79827, 'linked_event_failed': 31449}
accounts whose debits or credits differ from the generated entries: 0   reserved (pending): 0 kobo
every account matches: True

111,276 transfers for 79,827 transactions, as the chapter worked out. The second send answers exists 79,827 times and linked_event_failed 31,449 times: 79,827 + 31,449 = 111,276. Every balance is the same afterwards.

3. Test your ledger with check.py. check.py accepts any database in the lab’s schema, so write the replayed transfers out as entries and point it at that.

python3 replay.py --export /tmp/replayed.sqlite
python3 check.py --db /tmp/replayed.sqlite
2,005 accounts, 79,827 posted transactions, 111,276 transfers sent
results: {'created': 111276}
accounts whose debits or credits differ from the generated entries: 0   reserved (pending): 0 kobo
every account matches: True
wrote 222,552 entries from the replayed transfers to /tmp/replayed.sqlite
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 (no statement)
6 skipped: no bank_statement table (or it is empty) in this database
OK: all invariants hold

The accounts-by-type line is the same one python3 check.py prints for the generated ledger. Invariant 6 is skipped because the replay has no bank statement. Invariants 1 to 5 hold on a ledger built only from transfers.

4. Show that the floor is not idempotency. The same replay, but after each payout a second one goes out under a new id.

python3 replay.py --double-payouts
2,005 accounts, 79,827 posted transactions, 153,070 transfers sent
results: {'created': 114873, 'exceeds_credits': 20138, 'linked_event_failed': 18059}
second payout under a new id, first leg: {'exceeds_credits': 14375, 'created': 6502, 'linked_event_failed': 20}
accounts whose debits or credits differ from the generated entries: 1779   reserved (pending): 0 kobo
every account matches: False
principal of the second payouts that went through: 11,596,038,573 kobo

Of 20,897 second payouts, 6,502 went through (31.1%) and 14,375 were refused by the floor. Twenty more failed on their fee leg, which fails the chain. The 6,502 are ₦115,960,385.73 of principal paid twice. Those wallets are now short, so later genuine transfers are refused too, which is why 1,779 of 2,005 accounts end different from the books. The created total is 114,873, not 111,276 plus thousands of duplicates, for the same reason.

5. Give every payout a hold, and lose some answers. Save holds.py. Every NIP payout becomes a pending chain with a 15-minute timeout, posted 3 seconds later, except that one in 40 gets no answer until a day later. Failed attempts (the switch’s bank unavailable) become a hold, then a void. The clock is the generated timestamps. All the timings are illustrative.

"""Replay the generated ledger with every NIP payout as a hold: pending, then post or void, or neither.

    python3 holds.py            1 payout in 40 gets no answer from the switch until a day later
    python3 holds.py --drain    ...and the seller sends the money the expired hold released to another wallet,
                                an hour after the hold expires

Every other transaction is replayed as in replay.py. The clock is the generated timestamps, in seconds. The
15-minute timeout, the 3-second answer, the 1-in-40 lost answers and the 24-hour reconciliation are ILLUSTRATIVE.
"""
import datetime as dt, sqlite3, sys
from collections import Counter
from tbledger import Ledger, Transfer, AMOUNT_MAX, LINKED, PENDING, POST, VOID, OK
from replay import SRC, load, chain

TIMEOUT, ANSWER, LATE, LOST_EVERY, DRAIN_AFTER = 900, 3, 86_400, 40, 3_600
drain = "--drain" in sys.argv
db = sqlite3.connect(SRC, uri=True)
accounts, kind_of, txns = load(db)
info = {i: (k, st, ts) for i, k, st, ts in db.execute("SELECT id, kind, status, created_at FROM transactions")}
epoch = lambda iso: int(dt.datetime.fromisoformat(iso).timestamp())
wallet = {c: a for a, c in db.execute("SELECT id, customer_id FROM accounts WHERE customer_id IS NOT NULL")}
settlement, fees = (db.execute("SELECT id FROM accounts WHERE code = ?", (c,)).fetchone()[0] for c in ("settlement_bank", "fee_revenue"))
SINK = wallet[1]                                     # where --drain sends the money

clock = [0]
L = Ledger(clock=lambda: clock[0])
L.create_accounts(accounts)


def legs(wallet_id, amount, fee):
    return [[wallet_id, amount + fee]], [[settlement, amount], [fees, fee]]


def as_holds(tx, d, c, flags):
    """The payout's chain with every transfer pending (flags=PENDING) or resolving pending ones (POST / VOID)."""
    out = []
    for t in chain(tx, d, c, kind_of.get(tx, 0)):
        last = not t.flags & LINKED
        if flags == PENDING:
            t.flags, t.timeout = PENDING | (0 if last else LINKED), TIMEOUT
        else:
            out.append(Transfer(t.id + 2, pending_id=t.id, amount=AMOUNT_MAX, flags=flags | (0 if last else LINKED), user_data=tx))
            continue
        out.append(t)
    return out


events = []                                          # (time, order, what, tx, wallet, amount, fee)
for tx, d, c in txns:
    kind, status, ts = info[tx]
    if kind != "payout_nip":
        events.append((epoch(ts), len(events), "plain", tx, d, c))
        continue
    amount, fee = c[0][1], c[1][1]
    w = d[0][0]
    events.append((epoch(ts), len(events), "hold", tx, d, c))
    if tx % LOST_EVERY == 0:
        events.append((epoch(ts) + LATE, len(events), "late", tx, d, c))
        if drain and TIMEOUT + DRAIN_AFTER < LATE:         # only if the repair has not yet come
            events.append((epoch(ts) + TIMEOUT + DRAIN_AFTER, len(events), "drain", tx, w, amount + fee))
    else:
        events.append((epoch(ts) + ANSWER, len(events), "post", tx, d, c))
for tx, kind, status, reason, cid, amount, fee, ts in db.execute(
        "SELECT id, kind, status, failure_reason, customer_id, amount_kobo, fee_kobo, created_at FROM transactions "
        "WHERE kind = 'payout_nip' AND status = 'failed' AND failure_reason = 'beneficiary_bank_unavailable'"):
    d, c = legs(wallet[cid], amount, fee)
    events.append((epoch(ts), len(events), "hold", tx, d, c))
    events.append((epoch(ts) + ANSWER, len(events), "void", tx, d, c))
events.sort()

seen, late_results, drained, moved = Counter(), Counter(), 0, Counter()
repaired, refused = 0, 0
for when, _, what, tx, d, c in events:
    clock[0] = when
    if what == "plain":
        r = L.create_transfers(chain(tx, d, c, kind_of[tx]))
    elif what == "hold":
        r = L.create_transfers(as_holds(tx, d, c, PENDING))
    elif what == "post":
        r = L.create_transfers(as_holds(tx, d, c, POST))
    elif what == "void":
        r = L.create_transfers(as_holds(tx, d, c, VOID))
    elif what == "drain":
        a = L.account(d)                              # d is the wallet id, c the amount the expired hold released
        move = min(c, a["credits_posted"] - a["debits_posted"] - a["debits_pending"])
        if move > 0:
            L.create_transfers([Transfer(tx * 10 + 9, d, SINK, move, user_data=tx)])
            drained += move
            moved[d] += move
        continue
    else:                                             # late: the switch confirms; the hold is long gone
        r = L.create_transfers(as_holds(tx, d, c, POST))
        late_results[r[0]] += 1
        r2 = L.create_transfers([Transfer(t.id + 4, t.debit, t.credit, t.amount, user_data=tx, flags=t.flags)
                                 for t in chain(tx, d, c, kind_of[tx])])
        late_results["repair: " + r2[0]] += 1
        if r2[0] == OK:
            repaired += sum(t.amount for t in chain(tx, d, c, kind_of[tx]))
        else:
            refused += sum(t.amount for t in chain(tx, d, c, kind_of[tx]))
        continue
    seen[(what, r[0])] += 1

clock[0] += LATE
L.create_transfers([])                                # let the clock expire whatever is left
states = dict(L.db.execute("SELECT state, COUNT(*) FROM pending GROUP BY state"))
print("answers by kind and first result:", {f"{k[0]}:{k[1]}": v for k, v in sorted(seen.items())})
print("holds by final state:", states)
print("late confirmations:", dict(late_results))
print(f"repairs booked {repaired:,} kobo; repairs refused {refused:,} kobo" + (f"; drained {drained:,} kobo" if drain else ""))

src = sqlite3.connect(SRC, uri=True)
want = {a: (dd, cc) for a, dd, cc in src.execute(
    """SELECT account_id, SUM(CASE direction WHEN 'debit' THEN amount_kobo ELSE 0 END),
              SUM(CASE direction WHEN 'credit' THEN amount_kobo ELSE 0 END) FROM entries GROUP BY account_id""")}
for w, amount in moved.items():                      # the drains are not in the generated books: allow for them
    want[w] = (want[w][0] + amount, want[w][1])
if moved:
    want[SINK] = (want[SINK][0], want[SINK][1] + drained)
wrong = [a for a, *_ in accounts if (L.account(a)["debits_posted"], L.account(a)["credits_posted"]) != want.get(a, (0, 0))]
held = L.db.execute("SELECT SUM(debits_pending + credits_pending) FROM accounts").fetchone()[0]
note = " (allowing for the drains)" if drain else ""
print(f"accounts that differ from the generated entries{note}: {len(wrong)}; kobo still reserved: {held}")
python3 holds.py
answers by kind and first result: {'hold:created': 21595, 'plain:created': 58930, 'post:created': 20385, 'void:created': 698}
holds by final state: {'expired': 1024, 'posted': 40770, 'voided': 1396}
late confirmations: {'pending_transfer_expired': 512, 'repair: created': 512}
repairs booked 1,999,405,654 kobo; repairs refused 0 kobo
accounts that differ from the generated entries: 0; kobo still reserved: 0

21,595 holds: 20,897 payouts and 698 failed attempts. Each is two transfers, so the final states count 40,770 posted (20,385 payouts, answered in time, times two), 1,396 voided (698 times two) and 1,024 expired (512 times two). The 512 lost answers all expire, every late post is refused with pending_transfer_expired, and the repair, a new transfer, books them: 1,999,405,654 kobo, ₦19,994,056.54. Nothing is left reserved, and every account matches the generated entries.

6. Optional: the same thing on a real TigerBeetle server. This step downloads a program and runs a server on your machine. Skip it if you prefer. The version used here is 0.17.9 (build 0.17.9+cc1c06a), on x86_64 Linux. Other systems use a different zip from the same releases page (check the asset list on that page; this chapter ran only the Linux one). In a spare terminal:

mkdir -p ~/tb && cd ~/tb
curl -L -o tigerbeetle.zip https://github.com/tigerbeetle/tigerbeetle/releases/download/0.17.9/tigerbeetle-x86_64-linux.zip
unzip tigerbeetle.zip
./tigerbeetle version
./tigerbeetle format --cluster=0 --replica=0 --replica-count=1 --development ./0_0.tigerbeetle
./tigerbeetle start --addresses=3000 --development ./0_0.tigerbeetle

Leave the last command running. In the lab terminal, install the client into its own environment and run tbreplay.py, which sends the same 111,276 transfers, sends them again, compares every balance, and then runs the walkthrough’s rules on both engines side by side. Save it first.

"""Optional: the same replay against a real TigerBeetle server, then the same rules on both engines.

    python3 tbreplay.py 3000          # the address you started the server on

Needs the official client:  pip install tigerbeetle==0.17.9  (the one place the lab leaves the standard library).
"""
import sys, time
from collections import Counter
import sqlite3
import tigerbeetle as tb
from replay import SRC, load, chain

BATCH = 250       # a --development server took 250 events in one request and refused 254 (a production one takes thousands)
import tbledger as mine

F, T = tb.AccountFlags, tb.TransferFlags
client = tb.ClientSync(cluster_id=0, replica_addresses=sys.argv[1] if len(sys.argv) > 1 else "3000")
name = lambda r: r.status.name.lower()

db = sqlite3.connect(SRC, uri=True)
accounts, kind_of, txns = load(db)
made = [tb.Account(id=i, ledger=1, code=code, flags=F.DEBITS_MUST_NOT_EXCEED_CREDITS if fl else F.NONE)
        for i, _, code, fl, _ in accounts]
for i in range(0, len(made), BATCH):
    client.create_accounts(made[i:i + BATCH])
transfers = []
for tx, d, c in txns:
    for t in chain(tx, d, c, kind_of[tx]):
        transfers.append(tb.Transfer(id=t.id, debit_account_id=t.debit, credit_account_id=t.credit, amount=t.amount,
                                     ledger=1, code=t.code, user_data_64=tx,
                                     flags=T.LINKED if t.flags & mine.LINKED else T.NONE))


def send(ts):
    out, i = [], 0
    while i < len(ts):
        j = min(i + BATCH, len(ts))
        while j < len(ts) and ts[j - 1].flags & T.LINKED:
            j += 1
        out += client.create_transfers(ts[i:j])
        i = j
    return out


t0 = time.time()
print("first send: ", dict(Counter(name(r) for r in send(transfers))), f"in {time.time() - t0:.1f} s")
print("second send:", dict(Counter(name(r) for r in send(transfers))))
want = {a: (d, c) for a, d, c in db.execute(
    """SELECT account_id, SUM(CASE direction WHEN 'debit' THEN amount_kobo ELSE 0 END),
              SUM(CASE direction WHEN 'credit' THEN amount_kobo ELSE 0 END) FROM entries GROUP BY account_id""")}
ids = [a[0] for a in accounts]
got = {a.id: (a.debits_posted, a.credits_posted) for i in range(0, len(ids), BATCH) for a in client.lookup_accounts(ids[i:i + BATCH])}
print("accounts read back:", len(got), "  every balance matches the generated entries:",
      all(got[a] == want.get(a, (0, 0)) for a in ids))

# The same rules on both engines. Step: (what, id, debit, credit, amount, pending id, timeout seconds)
E, S, C = 9_000_001, 9_000_002, 9_000_003
STEPS = [("single", 1001, E, S, 1_000_000), ("single", 1001, E, S, 1_000_000), ("single", 1001, E, S, 1_000_100),
         ("pending", 2001, S, C, 600_000, 900), ("pending", 2002, S, C, 600_000, 900), ("single", 1002, E, S, 500_000),
         ("pending", 2002, S, C, 600_000, 900), ("post", 3001, 2001, None), ("post", 3002, 2001, None),
         ("pending", 2004, S, C, 100_000, 1), ("wait", 3), ("post", 3004, 2004, None),
         ("pending", 2005, S, C, 300_000, 900), ("post", 3005, 2005, 250_000),
         ("pending", 2006, S, C, 300_000, 900), ("post", 3006, 2006, 300_100)]
MAX = mine.AMOUNT_MAX
BASE = 10**9        # keep these ids clear of the replay's (transaction id times 10)
client.create_accounts([tb.Account(id=E, ledger=1, code=1), tb.Account(id=S, ledger=1, code=2, flags=F.DEBITS_MUST_NOT_EXCEED_CREDITS),
                        tb.Account(id=C, ledger=1, code=1)])
clock = [0]
L = mine.Ledger(clock=lambda: clock[0])
L.create_accounts([(E, 1, 1, 0, 0), (S, 1, 2, mine.DEBITS_MUST_NOT_EXCEED_CREDITS, 0), (C, 1, 1, 0, 0)])
agree = True
print(f"{'step':<28}{'tbledger.py':<36}real TigerBeetle")
for s in STEPS:
    if s[0] == "wait":
        time.sleep(s[1]); clock[0] += s[1]
        continue
    kind, tid = s[0], BASE + s[1]
    if kind in ("single", "pending"):
        d, c, amt = s[2:5]
        timeout = s[5] if kind == "pending" else 0
        a = L.create_transfers([mine.Transfer(tid, d, c, amt, flags=mine.PENDING if timeout else 0, timeout=timeout)])[0]
        b = name(client.create_transfers([tb.Transfer(id=tid, debit_account_id=d, credit_account_id=c, amount=amt, ledger=1, code=1,
                                                      flags=T.PENDING if timeout else T.NONE, timeout=timeout)])[0])
    else:
        pid, amt = BASE + s[2], s[3] or MAX
        a = L.create_transfers([mine.Transfer(tid, pending_id=pid, amount=amt, flags=mine.POST)])[0]
        b = name(client.create_transfers([tb.Transfer(id=tid, pending_id=pid, amount=amt, ledger=1, code=1,
                                                      flags=T.POST_PENDING_TRANSFER)])[0])
    agree &= a == b
    print(f"{kind + ' ' + str(s[1]):<28}{a:<36}{b}")
real = client.lookup_accounts([S])[0]
mineS = L.account(S)
print("seller, tbledger.py:", mineS)
print("seller, real:       ", dict(debits_pending=real.debits_pending, debits_posted=real.debits_posted,
                                    credits_pending=real.credits_pending, credits_posted=real.credits_posted))
print("every result and the seller's four counters agree:", agree and mineS == dict(
    debits_pending=real.debits_pending, debits_posted=real.debits_posted,
    credits_pending=real.credits_pending, credits_posted=real.credits_posted))
python3 -m venv ~/tb/.venv
~/tb/.venv/bin/pip install tigerbeetle==0.17.9
~/tb/.venv/bin/python tbreplay.py 3000
TigerBeetle version 0.17.9+cc1c06a
2026-11-17 21:57:20.510Z info(main): 0: formatted: cluster=0 replica_count=1
first send:  {'created': 111276} in 1.8 s
second send: {'exists': 79827, 'linked_event_failed': 31449}
accounts read back: 2005   every balance matches the generated entries: True
step                        tbledger.py                         real TigerBeetle
single 1001                 created                             created
single 1001                 exists                              exists
single 1001                 exists_with_different_amount        exists_with_different_amount
pending 2001                created                             created
pending 2002                exceeds_credits                     exceeds_credits
single 1002                 created                             created
pending 2002                id_already_failed                   id_already_failed
post 3001                   created                             created
post 3002                   pending_transfer_already_posted     pending_transfer_already_posted
pending 2004                created                             created
post 3004                   pending_transfer_expired            pending_transfer_expired
pending 2005                created                             created
post 3005                   created                             created
pending 2006                created                             created
post 3006                   exceeds_pending_transfer_amount     exceeds_pending_transfer_amount
seller, tbledger.py: {'debits_pending': 300000, 'debits_posted': 850000, 'credits_pending': 0, 'credits_posted': 1500000}
seller, real:        {'debits_pending': 300000, 'debits_posted': 850000, 'credits_pending': 0, 'credits_posted': 1500000}
every result and the seller's four counters agree: True

The first two blocks are what version printed and the last line format printed (it also logged two lines about creating and allocating the file, and the time stamp is yours). The first send takes about 1.8 s here, and yours will differ. The second send gives the same 79,827 and 31,449 as tbledger.py. Every one of the 2,005 balances matches the generated entries. In the table, the model and the real server give the same answer on all fifteen operations, and the seller’s four counters agree. A development server took 250 events in one request and refused 254 with a too-much-data error, so the script sends 250 at a time. A production server’s batches are much larger. The script is for a freshly formatted file: run twice on the same server, the account and transfer ids already exist and the table will differ. Stop the server with Ctrl-C and delete ~/tb/0_0.tigerbeetle (about 1.1 GB) when you finish.

This output is one run on one machine. It does not show a difference in speed between the model and the server, and you should not read one into it: the model is one writer on SQLite, and the server is a replicated database run here as a single node.

Lose the money the clock gave back. Run python3 holds.py --drain: an hour after each lost payout’s hold expires, the seller sends the released money to another wallet, so that by the time the late repair arrives the money is gone. The output on the machine this chapter ran on:

answers by kind and first result: {'hold:created': 21346, 'hold:exceeds_credits': 249, 'plain:created': 58781, 'plain:exceeds_credits': 149, 'post:created': 20154, 'post:pending_transfer_not_found': 231, 'void:created': 686, 'void:pending_transfer_not_found': 12}
holds by final state: {'expired': 1012, 'posted': 40308, 'voided': 1372}
late confirmations: {'pending_transfer_expired': 506, 'repair: created': 326, 'repair: exceeds_credits': 185, 'pending_transfer_not_found': 6, 'repair: linked_event_failed': 1}
repairs booked 791,640,567 kobo; repairs refused 1,207,765,087 kobo; drained 1,991,644,098 kobo
accounts that differ from the generated entries (allowing for the drains): 411; kobo still reserved: 0

186 of the 512 repairs are refused, 185 with exceeds_credits and one on a later leg of its chain: ₦12,077,650.87 that the switch paid and the ledger cannot book without an overdraft. That is a reconciliation break and a loss, not a rounding difference. The wallets that did repay are short for what comes next (the hold:exceeds_credits, plain:exceeds_credits and post:pending_transfer_not_found lines are later genuine transfers refused), so 411 accounts end different from the books even after the drains are allowed for. Now shorten the day. In holds.py change LATE from 86_400 to 1_800, so the repair arrives after 30 minutes, and run python3 holds.py --drain again. The drain would come at 4,500 seconds, so the script skips it:

answers by kind and first result: {'hold:created': 21595, 'plain:created': 58930, 'post:created': 20385, 'void:created': 698}
holds by final state: {'expired': 1024, 'posted': 40770, 'voided': 1396}
late confirmations: {'pending_transfer_expired': 512, 'repair: created': 512}
repairs booked 1,999,405,654 kobo; repairs refused 0 kobo; drained 0 kobo
accounts that differ from the generated entries (allowing for the drains): 0; kobo still reserved: 0

The exposure window is the time between expiry and repair. Thirty minutes of it removes every refusal. The price is a requery of the switch for every unanswered payout within 30 minutes, instead of a daily reconciliation.

ARTEFACT Write the ledger design decision record ~50 MIN
YOU PRODUCEArchitecture decision record (ADR): ledger design

Template

# ADR <number>: <the decision in one line>
Status: proposed | accepted | superseded by <number>
Author: <staff engineer> · Accepted by: architecture review group · Finance sign-off: <controller>
Date: <date> · Review date: <date>
Decision needed: <what the reviewers must decide, and by when>

## Context
<What exists today, the incidents that forced the question, and what is out of scope.>

## Options considered
1. <Option> — <one line on what it is>
2. <Option> — ...
(Include the cheapest patch and "do nothing".)

## Decision drivers
| Driver | What we need | Evidence | Gap |
|---|---|---|---|
| Idempotency | | | |
| Pending transfers | | | |
| Immutability | | | |
| Throughput | | | |
| Operability | | | |

## Evidence from the lab
<Commands run, the exact figures printed, and what each shows. Say which are illustrative.>

## Decision
<One sentence, then the first step and its owner.>

## Consequences
- Easier: <...>
- Harder or new work: <...>
- Risks we accept: <...>

## What would make us revisit
- <Measurable trigger, who checks it, when>

## What this record cannot see
<One way it could be wrong, and what would show it.>
WORKED EXAMPLE

At a real company a staff engineer writes this record, the architecture review group accepts it, and the finance lead for payouts signs that the balance check meets finance’s needs.

ADR: Ojaline’s seller wallet moves to a transfer model, proven by replay before any engine is chosen. Author: Ebikabowei, an engineer on the replacement team. Accepted by: architecture review group. Finance sign-off: Chiagozie. Status: proposed, 2026-11-20. Review date: after the replay. Decision needed: build the model first?

Context. One balance column per seller, read then written. Three incidents (illustrative): a double tap paid ₦12,000 from ₦10,000; a ₦4,500 hold never released; a retry under a new reference paid twice.

Options. Replay through a small model first; a purpose-built ledger database now; the balance column plus a holds table and unique payout ids; an in-house append-only service.

Drivers and evidence (figures from the lab’s replay of Owoleaf’s books).

  • Idempotency: sending all 111,276 transfers twice gave 79,827 exists and 31,449 linked_event_failed, and every balance stayed the same.
  • The floor is not enough: 6,502 of 20,897 second payouts under new ids went through, 31.1%, ₦115,960,385.73 paid twice.
  • Pending transfers: 512 lost answers expired; ₦19,994,056.54 became spendable again until repair.
  • Immutability: check.py printed OK, all invariants hold, on a ledger built only from transfers.
  • Throughput: not measured. The lab model is one writer on SQLite.

Decision. Build client-chosen ids, holds with a timeout, a floor on wallet accounts only and corrections as new transfers as a model over the existing database, and choose an engine only after a quarter of Ojaline’s seller history replays with every seller’s balance matching. First step: Ebikabowei writes the model.

Consequences. Ids are stored before sending. The timeout becomes a business number. The ledger holds no seller names, so a standing comparison is needed.

Revisit if any seller’s debits or credits differ after the replay (Chiagozie checks, at week six), or a load test at Ojaline’s peak payout rate fails on one writer (Ebikabowei, before cut-over).

Could be wrong: the lab replayed Owoleaf’s books, not Ojaline’s. The quarter’s replay would show it.

Now you

Assume, for this exercise, that Owoleaf at 200 people will put every NIP payout behind a hold. You are the engineer asked to write the ADR for the hold timeout and the repair path. The lab’s step 5 used a 15-minute timeout, a late answer after a day, and illustrative timings. Run python3 holds.py and the --drain variant, then change LATE from 86_400 to 1_800 and run it again. Use the printed lines: 512 expired holds, ₦19,994,056.54 spendable again, 186 repairs refused with ₦12,077,650.87 unbookable, and none refused at 30 minutes. Compare at least three options, such as keeping the day, a 30-minute requery, and a longer timeout. State what each costs the team. Say what the lab cannot show about Owoleaf’s real switch answer times. If you cannot run the lab, use the figures printed above; the record needs no new code. Your readers are the architecture review group and the finance controller, and the record supports one decision: which timeout and repair window ship with the payout cut-over.

Self-check

DECIDE

Ojaline's seller wallet is one balance column per seller, a nightly job that releases earnings after delivery, and a withdraw call that reads the balance and then writes it. Ebikabowei has a quarter to replace it. Chiagozie, who runs finance operations for seller payouts, will not sign a cut-over that she cannot check balance by balance. Four routes are on the table. What does the team do first?

READING
  1. DOC
    Two-Phase Transfers (TigerBeetle documentation) TigerBeetle

    The vendor's own account of pending, post, void and timeout, with the rule that an expired transfer cannot be resolved. Read it beside steps 1 and 5 of the lab. This chapter confirmed the page from a search summary, and its behaviour is for the version the docs describe.

  2. DOC
    Transfer (TigerBeetle reference) TigerBeetle

    Every transfer field and flag, including the rule that transfers are immutable and have unique ids. Read the field table and the flags. Skip the imported-transfer material on a first pass.

  3. POST
    Books, an immutable double-entry accounting database service (Square) Square, 2019

    A payments company's account of a ledger in which balances change only through accounting transactions. Read it for the immutable design in its authors' words. It is Square's own description of its own service.

  4. POST
    Ledger: Stripe's system for tracking and validating money movement Stripe

    Stripe's engineering account of its ledger and the data quality checks beside it. Read it for the idea of measuring how much money movement a ledger can explain, and treat the figures as the vendor's claims about its own system.

  5. PAPER
    The Transaction Concept: Virtues and Limitations (Gray, Tandem technical report 81.3, VLDB 1981) Jim Gray, 1981

    The paper that states what a transaction promises. Read it for the all-or-nothing idea behind linked transfers and for what it says a transaction does not give you. The link is a Purdue course copy of the Tandem report; the VLDB version (pages 144 to 154) may differ slightly. Read: The sections on what a transaction guarantees and on its limitations.

  6. PAPER
    Immutability Changes Everything (Helland, CIDR 2015) Pat Helland, 2015

    The case for append-only data, with the accountant's habit of never erasing as its model. Read the section on accountants and erasers for the reason corrections are new transfers. The link is the Communications of the ACM reprint (2016) of the CIDR paper. Read: The section 'Accountants Don't Use Erasers'.

  7. DOC
    Jepsen: TigerBeetle 0.16.11 Jepsen

    A test of the same database by Jepsen, who do not sell it; the report says TigerBeetle, Inc. funded it. Read what it found and what it says about the single-core design. This chapter confirmed the page from a search summary and did not read it in full, and the analysis is of an earlier version than the one in the lab.

All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: Who is liable when an AI moves money: authorisation, consent and the rules not yet written →