Skip to content

About

A double-entry ledger in Go that never loses a cent: idempotent transfers, ordered row locks, append-only postings on Postgres.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

ledger-service

A double-entry ledger in Go that never loses a cent: idempotent transfers, ordered row locks, append-only postings on Postgres.

CI License: MIT Go 1.27.4 Go Report Card

A double-entry accounting ledger as a Go microservice: every movement of money is an idempotent transfer that writes two balanced postings and both account balances in one Postgres transaction.

Transfers can be reversed exactly once with a compensating transfer. This is the kind of service that sits under a payments or wallet product: the part that has to be correct under concurrency, not just fast. The HTTP contract is api/openapi.yaml.

At a glance (details in Tests and Load):

Check Result
Concurrency test 40 goroutines transferring in both directions; total balance is conserved and never goes negative (CI, -race, real Postgres)
Load, 500 accounts ~2,300-2,400 transfers/sec median on an Apple M2 Pro laptop, single instance (recorded 2026-10-19, see BENCHMARKS.md)
Load, 50 hot accounts ~1,450-1,800 transfers/sec (recorded 2026-10-19)
Balance drift zero errors and zero drift across ~365k transfers (recorded 2026-10-19)

Why this exists

Moving money looks simple until two requests hit the same accounts at once, a client retries after a timeout, or a refund races the original payment. This repository shows one way to get those cases right with nothing more than Postgres: integer minor units, ordered row locks, idempotency keys enforced by a unique index, an append-only postings table and database CHECK constraints behind the application checks.

Most of my other repositories are Python machine-learning and agent work; this is the backend-systems piece — a small Go service whose whole job is to move money under concurrency without losing or duplicating a cent.

Architecture

flowchart LR
    C["Client"] -->|"HTTP + Idempotency-Key"| R["internal/httpapi<br/>chi router, auth, request id, metrics"]
    R --> S["internal/ledger<br/>Service: accounts, transfers, reversals"]
    S -->|"pgx tx: SELECT ... FOR UPDATE<br/>lowest id first"| DB[("Postgres<br/>accounts, transfers, postings")]
    M["cmd/ledger<br/>config, pool, migrate, serve"] --> ST["internal/store<br/>pgx pool + embedded SQL migrations"]
    ST --> DB
    M --> R
    R -->|"/metrics"| P["Prometheus"]
Loading

A transfer runs in one read-committed transaction: both account rows are locked in a fixed order, the two postings are inserted, both balances are updated, and a duplicate Idempotency-Key returns the original transfer instead of moving funds twice. A serialization failure or deadlock restarts the transaction, up to five attempts.

Why it's built this way

Concern Approach
Money int64 minor units and an ISO-4217 currency string. Balances, postings and transfer arithmetic never touch floating point. (Prometheus histograms observe amounts as float64, as that API requires — that is metrics, not the money path.)
Balanced books Two postings per transfer, equal and opposite. postings is append-only. accounts.balance is a cached running total mutated only in the same transaction as its postings, so it can never drift from SUM(postings).
Concurrency Both account rows are taken with SELECT ... FOR UPDATE in a deterministic order (lowest UUID first). Concurrent transfers over the same pair serialize on the row locks and cannot deadlock. Serialization failures (40001) and deadlocks (40P01) are retried with backoff.
Idempotency transfers.idempotency_key is UNIQUE. A retried request with the same key and body returns the original transfer; the same key with a different body is a 409. The unique-violation race is handled.
Reversals A reversal is a normal transfer in the opposite direction, tagged reverses_transfer_id. A partial unique index guarantees at most one reversal per original, even under concurrency; the original flips to status = 'reversed' in the same transaction.
Invariants at the edge DB CHECK constraints (amount > 0, balance >= 0 unless overdraft, distinct debit/credit accounts) back up the application checks.
Migrations Plain .sql files embedded with go:embed, applied on startup, tracked in schema_migrations.

API

Full contract: api/openapi.yaml, also served live at GET /openapi.yaml.

Method Path Notes
POST /v1/accounts {name, currency, allow_overdraft?} → 201
GET /v1/accounts list, newest-first, ?limit=&cursor=
GET /v1/accounts/{id} account with current balance
GET /v1/accounts/{id}/postings ?limit=&before= — keyset on posting id
POST /v1/transfers requires Idempotency-Key header
GET /v1/transfers list, ?account_id=&limit=&cursor=
GET /v1/transfers/{id} transfer by id
GET /v1/transfers/{id}/postings the two postings for the transfer
POST /v1/transfers/{id}/reversals requires Idempotency-Key; posts a compensating transfer
GET /healthz · /readyz · /version liveness · readiness (pings DB) · build info
GET /metrics Prometheus (HTTP + business metrics)

Errors are always {"error": {"code": "...", "message": "..."}} with a stable code. List responses are {"data": [...], "next_cursor": "..."} (next_cursor is empty at the end). Request bodies are capped at 1 MiB and unknown JSON fields are rejected.

Example

SRC=$(curl -s localhost:8080/v1/accounts -d '{"name":"treasury","currency":"USD","allow_overdraft":true}' | jq -r .id)
DST=$(curl -s localhost:8080/v1/accounts -d '{"name":"merchant","currency":"USD"}' | jq -r .id)

# move $25.00 — retrying this exact call is safe, funds move once
TR=$(curl -s localhost:8080/v1/transfers -H "Idempotency-Key: order-1001" \
  -d "{\"debit_account_id\":\"$SRC\",\"credit_account_id\":\"$DST\",\"amount\":2500,\"currency\":\"USD\"}" | jq -r .id)

curl -s localhost:8080/v1/accounts/$DST | jq .balance          # 2500

# refund it — balances return to 0, original becomes "reversed"
curl -s -X POST localhost:8080/v1/transfers/$TR/reversals -H "Idempotency-Key: refund-1001"
curl -s localhost:8080/v1/accounts/$DST | jq .balance          # 0

Quickstart

docker compose up --build        # ledger on :8080, Postgres on :5432

Or locally against your own Postgres:

export DATABASE_URL='postgres://ledger:ledger@localhost:5432/ledger?sslmode=disable'
make run

Without DATABASE_URL, make run uses the make dev-db Postgres on :55432.

Configuration (environment)

Var Default
DATABASE_URL — required
LEDGER_ADDR :8080 listen address
LOG_LEVEL info debug / info / warn / error
SHUTDOWN_TIMEOUT 15s graceful-shutdown budget
REQUEST_TIMEOUT 10s per-request deadline
DB_MAX_CONNS / DB_MIN_CONNS 10 / 0 pool sizing
LEDGER_API_TOKENS — comma-separated bearer tokens; when set, /v1/* requires Authorization: Bearer <token>

Operational endpoints (/healthz, /readyz, /version, /metrics, /openapi.yaml) are always unauthenticated. See SECURITY.md.

Tests

make dev-db        # throwaway Postgres on :55432
make test          # unit + Postgres-backed integration, with -race
make dev-db-stop

internal/money and internal/config are pure unit tests. internal/httpapi tests the HTTP layer against an in-memory fake (routing, error mapping, idempotency headers, bearer auth, metrics, OpenAPI serving). internal/ledger has database-free unit tests for its pure helpers (lock ordering, the keyset cursor and its malformed-input paths, pagination, retry and validation predicates), plus an integration suite that runs against a real Postgres (TEST_DATABASE_URL; skipped with a message when unset, or failed when REQUIRE_DB_TESTS=1, which CI sets) and covers transfers and balance math, insufficient funds, currency mismatch, idempotent replay, idempotency conflict, reversals (restore balances, replay, already-reversed, reverse-a-reversal), keyset pagination, and a 40-goroutine concurrent bidirectional transfer test that asserts total balance is conserved and never goes negative. CI runs the full suite with -race against a Postgres service container, plus golangci-lint, govulncheck, and a container smoke test on every push.

Load

loadtest/ drives a running instance with concurrent transfers and checks balance conservation after every run. Measured on an Apple M2 Pro laptop (single instance, Postgres 16 in Docker, loadtest on the same machine), 3 runs of 15 s each: ~1,450-1,800 transfers/sec with 50 hot accounts and ~2,300-2,400 transfers/sec (median; best single run 2,950) with 500 accounts, with zero errors and zero balance drift across ~365k transfers. The write path scales with account spread (row-lock contention), and the service held at ~12 goroutines / ~42 MB RSS. Run-to-run spread is wide, so see the ranges, hardware and method in BENCHMARKS.md; re-measure with make bench.

Layout

api/                   OpenAPI 3.1 spec (embedded + served)
cmd/ledger/            entrypoint: config, pool, migrate, serve, graceful shutdown
loadtest/              concurrent-transfer load generator + balance-conservation check
internal/config/       env configuration
internal/money/        integer-minor-unit money type + parsing
internal/store/        pgx pool + embedded SQL migrator
internal/ledger/       the domain: accounts, transfers, reversals, postings, pagination
internal/httpapi/      chi router, handlers, middleware (request id, recover, auth, metrics)

Limitations and what I would improve next

  • Transfers are strictly two-legged; multi-leg entries (fees, splits) would need a postings model with more than one debit or credit per transfer.
  • There is no pending or held state: a transfer is posted or reversed. Authorisation holds would need a separate state and expiry.
  • Authorization is a static bearer-token list. Which token may touch which account, and rate limiting, are left to a layer in front of the service (see SECURITY.md).
  • Load numbers come from one laptop with the load generator on the same machine; a run on separate hosts with a managed Postgres would give a fairer ceiling.
  • Downstream consumers have to poll; an outbox table that publishes posted transfers would let them subscribe instead.

License

MIT


Part of Nagizaaz Shaik's open-source work · all repositories

About

A double-entry ledger in Go that never loses a cent: idempotent transfers, ordered row locks, append-only postings on Postgres.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages