feat(api): wallet ledger with database-enforced race protection (#23) #88

Merged
amiryahaya merged 1 commit from feat/wallet-ledger into main 2026-10-23 12:39:43 +02:00
Owner

Closes #23. First P2 (money core) PR.

What

Customer and organization wallets with an append-only ledger, protected against race conditions by the database itself.

Guard rails (migration 0010; they hold even if Go code is wrong, a second service is added, or someone runs SQL by hand)

  1. wallets.balance can only change as a side effect of a ledger insert. A direct UPDATE, or opening a wallet with money in it, is rejected.
  2. The ledger insert takes the wallet's row lock, computes balance_after itself (a writer's own figure is ignored) and refuses a payment larger than the balance. Concurrent inserts for one wallet queue on the lock. The same trigger numbers each wallet's entries 1, 2, 3... without gaps.
  3. The ledger is append-only (update, delete and truncate rejected). balance >= 0 is also a CHECK. A wallet_balance_drift view proves balance = sum of entries.

The Go layer (internal/wallet) adds

currency must match the wallet (legacy debited without checking); idempotent operations by key (a retried payment, top-up or refund returns the original entry and changes nothing; the same key with a different amount is refused); an overdraft returns ErrInsufficientFunds without poisoning the caller's transaction; a 3 s lock wait then ErrBusy (retry) instead of a hang; Apply runs inside the caller's transaction so a wallet change commits or rolls back with the transaction and tickets (R-WAL-2).

Customer API (spec + contract tests updated, 77 operations)

GET /v1/me/wallets, GET /v1/me/wallets/{id}/entries?limit&before (cursor by entry number). The owner always comes from the authenticated user; another customer's wallet is a 404, not a 403. Never cached.

Answering "does the lock hurt at 1,000 concurrent users?" (measured, BenchmarkWalletPayments)

throughput latency p50 / p99
1,000 customers pay at the same instant, own wallets ~3,700/s 109 / 259 ms
ONE hot wallet, 200 concurrent payers ~680/s 220 / 294 ms
ONE hot wallet, 20 payers x 25 back to back ~850/s 12 / 81 ms
The lock is per wallet, so different customers never contend; latency is waiting for one of 20 connections. One wallet serialises at ~1.2-1.5 ms per payment. Laptop numbers; rerun on the real servers. With synchronous replication a hot wallet's ceiling is about 1 / commit time (~300/s at 3 ms): still ample.

Modern Treasury (row locks on user accounts, async for hot shared accounts), Brandur on Stripe (idempotency keys), PostgreSQL SSI, TigerBeetle (single-threaded batching, two-phase pending transfers). Conclusion: a short row lock is the standard answer for user balances; optimistic locking, SERIALIZABLE, queue-per-account and holds solve other problems or need infrastructure we do not have. Mostly vendor docs and blogs, not independent studies.

Standards review (docs/development-standards.md)

  • TDD: schema, domain, store, race and handler tests first. A hang I caused in a test (a user created inside a one-connection transaction) and a wrong test case (PostgreSQL rounds 1.005 silently) were fixed in the tests, not the schema.
  • Mutation checks, each fails for the intended reason: the trigger reading the balance without its lock -> raw-SQL race test: "won 8, refused 0" (should be 30); guard 1 removed -> four direct-update checks fail; the database trusting a writer's balance_after -> fails; the app skipping its overdraft check -> "current transaction is aborted".
  • SOLID / coupling: Ledger, Provisioner and Reader are separate narrow interfaces; the domain has no SQL; checkout will depend on Ledger only.
  • Coverage: 94.6% total; wallet 91.8%, wallet store 85.6%. make lint 0 issues. Both generated clients still compile. Security scans run on main after merge.

Rules for callers (ADR 0007, CLAUDE.md)

No slow work between taking a wallet lock and committing; one wallet per transaction, or several in ascending id order; no running totals; no per-sale update of a shared balance.

Not in this PR

HTTP-level idempotency keys (#24), organization wallet endpoints (organizations, #37), manual adjustments, two-phase holds, a drift alert job, wiring wallet payment into checkout (#26/#30).

🤖 Generated with Claude Code

Closes #23. First P2 (money core) PR. ## What Customer and organization wallets with an append-only ledger, protected against race conditions **by the database itself**. ### Guard rails (migration 0010; they hold even if Go code is wrong, a second service is added, or someone runs SQL by hand) 1. **`wallets.balance` can only change as a side effect of a ledger insert.** A direct `UPDATE`, or opening a wallet with money in it, is rejected. 2. **The ledger insert takes the wallet's row lock, computes `balance_after` itself** (a writer's own figure is ignored) **and refuses a payment larger than the balance.** Concurrent inserts for one wallet queue on the lock. The same trigger numbers each wallet's entries 1, 2, 3... without gaps. 3. **The ledger is append-only** (update, delete and truncate rejected). `balance >= 0` is also a CHECK. A `wallet_balance_drift` view proves balance = sum of entries. ### The Go layer (`internal/wallet`) adds currency must match the wallet (legacy debited without checking); **idempotent operations by key** (a retried payment, top-up or refund returns the original entry and changes nothing; the same key with a different amount is refused); an overdraft returns `ErrInsufficientFunds` **without poisoning the caller's transaction**; a **3 s lock wait** then `ErrBusy` (retry) instead of a hang; **`Apply` runs inside the caller's transaction** so a wallet change commits or rolls back with the transaction and tickets (R-WAL-2). ### Customer API (spec + contract tests updated, 77 operations) `GET /v1/me/wallets`, `GET /v1/me/wallets/{id}/entries?limit&before` (cursor by entry number). The owner always comes from the authenticated user; **another customer's wallet is a 404**, not a 403. Never cached. ## Answering "does the lock hurt at 1,000 concurrent users?" (measured, `BenchmarkWalletPayments`) | | throughput | latency p50 / p99 | |---|---|---| | 1,000 customers pay at the same instant, own wallets | ~3,700/s | 109 / 259 ms | | ONE hot wallet, 200 concurrent payers | ~680/s | 220 / 294 ms | | ONE hot wallet, 20 payers x 25 back to back | ~850/s | 12 / 81 ms | The lock is per wallet, so different customers never contend; latency is waiting for one of 20 connections. One wallet serialises at ~1.2-1.5 ms per payment. Laptop numbers; rerun on the real servers. With synchronous replication a hot wallet's ceiling is about 1 / commit time (~300/s at 3 ms): still ample. ## Research: how other systems handle this (ADR 0007 has the table and links) Modern Treasury (row locks on user accounts, async for hot shared accounts), Brandur on Stripe (idempotency keys), PostgreSQL SSI, TigerBeetle (single-threaded batching, two-phase pending transfers). Conclusion: a short row lock is the standard answer for user balances; optimistic locking, SERIALIZABLE, queue-per-account and holds solve other problems or need infrastructure we do not have. Mostly vendor docs and blogs, not independent studies. ## Standards review (docs/development-standards.md) - **TDD**: schema, domain, store, race and handler tests first. A hang I caused in a test (a user created inside a one-connection transaction) and a wrong test case (PostgreSQL rounds `1.005` silently) were fixed in the tests, not the schema. - **Mutation checks, each fails for the intended reason**: the trigger reading the balance without its lock -> raw-SQL race test: "won 8, refused 0" (should be 30); guard 1 removed -> four direct-update checks fail; the database trusting a writer's `balance_after` -> fails; the app skipping its overdraft check -> "current transaction is aborted". - **SOLID / coupling**: `Ledger`, `Provisioner` and `Reader` are separate narrow interfaces; the domain has no SQL; checkout will depend on `Ledger` only. - **Coverage**: 94.6% total; wallet 91.8%, wallet store 85.6%. `make lint` 0 issues. Both generated clients still compile. Security scans run on `main` after merge. ## Rules for callers (ADR 0007, CLAUDE.md) No slow work between taking a wallet lock and committing; one wallet per transaction, or several in ascending id order; no running totals; no per-sale update of a shared balance. ## Not in this PR HTTP-level idempotency keys (#24), organization wallet endpoints (organizations, #37), manual adjustments, two-phase holds, a drift alert job, wiring wallet payment into checkout (#26/#30). 🤖 Generated with [Claude Code](https://claude.com/claude-code)
feat(api): wallet ledger with database-enforced race protection (closes #23)
All checks were successful
ci / changes (pull_request) Successful in 11s
ci / clients (pull_request) Successful in 2m3s
ci / api (pull_request) Successful in 7m34s
ci / ci-gate (pull_request) Successful in 5s
2d2bcb4d87
Migration 0010: wallets and an append-only wallet_ledger. The ledger insert takes the wallet row lock,
computes balance_after and the gap-free per-wallet seq itself, and refuses an overdraft; wallets.balance can
change only through the ledger; a drift view proves balance = sum of entries. internal/wallet adds the
currency check, idempotent replay by operation key, a 3 s lock wait (ErrBusy), Apply inside the caller's
transaction, and a customer read API (/v1/me/wallets, statement with cursor). ADR 0007 records the design,
the research on how other ledgers handle this, and the measured cost of the lock.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Sign in to join this conversation.
No reviewers
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
primatekuntech/kws!88
No description provided.