Mini Ledger Service: Credits, Debits and Safe Balances
System DesignModel answerLast updated
Design and build a small full-stack ledger app with an API, storage, a basic UI and tests that records credits and debits and never lets an account balance drop below zero.
Mini Ledger Service
You are asked to build a small web application, using any AI coding assistant you like, that tracks money moving in and out of accounts. The goal is a working, well-reasoned vertical slice rather than a polished product.
What the app must do
- Offer an HTTP API (REST or GraphQL) to record a credit (adds funds) or a debit (removes funds) against an account and to read the account's current balance.
- Store data durably. An in-memory store or a lightweight embedded database is acceptable.
- Provide a simple frontend where a user can submit a transaction and see the account balance and its transaction history.
- Validate every input on the server (transaction type, amount, account existence, field lengths).
- Guarantee that an account balance never goes negative, including when several requests arrive at the same time.
- Include a basic automated test suite.
- Supply setup instructions and a short README.
What to cover in your answer
Describe how you would approach this as a time-boxed exercise (about an hour). Your answer should address:
- The assumptions and scope you would state up front.
- Technology choices and why.
- API endpoints, request/response shapes and error codes.
- The data model and how you represent money.
- How you prevent overdrafts under concurrent requests, and how you make client retries safe.
- What the frontend needs to contain.
- Which tests you would write.
- How you would supervise the AI tool and verify what it produces.
- What you would change to take this to production.
Hints
Hint 1
Decide how money is stored before anything else: think about what goes wrong with floating-point arithmetic, and pick a representation that is exact.
Hint 2
A check-then-write sequence (read the balance, compare in application code, then write) is racy. Look for a way to make the check and the update one atomic operation inside a database transaction, and back it with a database constraint.
Hint 3
Clients retry on timeouts. Consider a client-supplied idempotency key with a uniqueness constraint so a repeated debit is applied only once, and write a concurrency test that fires many parallel debits at one account.
Hint 4
When using an AI tool, review its output specifically for float amounts, missing validation, unchecked balance logic and absent tests, then prompt it to fix each issue.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Overview
The exercise is small, so the priorities are: scope quickly, get the money handling right, and stay in control of the AI tool rather than accepting whatever it generates. I would treat it as a miniature system design followed by an implementation.
1. Assumptions (first few minutes)
- Multiple accounts, created through the API, starting at balance 0.
- Credit adds, debit subtracts. Transfers are out of scope (I would mention they are two ledger entries in one DB transaction).
- Single currency, no authentication (flagged as a production gap), single node.
- Non-functional rules: balances never negative even under concurrency, and retries never double-apply.
2. Stack
- Backend: FastAPI with Pydantic for validation.
- Database: SQLite. It is persistent, needs no setup, and supports real transactions and
CHECKconstraints, so I can demonstrate atomicity. - Frontend: one small page (plain HTML/JS served by the backend, or a Vite React page) with a form, a balance display and a history list.
- Tests: pytest with FastAPI's
TestClient.
3. API
POST /accounts {name} -> 201 account
GET /accounts/{id} -> 200 account
POST /accounts/{id}/transactions {type, amount_cents, description}
Header: Idempotency-Key -> 201 transaction
GET /accounts/{id}/transactions?limit=50&before_id=N -> 200 list
| Status | Meaning |
|---|---|
| 422 | Invalid input (amount ≤ 0, unknown type, amount above a cap, wrong types) |
| 404 | Unknown account |
| 409 | Insufficient funds, body includes the current balance |
| 201 with original body | Replayed idempotency key |
4. Data model
CREATE TABLE accounts (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
balance_cents INTEGER NOT NULL DEFAULT 0 CHECK (balance_cents >= 0),
created_at TEXT NOT NULL
);
CREATE TABLE transactions (
id INTEGER PRIMARY KEY,
account_id INTEGER NOT NULL REFERENCES accounts(id),
type TEXT NOT NULL CHECK (type IN ('credit','debit')),
amount_cents INTEGER NOT NULL CHECK (amount_cents > 0),
balance_after_cents INTEGER NOT NULL,
description TEXT,
idempotency_key TEXT,
created_at TEXT NOT NULL,
UNIQUE (account_id, idempotency_key)
);
Decisions worth stating:
- Integer minor units (cents). Floats cannot represent most decimals exactly (
0.1 + 0.2 != 0.3). AI tools frequently default tofloat, so I check for it. - Append-only ledger. Rows are never edited or deleted; corrections are new entries.
- Cached balance on the account gives O(1) reads. A test or reconciliation job checks that it equals credits minus debits.
- Defense in depth. The
CHECK (balance_cents >= 0)constraint protects against application bugs.
5. Preventing overdrafts under concurrency
The naive flow (read balance, compare in Python, write) lets two simultaneous 80-unit debits both pass against a balance of 100. The fix is to make check and update one atomic statement inside a DB transaction that also writes the ledger row:
def create_transaction(conn, account_id, tx_type, amount, desc, key):
with conn: # one transaction; use BEGIN IMMEDIATE in SQLite
if key:
row = conn.execute(
"SELECT * FROM transactions WHERE account_id=? AND idempotency_key=?",
(account_id, key)).fetchone()
if row:
return row
delta = amount if tx_type == "credit" else -amount
cur = conn.execute(
"""UPDATE accounts SET balance_cents = balance_cents + ?
WHERE id = ? AND balance_cents + ? >= 0
RETURNING balance_cents""",
(delta, account_id, delta))
new_bal = cur.fetchone()
if new_bal is None:
exists = conn.execute("SELECT 1 FROM accounts WHERE id=?", (account_id,)).fetchone()
raise NotFound() if not exists else InsufficientFunds()
conn.execute(
"""INSERT INTO transactions
(account_id,type,amount_cents,balance_after_cents,description,idempotency_key,created_at)
VALUES (?,?,?,?,?,?,datetime('now'))""",
(account_id, tx_type, amount, new_bal[0], desc, key))
The conditional UPDATE takes the write lock and checks and changes the balance in one step. If the ledger insert fails, the whole transaction rolls back. On Postgres I would use the same conditional update or SELECT ... FOR UPDATE on the account row.
6. Idempotency
Clients retry after timeouts, and a retried debit must not apply twice. The Idempotency-Key header plus the unique constraint, checked inside the same transaction, returns the original result on replay. A production refinement is storing a hash of the request so a reused key with a different payload yields 422.
7. Validation
Use strict Pydantic models: type: Literal["credit","debit"], amount_cents: int = Field(gt=0, le=1_000_000_000), description with a max length. Reject booleans and numeric strings. Client-side checks (including converting dollars to cents by string parsing, not parseFloat * 100) are UX only; the server is the source of truth.
8. Frontend
A page with an account picker/create button, a balance display, a form (type, amount, description) and a history list. It shows server error messages (for example insufficient funds), disables the button while a request is in flight, and generates one idempotency key per submission attempt.
9. Tests
- Credit then debit updates balance and history correctly.
- Debit larger than balance returns 409 and changes nothing.
- Invalid payloads (zero, negative, float, bad type, unknown account) return 422/404.
- Replaying the same idempotency key creates one transaction.
- Concurrency: fire, say, 20 parallel debits of 10 at a balance of 100 and assert exactly 10 succeed and the final balance is 0.
- Invariant: balance equals the sum of credits minus debits.
10. Working with the AI tool
- Give it the schema, API contract and invariants up front rather than asking for "an app".
- Build in small steps (schema, then service logic, then endpoints, then UI, then tests) and read every diff.
- Specifically check for float money, check-then-write logic, missing validation, swallowed errors and tests that only cover the happy path.
- Run the tests yourself and be able to explain every line.
11. Production gaps
Authentication and authorization, audit logging, Postgres with migrations, rate limiting, request hashing for idempotency, pagination hardening, multi-currency, transfers as paired ledger entries, and periodic reconciliation.
Common mistakes
- Using floats for money.
- Checking the balance in application code before a separate write.
- Forgetting that retries need idempotency.
- Trusting client-side validation.
- Accepting AI output without tests, especially a concurrency test.
- Spending the time on UI polish while the money logic is wrong.