Platform Architecture
How LedgerFlow is built, and how to integrate with it.
LedgerFlow is a self-contained, containerised platform of 17 orchestrated services built on PostgreSQL 18 as the primary infrastructure layer. It replaces traditional message brokers, job schedulers, and caching with native PostgreSQL extensions — reducing operational complexity without sacrificing reliability.
The architecture is explicitly designed for payment service providers (PSPs), financial institutions, and merchants that need double-entry bookkeeping, real-time fraud detection, maker-checker approval workflows, and multi-currency processing in a single, auditable platform.
What You Are Looking At
The diagram below shows all 17 running services organised into six conceptual layers: client access, Cloudflare edge, application, core data, async workers, and observability.
For buyers and evaluators: LedgerFlow ships as a complete, ready-to-deploy solution. Every service in the diagram is pre-configured and starts with a single command. No external message broker, job scheduler, or caching layer is required.
Accessing the platform — public endpoints via Cloudflare:
ui.ledgerflow.ai— Web UI and customer self-service portalapi.ledgerflow.ai— REST API for all integrations (transactions, accounts, reconciliation, KYC)wss.ledgerflow.ai— Real-time WebSocket event streamswagger.ledgerflow.ai— Interactive API documentation (browse all endpoints without writing code)mcp.ledgerflow.ai— Multi-Channel Platform (MCP) documentation and toolsobs.ledgerflow.ai— Observability stack (Grafana dashboards, Prometheus metrics, Loki logs, Tempo traces, Pyroscope profiles)sec.ledgerflow.ai— SIEM Security portal (audit logs, blockchain anchor proofs, access control management)htmx.ledgerflow.ai— HTMX-powered micro-frontends (User wallets)
Cloudflare provides DDoS protection, Web Application Firewall (WAF), global CDN, automatic HTTPS, and rate limiting — before any request reaches the application.
For system integrators: All business logic is exposed through a PostgREST-generated REST API.
Authentication is JWT or OIDC. Transaction endpoints are served by a dedicated high-throughput pool —
high-frequency API clients never starve the general API pool. The full OpenAPI specification is at
swagger.ledgerflow.ai.
Architecture Overview — 17-Service Containerised Platform
All services run inside a single Docker Compose stack. The amber Cloudflare band at the top shows the four public-facing domains — DDoS protection, WAF, CDN, and TLS all resolved before the request enters the platform. The orange DB Schema Abstraction band represents the sole REST API surface — all client requests are authenticated and permission-checked before reaching any business data.
External integrations (left panel) communicate exclusively through the async HTTP Client microservice via the internal message queue, keeping the core ledger isolated from third-party availability.
Double-Entry Ledger Engine
Every financial movement is recorded as a balanced set of postings across debit and credit accounts. The ledger enforces GAAP-compatible double-entry rules automatically — clients submit amounts and account IDs; the engine normalises debit/credit signs by account type (Asset, Liability, Income, Expense) so erroneous sign entries are impossible.
Transactions support: reversals, foreign exchange settlement across two currencies, dynamic fee-generation rules (six rule types), and deep hierarchical account aggregation with automatic cycle detection. All balance updates propagate to parent accounts in real time.
Maker-Checker 4-Eye Workflows
Batches of staged transactions flow through a state machine enforced at the database level: Pending → Pre-Authorised → Authorised → Processed (or Rejected). The same user cannot be both maker and checker for the same batch — enforced by a stored-procedure constraint, not application logic.
This satisfies regulatory separation-of-duties requirements for financial institutions without additional middleware. All batch state transitions are fully audited — every action is recorded with the user, timestamp, and full before/after state.
Proprietary Cyclic Fraud Detection
LedgerFlow's fraud engine uses circular statistics (sin/cos/atan2) to model 24-hour behavioural patterns. Unlike linear mean/stddev, circular statistics correctly handle wraparound (e.g., transactions at 23:00 and 01:00 have a circular mean of midnight, not noon).
Per-account baselines are computed across three time dimensions (hour-of-day, day-of-week, day-of-month) over a rolling 90-day window. Anomalies are flagged in real time the moment a transaction is posted — no batch job required. Anomaly details are accessible through the UI or via the API.
Automated Reconciliation
Import partner CSV files and match them against ledger postings using configurable templates. Each template defines field mappings, date formats, tolerance thresholds, and multi-account scope. The engine produces three outputs: matched pairs, unmatched partner rows (exceptions), and unmatched ledger rows (missing payments).
Reconciliation supports multiple currencies per run and full auditability — every import, every match decision, and every exception is persisted.
Real-Time Notifications
LedgerFlow delivers real-time push notifications to connected web browsers, mobile apps, and integrated systems — without any polling required on the client side.
Messages can be sent to all connected users simultaneously, or targeted to a specific user. The same authentication token used for the REST API grants WebSocket access — no separate credential is needed.
Typical events: transaction confirmed, batch approved or rejected, KYC status changed, balance threshold reached, system alert.
Customer KYC & Self-Service Portal
Customers (individuals, merchants, or vendors) are managed with KYC status tracking (pending → verified → rejected → expired). Document uploads trigger AI-assisted processing via Docling (OCR + classification) and hash-verified storage.
The customer portal supports: account statements, push payments, pull payment requests, fund loading and settlement via third-party payment switches and gateways, and real-time transaction notifications. All portal access is governed by the same role-based access control model as the back-office.
Integrating with the API
All API endpoints are auto-generated by PostgREST from the api schema. You do not call
database functions directly — you call HTTP endpoints, and PostgREST maps them to stored procedures
with full JWT verification and role assignment before execution.
Base URL: https://api.ledgerflow.ai
Authentication flow:
POST /rpc/login_get_tokenwith{ "email_p": "...", "password_p": "..." }→ returns{ "token": "..." }- Include
Authorization: Bearer <token>on all subsequent requests - OIDC/SSO is also supported — redirect to the configured SSO endpoint and handle the callback
Smart routing (managed transparently by NGINX): Transaction and maker-checker endpoints are automatically routed to a dedicated high-throughput pool — no special configuration required by the API client.
Full API specification is available at https://swagger.ledgerflow.ai — browse all
available endpoints, request schemas, and filter parameters without reading source code.
Core Transaction API
POST /rpc/transactions_add
Authorization: Bearer <JWT>
{
"application_uuid": "3fa85f64-5717-d562-b3fc-2c963f6dafa6",
"journal_notes": "Payment for services",
"transaction_reference": "TXN-001",
"journal_records": [
{ "account_id": 1001, "currency_id": "USD",
"amount": 100.00, "flag": "d" },
{ "account_id": 2001, "currency_id": "USD",
"amount": 100.00, "flag": "c" }
]
}
flag is "d" (debit) or "c" (credit); application_uuid is the idempotency key.
DR/CR normalisation, rule triggers, balance propagation, and audit logging all happen
inside the stored procedure — the caller only needs account IDs and amounts.
This is indicative. See swagger.ledgerflow.ai for the full request/response schema.
Maker-Checker & Customer Payment APIs
Maker-Checker batch lifecycle:
POST /makerchecker_batch ← maker creates the batch
POST /rpc/makerchecker_transactions_add ← maker stages transactions
POST /rpc/makerchecker_batch_process ← checker authorises & system posts
Customer self-service:
POST /rpc/customer_send_payment ← send funds
POST /rpc/customer_request_payment ← request funds
POST /rpc/me_payment_request_pay ← payer approves/pays a request
All endpoints return JSON. Errors use standard HTTP 4xx/5xx responses.
See swagger.ledgerflow.ai for full parameter details.
Authentication & Authorisation
LedgerFlow implements a seven-layer security model:
- Cloudflare edge — DDoS protection, WAF, TLS termination before the platform
- NGINX — rate limiting and smart upstream routing
- Session or JWT token validation
- User active-status and password-expiry checks
- Fine-grained permission checks — 25+ permission categories (read / read-write / read-write-delete)
- Role assignment — business logic executes under the user's assigned database role
- Row-Level Security — data filtered at the engine level, enforced in the database
OIDC/SSO integrates with Keycloak, Auth0, Microsoft Entra, or any standards-compliant identity provider. Federated identities are mapped to internal roles on first login.
Full Audit Trail
Every INSERT, UPDATE, and DELETE across all system tables is automatically captured by a trigger-based audit system, recording:
- Timestamp of the change
- User email (from session context)
- Client IP address
- Action type (INSERT / UPDATE / DELETE / DOWNLOAD)
- Before state — full previous record
- Changed fields — only the fields that changed (JSON diff)
Audit records are stored in a dedicated, restricted schema — only the audit trigger can write to it. No application code can bypass or modify audit records. Fully indexed for fast querying by user, timestamp, table, action, or IP address.
Blockchain Anchoring — Cryptographic Proof of Ledger Integrity
LedgerFlow periodically commits a cryptographic fingerprint of the entire ledger to the Bitcoin blockchain via OpenTimestamps, creating an immutable, publicly verifiable timestamp that proves the ledger state existed at a specific point in time and has not been altered since.
How it works — four steps:
-
Snapshot — At each anchor interval, a deterministic CSV is generated: one row per account, sorted by
account_id, containing the account ID, current balance, the SHA-256 hash of the latest transaction row, and the prior chained hash. Field ordering and sort order are fixed — the CSV is byte-for-byte reproducible from the same ledger state. -
Root Hash —
root_hash_hex = SHA-256(snapshot_csv). Because the hash is derived directly from the snapshot text, anyone holding the CSV can verify it independently:echo -n "$snapshot" | sha256summust matchroot_hash_hex. -
Bitcoin Commitment — The 32-byte root hash is submitted as a binary digest to an OpenTimestamps calendar server, which aggregates it with other digests into a Merkle tree and embeds the tree root in a single Bitcoin transaction via OP_RETURN. A pending
.otsproof file is returned immediately. -
Confirmation (~1 hour) — Once the Bitcoin block is mined, the calendar returns the complete Merkle path. LedgerFlow assembles the full proof, extracts the Bitcoin block height and OP_RETURN value, and marks the anchor as confirmed.
Deployment Model
Development / single-node:
docker-compose up -d # starts all 17 services
One command. No external dependencies. PostgreSQL, all microservices, NGINX, and the full observability stack start together with pre-configured dependencies.
Production considerations (scale-out):
- PostgreSQL HA: streaming replication
- Load balancing: cloud ALB or NGINX cluster in front of the platform
- Secrets management: integrate with Vault or cloud secrets manager
- Horizontal scale: API and queue services are stateless — add replicas behind NGINX
- Storage: object storage for backups, NVMe/SSD for active data
Minimum resources (single-node): Database: 8 CPU, 16 GB RAM, 500 GB SSD · Application: 4 CPU, 8 GB · Observability: 2 CPU, 4 GB
Observability Stack
Six pre-configured services provide full-stack visibility with zero setup:
| Tool | Purpose |
|---|---|
| Grafana | Dashboards, alerting, drill-down exploration |
| Prometheus | Metrics (15-second scrape, 9 targets) |
| Loki | Log aggregation and full-text querying |
| Tempo | Distributed traces (7-day retention) |
| Pyroscope | Continuous CPU/memory profiling |
| Alloy | OpenTelemetry collector |
All Go microservices expose metrics endpoints. NGINX emits OpenTelemetry spans. PostgreSQL query performance is tracked automatically. Pre-provisioned Grafana dashboards cover: DB performance, NGINX latency, queue processing, and business metrics.