# Mint PRD

Oct 8, 2026 · @Donna

## Overview

Mint is a digital wallet backend built on a double-entry ledger. Users hold accounts in a currency, deposit money in, withdraw it out, and transfer it to each other. Every movement of money is recorded as a balanced set of entries, so the ledger can always prove where every cent came from.

The point of Mint is correctness under real-world failure: two requests hitting the same account at once, a client retrying after a timeout, or a process dying halfway through a write. The core guarantees live in PostgreSQL itself, not only in application code.

The system is built in TypeScript with Fastify and PostgreSQL, and tested with Vitest against a real database.

## Problem

Moving money looks simple until something goes wrong. Most toy wallet backends store a balance column and add or subtract from it, which breaks in three common situations:

- **Races.** Two withdrawals read the same balance at the same time, both pass the funds check, and the account goes negative.
- **Retries.** A client times out and retries a transfer that actually succeeded, so the user is charged twice.
- **Partial failures.** A process crashes after debiting one account but before crediting the other, and money disappears.

On top of that, a single balance column has no history. When a number looks wrong, there is no way to rebuild it or prove it is right.

## Goals and non-goals

The MVP proves that a small ledger service can keep money conserved and balances correct under concurrency, retries, and crashes, and can prove it with tests.

**Goals**

- Record every money movement as a double-entry transaction whose entries sum to zero.
- Prevent overdrafts even when many requests hit one account at once.
- Make every write safe to retry with an idempotency key.
- Keep history append-only, so corrections are new transactions, never edits.
- Rebuild every balance from entries on demand and report any drift.

**Non-goals**

- Real payment rails (cards, bank transfers, Interac). Deposits and withdrawals move money against an internal external-funds account.
- Currency conversion. A transaction may only touch accounts in one currency.
- User authentication, KYC, or fraud checks.
- A consumer-facing app. Mint is an API.

## Users and user stories

The primary user is a client application (a wallet app or another service) that calls the Mint API. A secondary user is an operator who needs to audit the ledger.

| As a… | I want to… | So that… |
| --- | --- | --- |
| Client app | Create an account in a currency | A user can start holding money |
| Client app | Deposit, withdraw, and transfer with one API call each | I don't have to manage ledger entries myself |
| Client app | Retry a request safely after a timeout | A user is never charged twice |
| Client app | Get a clear error when funds are insufficient | I can show the user why a payment failed |
| Client app | Page through an account's entry history | A user can see their statement |
| Operator | Run a reconciliation over the whole ledger | I can prove cached balances match the entries |

## Functional requirements

P0 items are required for the MVP; P1 items follow once the core ledger is proven.

| ID | Requirement | Priority |
| --- | --- | --- |
| FR-1 | `POST /accounts` creates a user account with a name and a 3-letter currency code | P0 |
| FR-2 | `POST /deposits`, `/withdrawals`, and `/transfers` each post one balanced ledger transaction | P0 |
| FR-3 | Amounts are positive integers in minor units (cents); floats and zero are rejected | P0 |
| FR-4 | Every write requires an `Idempotency-Key` header (8–255 chars) | P0 |
| FR-5 | A replay with the same key and body returns `200` with the original result; a first request returns `201` | P0 |
| FR-6 | A reused key with a different body returns `409 IDEMPOTENCY_KEY_REUSED` | P0 |
| FR-7 | A withdrawal or transfer that would make a user account negative returns `INSUFFICIENT_FUNDS` and writes nothing | P0 |
| FR-8 | Transfers between accounts in different currencies, or to the same account, are rejected | P0 |
| FR-9 | `GET /accounts/:id/entries` returns entries newest-first with `limit` and `before` cursor paging | P0 |
| FR-10 | `GET /admin/reconcile` reports balance drift, unbalanced transactions, and per-currency totals | P0 |
| FR-11 | Errors use one shape: `{ "error": { "code", "message" } }` | P0 |
| FR-12 | Reversals: a refund endpoint that posts a new transaction undoing an earlier one | P1 |
| FR-13 | Holds: reserve funds for a pending payment, then capture or release | P1 |
| FR-14 | API keys so only known clients can call write endpoints | P1 |
| FR-15 | Metrics and structured logs for latency, retries, and conflict rates | P1 |

## System architecture

```mermaid
flowchart LR
  C[Client app] -->|HTTP + Idempotency-Key| A[Fastify API<br/>src/app.ts]
  A --> L[Ledger service<br/>src/ledger.ts]
  L -->|withTransaction + retry| P[(PostgreSQL)]
  P --- T1[CHECK balance >= 0]
  P --- T2[Deferred trigger:<br/>entries sum to 0]
  P --- T3[Trigger:<br/>entries append-only]
  O[Operator] -->|GET /admin/reconcile| A
```

The API validates the request and hands it to the ledger service. The ledger opens one database transaction per request, and PostgreSQL enforces the final safety net: constraints and triggers reject any write that would break a guarantee, even from raw SQL.

## Data model

| Table | Purpose | Key fields |
| --- | --- | --- |
| `accounts` | One wallet per row, user or system | `currency`, `kind`, `allow_negative`, cached `balance` |
| `ledger_transactions` | One row per money movement | `kind`, unique `idempotency_key`, `request_hash` |
| `entries` | Signed amounts against accounts | `transaction_id`, `account_id`, `amount`, `balance_after` |

Deposits and withdrawals move money against one **external** system account per currency. It goes negative as money enters Mint, so the ledger as a whole always sums to zero.

## How a write stays correct

Each money movement runs as one database transaction:

1. **Claim the idempotency key.** Insert the transaction row first. If the key already exists, a concurrent duplicate waits on the unique index, then replays the stored result (or returns `409` if the body hash differs).
2. **Lock accounts in id order.** `SELECT … FOR UPDATE` on every touched account, sorted by id, so opposite transfers (A→B and B→A) can't deadlock.
3. **Check and write.** Reject if a user balance would go negative, then update cached balances and insert entries.
4. **Commit.** Deferred triggers check that the entries sum to zero and use one currency. Any failure rolls back the whole thing, so a rejected request leaves no trace.
5. **Retry transient conflicts.** Deadlock and serialization failures are retried with jittered backoff.

## Success metrics

The MVP succeeds if the guarantees hold under the stress tests and reconciliation always comes back clean.

| Metric | Target | How it's measured |
| --- | --- | --- |
| Money conservation | Ledger sums to 0 per currency after every test run | `GET /admin/reconcile` → `ok: true` |
| Overdraft safety | 0 negative user balances across 100 racing withdrawals | `concurrency.test.ts` |
| Retry safety | 50 concurrent duplicate requests post exactly once | `idempotency.test.ts` |
| Database enforcement | Raw SQL can't unbalance, edit history, or overdraw | `database-guarantees.test.ts` |
| Consistency under load | 400 random concurrent transfers reconcile with 0 drift | `concurrency.test.ts` |
| Latency | p95 transfer under 50 ms on local Postgres (proposed) | Load test, to add |

## Milestones

| # | Milestone | Status |
| --- | --- | --- |
| M1 | Ledger core: schema, double-entry posting, deposits, withdrawals, transfers | Done |
| M2 | Concurrency: row locks in fixed order, deadlock retry, overdraft constraint | Done |
| M3 | Retry safety: idempotency keys, request hashing, replay, reconciliation | Done |
| M4 | Reversals and holds (FR-12, FR-13) | Proposed |
| M5 | API keys, metrics, and logging (FR-14, FR-15) | Proposed |
| M6 | Load test, docs, and deploy | Proposed |

## Risks and open questions

The biggest risk is a guarantee that holds in the happy path but breaks under a race nobody tested.

| Risk | Mitigation |
| --- | --- |
| The external account row becomes a hot lock under heavy deposit traffic | Measure under load; consider sharded system accounts per currency |
| Cached balances drift from entries after a bug | Reconcile on demand; consider a scheduled reconcile with alerts |
| Idempotency keys grow forever | Add a retention window and document how long replays are guaranteed |
| JavaScript numbers lose precision above 2^53 cents | `Number.isSafeInteger` check on amounts; switch to `bigint` if limits grow |
| Retry loop hides a real bug as a "transient" conflict | Cap retries and log every retried error code |

**Open questions**

- How long should idempotency keys be kept before they can be reused?
- Should reconciliation run on a schedule, and who gets alerted on drift?
- Do holds belong in Mint, or in a separate payments layer on top of it?
- Is multi-currency (with FX) ever in scope, or is one currency per transaction a permanent rule?
