← All Articles

SQLite & Backend

Token Spend Ledgers: Double-Entry Cost Accounting for Every LLM Call in Python

Treating model spend like money, not metrics: an append-only, balanced ledger that reconciles provider invoices to the cent and halts runaway agents before the bill does.

By Tharusha Nuwansara · Nov 19, 2026 · 6 min read

Why Usage Dashboards Drift From the Invoice

Most teams track LLM spend as a counter: increment a metric after each response, chart it, and hope it matches the provider invoice at month end. It rarely does. Retries are double-counted or never counted, streaming responses that are cancelled mid-flight still bill for generated tokens, and price changes silently re-weight historic usage.

A ledger fixes this by recording every movement of value as a balanced pair of entries. Spend is never inferred; it is posted, and the books must sum to zero.

  • Append-only: corrections are new reversing entries, never updates.
  • Idempotent: each provider request id posts exactly once.
  • Priced at call time: the rate card in force is frozen into the entry.

The Balanced Ledger Model

Each call debits an agent:<name> expense account and credits a budget:monthly account. The unique constraint on the request id gives us idempotency for free.

import sqlite3
from decimal import Decimal

SCHEMA = """
CREATE TABLE IF NOT EXISTS entries (
    request_id TEXT NOT NULL,
    account    TEXT NOT NULL,
    amount_usd TEXT NOT NULL,
    UNIQUE (request_id, account)
);
"""

PRICE_PER_1K = {"small": Decimal("0.00015"), "large": Decimal("0.0025")}


def post_call(db, request_id, agent, model, tokens):
    cost = (PRICE_PER_1K[model] * Decimal(tokens) / 1000).quantize(Decimal("0.000001"))
    with db:
        db.executemany(
            "INSERT OR IGNORE INTO entries VALUES (?, ?, ?)",
            [
                (request_id, "agent:" + agent, str(cost)),
                (request_id, "budget:monthly", str(-cost)),
            ],
        )
    return cost


def trial_balance(db):
    rows = db.execute("SELECT amount_usd FROM entries").fetchall()
    return sum((Decimal(r[0]) for r in rows), Decimal("0"))


db = sqlite3.connect(":memory:")
db.executescript(SCHEMA)
post_call(db, "req_001", "triage", "small", 1800)
post_call(db, "req_001", "triage", "small", 1800)  # retry: ignored
post_call(db, "req_002", "planner", "large", 4200)
print("balance:", trial_balance(db))

A Hard Budget Guard Before Each Call

Because spend lives in the same database as the agent state, a guard can refuse a call before it is made, using a worst-case estimate of the prompt plus the maximum completion length.

from decimal import Decimal


class BudgetExceeded(RuntimeError):
    pass


def spent(db, agent):
    row = db.execute(
        "SELECT COALESCE(SUM(CAST(amount_usd AS REAL)), 0) FROM entries WHERE account = ?",
        ("agent:" + agent,),
    ).fetchone()
    return Decimal(str(row[0]))


def guard(db, agent, worst_case_usd, cap_usd=Decimal("5.00")):
    if spent(db, agent) + worst_case_usd > cap_usd:
        raise BudgetExceeded(agent + " would exceed its cap")


guard(db, "planner", Decimal("0.02"))
print("planner spent:", spent(db, "planner"))

Captured Sandbox Output

balance: 0
planner spent: 0.0105

The trial balance is exactly zero even though req_001 was posted twice: the retry was absorbed by the unique constraint rather than inflating spend.

Ship the Ledger in Production

Run a nightly reconciliation that compares the ledger total per model against the provider usage export. Any non-zero difference is a bug in your instrumentation, and you now have the request ids to find it.