Building a PostgreSQL Double-Entry Ledger with Database Constraints

Payments

Build a PostgreSQL double-entry ledger with deferred balance checks, safe retries and append-only posting history. See how to model holds and reconciliation.

TL;DR

  • A PostgreSQL double-entry ledger represents each financial event as a journal with signed postings. Each posting belongs to one account, ledger and currency. The database rejects an empty, one-sided or mismatched journal at transaction end. An account balance can be calculated again from the same postings even if a read model or reporting database is rebuilt.
  • Use a unique request key on the journal and only expose a restricted posting function to the application. The same key and request body return the original journal on retry. Reverse a mistake with another journal. Keep external payment status, settlement and reconciliation separate from the internal accounting invariant.
  • Balance conservation and spending limits are separate controls. A perfectly balanced journal can still overdraw a wallet. If available funds matter, protect the available balance and holds with transactional updates and a consistent lock order. Measure contention on your busiest accounts before bringing that policy onto the payment path.

Why a balance column cannot explain money movement

Imagine a marketplace that charges a buyer USD 100.00. The processor confirms the capture, a seller is owed USD 97.00, and the platform earns USD 3.00. An integration worker records the capture. Its database commit succeeds, but the connection closes before the worker receives a response. The worker retries, while a scheduled payout is also inspecting available funds. Support needs to answer what happened without reconstructing a timeline from logs that may already have rotated.

A stored balance can be updated safely with an atomic SQL statement. The harder problem is that a balance alone cannot explain which business events produced it. Two systems can report the same balance after missing both a credit and a debit. A static total has nowhere to put the processor reference, the reason for a correction or the relationship between the three sides of that capture. A last-write-wins update introduces an additional bug when two workers read the same original number and subsequently write conflicting totals.

A journal captures a business event. A posting is one line of that event applied to one account. Under the sign convention in this example, debits are positive and credits are negative. USD 100.00 of processor clearing is a debit of 10000 minor units. USD 97.00 of seller payable and USD 3.00 of fee revenue are credits of -9700 and -300. A credit-normal account displays its balance with the opposite sign to a debit-normal account. The journal has evidence for where the entire amount went.

Stripe published a description of its own immutable money movement ledger and the systems it uses to verify data arriving from external partners. That write-up illustrates why balancing internal events and reconciling external data are distinct tasks. The schema below is an independent PostgreSQL example. Stripe’s engineering write-up on Ledger

Design a PostgreSQL double-entry ledger around its invariants

Start by deciding which facts must survive every code path that can write financial data. A request key belongs to one ledger, a journal belongs to one currency, and each posting refers to an account in that same ledger and currency. Each journal must contain at least two nonzero lines whose signed sum is zero. Journal creation and all its lines occur in a single database transaction. An unsuccessful commit means none of that event was recorded.

Payment event
  → trusted writer authenticates ledger and canonicalises the request
  → journal identity and request key
  → signed posting lines tied to accounts
  → deferred validation at commit
  → balance views, exports and reconciliation

Pick the ledger boundary before designing indexes. A ledger could represent a legal entity, a set of customer obligations or another verified accounting boundary. In this example an account ID lives inside a ledger, so a foreign key that checks the numeric account ID alone cannot enforce isolation. Adding currency to the composite references prevents an accidental USD entry from targeting a different ledger’s account or an account denominated in INR.

Keep currency amounts in integer minor units when the required precision fits the currency model. Currencies can have different exponents. Convert at the boundary with explicit currency metadata and input validation. Some products need finer precision for accruals or pricing. Use a defined decimal scale and rounding policy for those products, and keep the booked unit distinct from a display amount. PostgreSQL’s sum(bigint) returns numeric, so an aggregate can exceed the range of an individual posting. A maintained balance column still needs a suitable type for accumulated amounts. PostgreSQL aggregate return types

A transfer between currencies does not make sense as a sum of unlike units. Record a balanced leg in each currency, connect the journals with a common operation identifier, and capture the rate and rounding policy independently. If those two legs constitute a single internal event, commit them together. A settlement that occurs later needs its own record and reconciliation path.

Keep the posting ledger append-only for normal users. Corrections should link a reversal to the original journal, then add the corrected entry if needed. The sample writer grants application access only to a function. That is a role boundary. Database owners can change objects, so stronger audit requirements need separate privileges, protected exports and restoration checks. Keep request data small and retain only fields you need for identity and reconciliation.

Implement the ledger in PostgreSQL

Create the accounts, journals and postings

Run the schema examples as a trusted migration owner on PostgreSQL 18. The journal header anchors retries and ties a business event to a currency. Every posting references both its journal and its account. The redundant-looking unique keys allow PostgreSQL to enforce currency and ledger equality declaratively, even when a caller constructs an invalid posting.

A row-level CHECK can prevent zero amounts. A deferred constraint trigger checks all the postings together. Attach it to journal insertion, which happens once per new transaction header. Attaching the same aggregate to each posting would repeat the work, and a journal with no postings would never queue such a trigger. This design depends on a single write gateway. The role that executes the function cannot insert postings directly into an older journal. PostgreSQL constraint triggers and deferral

CREATE ROLE ledger_writer NOLOGIN;
CREATE SCHEMA money;

CREATE TABLE money.account (
  ledger_id bigint NOT NULL,
  id bigint NOT NULL,
  currency text NOT NULL CHECK (currency ~ '^[A-Z]{3}$'),
  PRIMARY KEY (ledger_id, id),
  UNIQUE (ledger_id, id, currency)
);

CREATE TABLE money.journal (
  id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  ledger_id bigint NOT NULL,
  currency text NOT NULL CHECK (currency ~ '^[A-Z]{3}$'),
  request_key text NOT NULL CHECK (length(request_key) BETWEEN 1 AND 200),
  request_body jsonb NOT NULL,
  recorded_at timestamptz NOT NULL DEFAULT clock_timestamp(),
  UNIQUE (ledger_id, request_key),
  UNIQUE (id, ledger_id, currency)
);

CREATE TABLE money.posting (
  journal_id bigint NOT NULL,
  line integer NOT NULL CHECK (line BETWEEN 1 AND 100),
  ledger_id bigint NOT NULL,
  currency text NOT NULL,
  account_id bigint NOT NULL,
  amount_minor bigint NOT NULL CHECK (amount_minor <> 0),
  PRIMARY KEY (journal_id, line),
  FOREIGN KEY (journal_id, ledger_id, currency)
    REFERENCES money.journal (id, ledger_id, currency),
  FOREIGN KEY (ledger_id, account_id, currency)
    REFERENCES money.account (ledger_id, id, currency)
);

CREATE INDEX posting_account_history
ON money.posting (ledger_id, account_id, journal_id);

CREATE FUNCTION money.assert_balanced() RETURNS trigger
LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog AS $$
DECLARE
  line_count bigint;
  net numeric;
BEGIN
  SELECT count(*), sum(amount_minor) INTO line_count, net
  FROM money.posting
  WHERE journal_id = NEW.id;

  IF line_count < 2 OR net IS DISTINCT FROM 0::numeric THEN
    RAISE EXCEPTION 'journal % must have at least two lines and net to zero', NEW.id
      USING ERRCODE = '23514';
  END IF;
  RETURN NULL;
END;
$$;

-- One aggregate per header; an empty journal also reaches this trigger.
CREATE CONSTRAINT TRIGGER journal_balanced
AFTER INSERT ON money.journal
DEFERRABLE INITIALLY DEFERRED
FOR EACH ROW EXECUTE FUNCTION money.assert_balanced();

The balance check is a security-definer trigger function because it can fire after the write function has returned, when the current role may lack direct read privileges. Use a trusted owner and keep references to ledger tables schema-qualified. In production, use a separate non-login owner role with the privileges this schema requires. Application roles should have no membership in that owner role.

Post every line through one gateway

Validate payer identity, account permissions and request size before calling SQL. The gateway below assumes ledger_writer belongs to a trusted service that has already authorised the ledger and account pairings. It should never be granted to a tenant or an arbitrary reporting user. Its limited input is the ledger ID, currency, canonical request identifier and the exact prepared list of lines.

BEGIN;
CREATE FUNCTION money.post_journal(
  p_ledger bigint, p_currency text, p_key text, p_lines jsonb
) RETURNS bigint
LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog AS $$
DECLARE
  result_id bigint;
  previous_currency text;
  previous_lines jsonb;
BEGIN
  IF jsonb_typeof(p_lines) IS DISTINCT FROM 'array' THEN
    RAISE EXCEPTION 'postings must be an array' USING ERRCODE = '22023';
  END IF;
  IF jsonb_array_length(p_lines) NOT BETWEEN 2 AND 100 THEN
    RAISE EXCEPTION 'send between two and 100 postings' USING ERRCODE = '22023';
  END IF;

  INSERT INTO money.journal (ledger_id, currency, request_key, request_body)
  VALUES (p_ledger, p_currency, p_key, p_lines)
  ON CONFLICT (ledger_id, request_key) DO NOTHING
  RETURNING id INTO result_id;

  IF result_id IS NULL THEN
    -- At READ COMMITTED, this separate statement can see a competing commit.
    SELECT id, currency, request_body
    INTO STRICT result_id, previous_currency, previous_lines
    FROM money.journal WHERE ledger_id = p_ledger AND request_key = p_key;

    IF previous_currency IS DISTINCT FROM p_currency
       OR previous_lines IS DISTINCT FROM p_lines THEN
      RAISE EXCEPTION 'request key reused for another journal'
        USING ERRCODE = '22023';
    END IF;
    RETURN result_id;
  END IF;

  INSERT INTO money.posting
    (journal_id, line, ledger_id, currency, account_id, amount_minor)
  SELECT result_id, line_number::integer, p_ledger, p_currency,
         (item->>'account_id')::bigint, (item->>'amount_minor')::bigint
  FROM jsonb_array_elements(p_lines) WITH ORDINALITY AS line(item, line_number);

  RETURN result_id;
END;
$$;

-- Create and revoke in one transaction so PUBLIC never sees the writer.
REVOKE ALL ON FUNCTION money.post_journal(bigint, text, text, jsonb) FROM PUBLIC;
GRANT USAGE ON SCHEMA money TO ledger_writer;
GRANT EXECUTE ON FUNCTION money.post_journal(bigint, text, text, jsonb) TO ledger_writer;
COMMIT;

Force fixed representation before retries. JSON objects compare by value, while array order matters. Replaying the same request with lines in a new order is a different request in this demonstration. If callers send spelling differences or unused properties, choose whether to normalise those before passing the body. Cap bytes at the application boundary as well as counting lines. An idempotency key should originate where attempts can be correlated, such as a verified processor capture ID paired with the operation type.

At READ COMMITTED, a competing insert can make ON CONFLICT DO NOTHING return nothing. A separate SQL statement then looks up the committed winner. Keep the retry branch within the same function. At higher isolation levels, retry the whole transaction on a serialization failure. Send a success response only after commit, because the balance trigger may run after the function has already returned an ID. PostgreSQL transaction isolation and visibility

INSERT INTO money.account (ledger_id, id, currency)
VALUES (7, 10, 'USD'), (7, 20, 'USD'), (7, 30, 'USD');

SET ROLE ledger_writer;
BEGIN;
SELECT money.post_journal(7, 'USD', 'capture:cap_1048', '[
  {"account_id": 10, "amount_minor": 10000},
  {"account_id": 20, "amount_minor": -9700},
  {"account_id": 30, "amount_minor": -300}
]'::jsonb);
COMMIT;
RESET ROLE;

Execute the same function call twice under ledger_writer. Inspect the tables under the migration role and verify there is one journal and three postings. Change one amount and reuse the key. The function should report an invalid request. Keep that changed amount and use a new key. The deferred trigger should now reject the commit. Repeat with an account that belongs to a different ledger and observe the foreign key rejection before the journal is posted. In an integration test, make those assertions against distinct database connections as well as a sequential replay.

Derive balances and protect available funds separately

A balance view can aggregate postings by ledger, account and currency. Once repeatedly scanning a large account’s history becomes expensive, maintain a balance table and update it in the posting transaction, or project balances asynchronously for reads where lag is acceptable. Verify snapshots against source postings. An asynchronous offset needs a commit-ordered change source or a design that tracks every processed journal individually. A sequence-generated journal ID can be assigned before another transaction commits a higher ID, so max(id) by itself is an unsafe checkpoint.

Spending decisions belong on the primary. For an account with a spending limit, lock the relevant wallet or position rows in a consistent order before checking available funds, writing a hold, or spending. An alternative for a single balance row is a conditional atomic update that reserves funds only when enough remain. Roll back the corresponding journal if the funds check fails. Holds can be represented with dedicated accounts or a separate table maintained in the same transaction. Settle or release each hold through one defined, idempotent transition.

# postgresql.conf defaults can be overridden for the trusted ledger worker.
# Illustrative budgets; measure contention before adopting them.
lock_timeout = '750ms'
statement_timeout = '5s'
idle_in_transaction_session_timeout = '15s'

Use measurements to set these timeout budgets for the writer. A busy platform clearing account can become a bottleneck if every capture locks and updates the same cached total. It may be safe to project that informational total later while keeping spendable wallets synchronous. Count and monitor lock waits and failed commits separately. A plausible early mistake is to apply one balance-locking rule to every account and learn that throughput now depends on one global row.

Failures a balanced journal can still hide

A duplicate provider event finds a different business key

A provider can deliver different event IDs for updates about the same underlying capture. A single event hash deduplicates delivery, but may produce duplicate monetary events. Store ingress identity separately from posting identity. Identify the settled transition by its stable business object and operation. Reject attempts to reuse that key for different economics and retain enough external IDs to explain the decision to support.

A balanced entry uses the wrong accounts

Moving USD 97.00 to the wrong seller can still balance. Tie account choice to authorisation and validate the allowed account types for each operation in the service that prepares the call. Underwater accounts similarly require their own policy. Use reconciliation against external processor reports, record missing or unmatched transfers, and review stale clearing entries. Systematic misclassification can appear perfectly balanced internally.

Deferred validation fails after a provisional success

On a service that emits a webhook or returns success as soon as the function yields an ID, a subsequent 23514 error leaves the outside world pointing at a journal that never committed. Commit before returning a result. If another system must be notified, write an outbox entry inside the same transaction and publish it afterwards. Retried delivery should pass a stable identifier.

Late provider reports alter the story of yesterday

One timestamp cannot represent both the effective business date and the time you learned about a movement. Add an effective timestamp when your reporting rules call for one. Use a clearly defined cutoff in period reports and preserve the recording timestamp. Keep reversals linked to their source so a later adjustment can explain any change in a historical report.

When another ledger design fits better

  • A single-entry adjustment history can be sufficient for a non-transferable product usage counter. A history of increments and decrements still makes support investigations easier. Choose double entry when the same event changes multiple financial positions whose movements need to reconcile.
  • A dedicated ledger system may fit when the team has a high transaction rate, requires specialised controls, or wants to rely on existing reporting and reconciliation operations. Compare semantics for reversals, pending transfers and external exports before deciding how your application integrates.
  • A synchronous balance cache complements an append-only ledger when decisions need to read funds immediately. Use the cache for a scoped decision, keep the posting history authoritative and include a reconciliation test that detects drift.

What to measure before relying on the ledger

As an illustration, 80,000 journals per day with three posting lines each yields 240,000 postings per day, or 87.6 million over 365 days before reversals and retries that produce new legitimate events. That is a row-count estimate. Measure actual heap and index space, live write-ahead log volume, and the size and cost of retention copies using a representative mix of accounts.

Stripe reported five billion events per day for its Ledger system, and reported verifying 99.99% of its dollar volume within four days. Those measures cover a different architecture and workload. For this design, benchmark a normal account distribution and a burst of writes to one account, then report latency percentiles, lock waits and deadlocks. Also test restoration and replay from a known journal set. Stripe’s published Ledger scale and verification figures

Frequently asked questions

How do you enforce double-entry balancing in PostgreSQL?

Insert a journal header and its postings in one transaction. Use composite foreign keys to enforce ledger and currency consistency on every posting. A deferred constraint trigger on the journal can confirm that at least two nonzero posting lines exist and that their signed amounts sum to zero. Restrict journal creation to a single controlled writer.

Should account balances be stored or calculated from postings?

Use postings as the authoritative history and calculate balances from them when that query meets the latency budget. A cached or projected balance can make frequent reads cheaper. Maintain synchronous balances for spending rules that require current funds, and reconcile cached values against the postings they represent.

How do you stop a ledger account from overdrawing?

Use a separate available-funds invariant for accounts that can be overdrawn. Lock the relevant position, check its balance after holds, and write the hold or posting before releasing that lock. An atomic conditional update can enforce the same invariant for a single balance row. Keep the spending decision and journal in one transaction.

How do you correct a journal in an append-only ledger?

Record a reversal that cancels the original postings and references their journal. If necessary, post a separate corrected journal. Give each event its own stable request key and record the reason for the correction. Keeping all three events preserves a timeline for reconciliation, reporting and support.

Further reading

Planning a PostgreSQL double-entry ledger? Talk to Dumb Potato about modelling your money flows, turning invariants into tests and deciding which operations need a current balance.

Dumb Potato Editorial

Putting this into practice?

Share the problem you’re solving and the tradeoffs you’re weighing with our engineering team.

See how we help with e-commerce

Discuss your project