Skip to main content

Part of topic: Zero-Trust & Auditable Infrastructure

LedgerX: Designing an Auditable Multi-Tenant Financial Platform with NestJS and PostgreSQL

LedgerX: Designing an Auditable Multi-Tenant Financial Platform with NestJS and PostgreSQL

November 20, 2024 3 min read NestJS, TypeScript, PostgreSQL, Multi-Tenant, Fintech, M-Pesa, Stripe

LedgerX: Designing an Auditable Multi-Tenant Financial Platform with NestJS and PostgreSQL is a Developer Journal article by Ancel Ajanga on https://ancel.co.ke. How I engineered a production-grade fintech backend: strict organization-scoped row isolation, true double-entry ledgering with append-only hash chains, and idempotent M-Pesa/Stripe adapters. It focuses on: SMB financial applications often suffer from weak multi-tenancy boundaries, vulnerable payment webhooks, lack of audit trails, and single-entry balanc…

How I engineered a production-grade fintech backend: strict organization-scoped row isolation, true double-entry ledgering with append-only hash chains, and idempotent M-Pesa/Stripe adapters.

Who this is for

Backend architects, fintech engineers, and technical leaders designing financial software requiring tamper-evident accounting, multi-tenancy, and resilient payment coordination.

Problem

SMB financial applications often suffer from weak multi-tenancy boundaries, vulnerable payment webhooks, lack of audit trails, and single-entry balances that silently desynchronize under partial failures.

Business outcome

A production-grade multi-tenant financial platform with immutable double-entry ledgering, SHA-256 hash chaining, token-versioned security, and deterministic fraud detection.

Metrics

  • Double-entry ledger invariant: debits strictly equal credits across every transaction
  • Append-only SHA-256 transaction hash chains for tamper detection
  • Idempotent webhook ingestion for M-Pesa and Stripe payments

When designing financial software, there is zero margin for error. A bug in a social media app causes a minor display glitch; a bug in a fintech backend causes duplicate payouts, corrupted balances, and regulatory violations.

I built LedgerX to answer a concrete engineering challenge: **How do you design a modern fintech backend that is strictly multi-tenant, mathematically auditable, resilient against provider outages, and operationally observable—without overengineering or hiding behind buzzwords?**

The Problem: Fragile Financial Foundations

Most small-to-mid business financial tools suffer from common architectural flaws: 1. **Weak Multi-Tenancy**: Tenant scoping is handled haphazardly at the controller level with simple `WHERE tenant_id = :id` clauses, leaving the system vulnerable to data leakage if a developer forgets a parameter. 2. **Single-Entry Balances**: Balance amounts are updated via direct SQL mutations (`UPDATE accounts SET balance = balance + 100`). If a database write succeeds but the audit log fails, the balance desynchronizes with no way to reconstruct the historical truth. 3. **Vulnerable Payment Webhooks**: Systems blindly trust external callbacks from payment providers without raw-body cryptographic signature verification or replay deduplication.

The Six Non-Negotiable Architectural Principles

LedgerX was built around six core design principles:

### 1. Strict Multi-Tenant Isolation Every request, query, and domain event is explicitly scoped to an Organization. Users can belong to multiple organizations with distinct roles (`ADMIN`, `MANAGER`, `MEMBER`). At the data access layer, repository guards ensure that no query executes without an authenticated organization context.

### 2. True Double-Entry Ledgering with Append-Only Hash Chains In LedgerX, balances are never directly updated. Every financial event generates balanced double-entry journal entries: - Every debit must equal every credit: `SUM(debits) - SUM(credits) = 0`. - Each ledger entry contains a cryptographic **SHA-256 hash** that incorporates the timestamp, amount, accounts, and the hash of the preceding transaction in the organization's chain. - If an attacker or rogue administrator modifies an existing database record, the cryptographic hash chain breaks, immediately alerting the system to data tampering.

ypescript
export function computeTransactionHash(
  previousHash: string,
  entry: LedgerEntry
): string {
  const payload = [
    previousHash,
    entry.organizationId,
    entry.timestamp.toISOString(),
    entry.debitAccount,
    entry.creditAccount,
    entry.amount.toString(),
  ].join('|');
  
  return crypto.createHash('sha256').update(payload).digest('hex');
}

### 3. Event-Driven Domain Bus Core actions trigger typed domain events: `PaymentCompleted`, `LedgerTransactionPosted`, `InvoiceOverdue`, `DiagnosticsRemediationExecuted`. An internal event dispatcher distributes these events to audit logging, fraud scoring, and telemetry listeners asynchronously without blocking the client request thread.

### 4. Idempotent Payment Adapters (Stripe & M-Pesa) Payment processing is decoupled through adapter interfaces: - **Raw-Body Verification**: Webhooks from Stripe and Safaricom M-Pesa are verified against raw request buffers before JSON parsing to prevent signature tampering. - **Idempotency Keys**: Every payment intent stores an idempotency key. Duplicate webhook deliveries from telecom network retries are detected and acknowledged without executing duplicate ledger posts.

### 5. Deterministic Fraud Signals Rather than relying on opaque machine learning models that cannot be audited, LedgerX implements deterministic fraud scoring: - Sudden velocity spikes in transaction volume. - Geographic anomalies. - Repeated failed payment attempts across short time windows. Each signal contributes a documented risk score, allowing managers to inspect exactly why a transaction was flagged.

### 6. Security & Token Versioning Authentication uses JWT access tokens paired with refresh tokens that enforce **token versioning**. If an account is compromised or permissions change, incrementing the user's `token_version` in the database immediately invalidates all active sessions across all devices.

Key Engineering Takeaways

1. **Single-Entry Accounting is a Trap**: Always use double-entry bookkeeping for financial state. If an entry fails, the invariant check halts execution before state corruption occurs. 2. **Auditability Must Be Structural**: An audit log should not be an afterthought written to a text file. Integrating cryptographic hash chains into your relational tables makes historical tampering mathematically detectable. 3. **Idempotency is Non-Negotiable in Payments**: Network retries are a normal condition, not an anomaly. Every payment handler must be strictly idempotent.

Explore the LedgerX Case Study, visit the [LedgerX Project Page](/projects/ledgerx), or inspect the [architecture documentation on GitHub](https://github.com/Ancel-duke/LedgerX/blob/main/ARCHITECTURE.md).

Trade-offs

Used deterministic, rule-based fraud scoring rather than opaque ML models to keep decisions fully explainable and auditable; relied on comprehensive E2E test suites for real system confidence.

Challenges faced

Preventing cross-tenant data leakage by enforcing tenant-scoping at the ORM repository layer; handling asynchronous payment webhooks idempotently without race conditions.