Triamorph Systems

Business Systems · 13 min read · Sep 08, 2024

Double-Entry Accounting Database Schema in PostgreSQL: Designing Immutable Financial Ledgers and Audit Trails

Production PostgreSQL schema design for double-entry bookkeeping ledgers: debit/credit constraints, immutable append-only triggers, snapshot balances, and financial reconciliation.

By Hammad Haider

Core Engineering Takeaways

  • Enforce the fundamental accounting equation at the database layer: `SUM(debits) - SUM(credits) = 0` per journal entry using PostgreSQL deferred constraints.
  • Make ledger transaction tables strictly append-only by attaching triggers that raise exceptions on any SQL `UPDATE` or `DELETE` statement.
  • Accelerate balance reporting by maintaining periodic snapshot tables (e.g. daily closing balances) rather than scanning millions of historical transaction rows.

Financial software must never permit balance inaccuracies or silent data corruption. In accounting systems, updating an account balance by running `UPDATE accounts SET balance = balance + 100` is an unacceptable architectural anti-pattern that violates auditability. A double-entry accounting engine enforces mathematical balance: every transaction consists of a Journal Entry containing at least two Postings where total debits strictly equal total credits.

1. The Mathematics & Schema of Double-Entry Bookkeeping

Relational data model for Accounts, Journal Entries, and Postings

In double-entry bookkeeping, money cannot be created or destroyed—it only transfers between accounts (Assets, Liabilities, Equity, Revenue, Expenses). Every financial event is recorded as a balanced journal entry.

db/schema/fintech_double_entry_ledger.sql (sql)
-- Core Double-Entry Ledger Schema
CREATE TYPE account_category_enum AS ENUM ('asset', 'liability', 'equity', 'revenue', 'expense');

CREATE TABLE ledger_accounts (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    organization_id UUID NOT NULL,
    account_code VARCHAR(32) NOT NULL, -- e.g. '1000' (Cash), '2000' (Accounts Payable)
    account_name VARCHAR(128) NOT NULL,
    category account_category_enum NOT NULL,
    currency VARCHAR(3) NOT NULL DEFAULT 'USD',
    is_active BOOLEAN NOT NULL DEFAULT TRUE,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    UNIQUE(organization_id, account_code)
);

CREATE TABLE journal_entries (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    organization_id UUID NOT NULL,
    reference_number VARCHAR(64) NOT NULL UNIQUE,
    description TEXT NOT NULL,
    posted_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    created_by UUID NOT NULL
);

CREATE TABLE ledger_postings (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    journal_entry_id UUID NOT NULL REFERENCES journal_entries(id) ON DELETE RESTRICT,
    account_id UUID NOT NULL REFERENCES ledger_accounts(id),
    amount_cents BIGINT NOT NULL, -- Positive integer representation
    direction VARCHAR(6) NOT NULL CHECK (direction IN ('debit', 'credit')),
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

2. Enforcing Immutability & Preventing UPDATE / DELETE

Guaranteeing tamper-proof audit trails for SOX & SOC 2 compliance

If a transaction was entered in error, accountants do not delete the row. Instead, they record a Reversing Journal Entry that cancels out the previous balance. We enforce this via PostgreSQL database triggers.

db/triggers/enforce_ledger_immutability.sql (sql)
CREATE OR REPLACE FUNCTION prevent_ledger_tampering()
RETURNS TRIGGER AS $$
BEGIN
    RAISE EXCEPTION 'Financial Ledger entries are strictly immutable. Modifications and deletions are prohibited by compliance policy.';
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER trg_no_update_delete_postings
BEFORE UPDATE OR DELETE ON ledger_postings
FOR EACH ROW EXECUTE FUNCTION prevent_ledger_tampering();

CREATE TRIGGER trg_no_update_delete_entries
BEFORE UPDATE OR DELETE ON journal_entries
FOR EACH ROW EXECUTE FUNCTION prevent_ledger_tampering();

3. Multi-Currency & BigInt Integer Precision

Avoiding floating-point calculation errors in financial codebases

Never store money using `FLOAT` or `DOUBLE PRECISION` datatypes, which introduce catastrophic IEEE 754 rounding inaccuracies. We store all monetary amounts as `BIGINT` in the smallest currency unit (e.g. cents, satoshis).

4. High-Speed Snapshot Balances & Automated Reconciliation

Querying account balances in sub-millisecond speeds at massive scale

Running `SUM(amount_cents)` across tens of millions of transaction rows slows dashboard loading. We maintain an automated nightly balance snapshot table, reducing live balance calculations to adding delta postings since the last snapshot.

Tags: double entry accounting database schemapostgresql financial ledger schemaimmutable audit trail database designjournal entries debits credits postgres constraintsfintech core ledger architecture

Related Engineering Practice & Case Studies

Engineering Practice Blueprint

Custom ERP & Core Operations Software →

Relational data architectures replacing brittle spreadsheets with scalable business systems.

View Practice Blueprint & Capabilities →
Production Client System

Operations Management Platform (Custom ERP) →

Unified logistics and inventory platform replacing multiple fragmented spreadsheets with synchronized database accuracy.

Read Deployed Case Study (4x faster database transactions with zero inventory discrepancy) →

Related Engineering Articles & Guides

Explore all technical guides in our Articles & Guides Index → or discuss your architecture with our engineers via Technical Discovery →