# Architecture And Data Flows

Last reviewed: 2026-07-01

Owner: Engineering architecture
Reviewers: Security, operations, finance, compliance, privacy

This document describes the current repository architecture. It is an engineering
control and does not assert that local provider adapters are licensed production
providers. The production trust boundaries must be reviewed again when real bank,
card, identity, sanctions, market-data, or custody providers are selected.

## System Context

```mermaid
flowchart LR
    Customer[Customer browser]
    Admin[Admin browser]
    Edge[WAF / TLS reverse proxy]
    Web[React and TypeScript frontend]
    API[Go banking API]
    Worker[Settlement worker]
    DB[(PostgreSQL)]
    Secrets[KMS and secret manager]
    Observe[Prometheus / Grafana / Alertmanager]
    Providers[Bank, card, KYC, sanctions, FX and custody providers]

    Customer -->|HTTPS| Edge
    Admin -->|HTTPS + MFA| Edge
    Edge --> Web
    Web -->|JSON API + access token| API
    Edge -->|Provider webhooks| API
    API -->|SQL over private network| DB
    Worker -->|SQL over private network| DB
    API -->|TLS + idempotency and correlation IDs| Providers
    Worker -->|TLS + provider references| Providers
    API -->|Runtime secrets| Secrets
    Worker -->|Runtime secrets| Secrets
    API -->|Internal metrics and redacted logs| Observe
    Worker -->|Internal metrics and redacted logs| Observe
```

The checked-in application currently wires local implementations for bank ledger,
card issuer, identity, sanctions, blockchain analytics, and custody interfaces.
Those adapters model contracts for development; they do not cross a real provider
boundary. Production adapters, credentials, contracts, and certified webhook
formats remain go-live gates.

## Runtime And Network Boundaries

```mermaid
flowchart TB
    subgraph Public[Public network]
        Browser[Customer or admin browser]
        Provider[External provider]
    end

    subgraph EdgeZone[Edge zone]
        Proxy[WAF, TLS termination, host and rate-limit policy]
        Static[Frontend static assets]
    end

    subgraph AppZone[Private application network]
        API[Go API replicas]
        Worker[Async worker replicas]
    end

    subgraph DataZone[Restricted data network]
        PG[(PostgreSQL HA and PITR)]
        Vault[KMS / secret manager]
        Evidence[Encrypted evidence and attachment storage]
    end

    subgraph OpsZone[Operations network]
        Metrics[Metrics, logs, traces and alerts]
        CICD[CI/CD and signed artifacts]
    end

    Browser -->|443| Proxy
    Provider -->|443 signed webhook| Proxy
    Proxy --> Static
    Proxy -->|trusted forwarded headers| API
    API -->|5432, TLS| PG
    Worker -->|5432, TLS| PG
    API -->|workload identity| Vault
    Worker -->|workload identity| Vault
    API -->|signed URL or private API| Evidence
    API -->|egress allowlist, 443| Provider
    Worker -->|egress allowlist, 443| Provider
    API -->|private scrape and export| Metrics
    Worker -->|private export| Metrics
    CICD -->|approved immutable digest| AppZone
```

Production rules:

- Only the edge is internet reachable; PostgreSQL, metrics, workers, evidence
  storage, and secret management are private.
- The API trusts forwarded client information only from configured proxies.
- Provider egress is allowlisted. Provider callbacks use a dedicated route,
  signature verification, replay protection, and event deduplication.
- Admin access requires least-privilege scopes, MFA or step-up for high-risk
  actions, and tamper-evident audit events.
- Production data is not copied into lower environments. Synthetic or approved
  anonymized data is used outside production.

## Application Components

| Component | Responsibility | Primary state |
| --- | --- | --- |
| React frontend | Customer and admin workflows, disclosures, step-up UX | Browser memory and refresh-token session contract |
| Go API | Authentication, validation, orchestration, policy enforcement and API responses | PostgreSQL |
| Settlement worker | Asynchronous SEPA settlement retries and terminal handling | PostgreSQL settlement and transfer records |
| Auth and authguard | Access/refresh sessions, MFA, recovery, suspicious-login and rate-limit controls | Users, sessions, MFA, security events and rate-limit buckets |
| Accounts and wallets | Fiat wallet/account ownership, currency balances, IBAN and routing metadata | Wallets, accounts and provider account references |
| Ledger | Immutable double-entry journals, holds, reversals, trial balance and exports | Ledger accounts, journals and lines |
| Payments and settlement | Beneficiaries, transfer state, screening, provider reports, inbound payments and notifications | Transfers, status events, reviews and settlement records |
| Cards | Tokenized card metadata, lifecycle, authorization holds, clearing, reversal, disputes and notifications | Card, authorization and ledger-event records |
| FX | Rates, expiring quotes, conversions, maker-checker and treasury reports | Rates, quotes, conversions and journals |
| Crypto | Custody metadata, addresses, screenings, chain lifecycle, travel rule and stablecoin controls | Crypto operational records; no private keys in this app |
| KYC, AML and compliance | Identity evidence, screening, risk, EDD, cases and regulatory-report workflow | Compliance records and evidence references |
| Risk and reconciliation | Limits, decisions, provider snapshots, EOD snapshots and break management | Risk events and reconciliation records |
| Backoffice and privacy | Operational cases, support sessions, evidence packages, DSAR and retention controls | Cases, audit events and policy records |

## Sources Of Truth

- Ledger journals are the financial accounting source of truth. Display balances
  are projections and must reconcile to journal-derived values.
- Provider reports and provider APIs are the source of truth for external
  execution, but never overwrite ledger history. Differences become explicit
  reconciliation breaks and approved corrective journals.
- PostgreSQL transfer, card, FX, crypto, KYC, and case state machines are the
  application workflow source of truth.
- The identity provider supplies verification decisions; compliance owns the
  acceptance, escalation, and customer-risk decision.
- Audit events and case history are append-oriented evidence. Corrections are new
  events, not edits to historical facts.
- Secrets and cryptographic keys belong in the configured KMS or secret manager,
  never in PostgreSQL, logs, source control, or support tooling.

## Data Classification

| Class | Examples | Handling |
| --- | --- | --- |
| Restricted | Password hashes, MFA seeds, recovery-code hashes, provider credentials, webhook secrets, card tokens | KMS-backed encryption where applicable, strict scopes, no logs or support export |
| Regulated confidential | KYC evidence, sanctions matches, SAR/STR material, financial transactions, crypto addresses | Need-to-know access, encrypted transport/storage, retention and access evidence |
| Confidential | Customer identity/contact data, cases, account identifiers, provider responses | Role-scoped access, redacted logs and controlled export |
| Internal | Aggregated operations metrics, runbooks, non-customer configuration | Employee access and change control |
| Public | Published notices, product disclosures and public API health response | Publication approval |

PAN and CVV handling is further constrained by `docs/card-data-scope.md`.

## Authentication And Session Flow

```mermaid
sequenceDiagram
    participant B as Browser
    participant E as Edge
    participant A as Go API
    participant D as PostgreSQL

    B->>E: Login over HTTPS
    E->>A: Request + trusted client metadata + request ID
    A->>D: Check user, password hash, lockout and anomaly signals
    D-->>A: User and security state
    A->>D: Create refresh session and audit/security events
    A-->>B: Short-lived access token + refresh-token contract
    B->>A: High-risk action
    A-->>B: step_up_required
    B->>A: TOTP or approved MFA proof
    A->>D: Record step-up and session evidence
    A-->>B: Elevated short-lived access token
```

Failure controls include generic login errors, distributed rate limiting, lockout,
session rotation, remote revocation, anomaly events, and redacted telemetry.

## Transfer And Ledger Flow

```mermaid
sequenceDiagram
    participant C as Customer
    participant A as API
    participant R as Risk and sanctions
    participant D as PostgreSQL
    participant P as Payment provider
    participant W as Settlement worker

    C->>A: Create transfer + idempotency key
    A->>D: Lock account and load beneficiary/routing rules
    A->>R: Limits, risk and beneficiary screening
    alt blocked or review required
        A->>D: Store risk/screening evidence and review hold
        A-->>C: Held or rejected status
    else approved
        A->>D: Atomic transfer + balanced ledger journal
        A-->>C: Accepted status
        W->>D: Claim pending settlement
        W->>P: Submit with provider/idempotency reference
        P-->>W: Accepted, failed, or unknown
        W->>D: Append status and settlement events
        W->>D: Approved reversal/refund journal on terminal failure
    end
```

Money movement invariants:

- Amounts use integer minor units or explicit crypto base-unit strings.
- Every fiat posting balances debits and credits per currency.
- Idempotency keys and unique external references prevent duplicate execution.
- Status transitions use explicit state machines; unknown provider outcomes are
  held for investigation and are not blindly replayed.
- Financial corrections use reversal or compensating journals. Operators do not
  edit balances or historical journal lines directly.

## Provider Webhook Flow

```mermaid
sequenceDiagram
    participant P as Provider
    participant E as Edge
    participant A as API webhook handler
    participant D as PostgreSQL
    participant O as Operations queue

    P->>E: HTTPS callback + signature + event ID
    E->>A: Size-limited raw body
    A->>A: Verify signature and timestamp
    A->>D: Insert event ID and payload hash
    alt duplicate or stale
        A-->>P: Idempotent success or rejection
    else valid new event
        A->>D: Validate ordering and state transition
        A->>D: Atomic business event, ledger effect and audit event
        A-->>P: Success
    end
    A->>O: Create case when order, signature, state, or balance is anomalous
```

Webhook payloads are untrusted input even after signature verification. Raw
payload retention, sensitive-field redaction, and replay windows must match each
contracted provider before production enablement.

## Card Authorization Flow

```mermaid
sequenceDiagram
    participant I as Card processor
    participant A as API
    participant R as Risk engine
    participant D as PostgreSQL and ledger

    I->>A: Signed authorization event
    A->>R: Card status, spending limits and velocity checks
    R-->>A: Approve, review, or decline
    A->>D: Deduplicate provider event
    A->>D: Create authorization hold ledger event
    I->>A: Clearing, reversal, or expiry event
    A->>D: Release/replace hold and append final balanced journal
    A-->>I: Contract response
```

The application stores tokenized card metadata, fingerprint and last four digits.
It must not persist CVV or reusable clear PAN. A real processor determines the
final production message contract and PCI scope.

## FX Conversion Flow

```mermaid
sequenceDiagram
    participant C as Customer
    participant A as API
    participant M as Market-data provider
    participant D as PostgreSQL and ledger

    A->>M: Fetch rate with source timestamp
    M-->>A: Rate, spread basis and observed time
    C->>A: Request quote
    A->>D: Store rate snapshot, fee and expiry
    A-->>C: Quote disclosure
    C->>A: Accept quote
    A->>D: Lock quote and source/destination accounts
    A->>D: Enforce unused and unexpired quote
    A->>D: Atomic balanced multi-currency conversion journals
    A-->>C: Conversion receipt
```

Rate changes require maker-checker approval. A stale or unavailable source must
fail closed unless an approved, bounded fallback rule exists.

## Crypto And Stablecoin Flow

```mermaid
sequenceDiagram
    participant C as Customer
    participant A as API
    participant S as Blockchain analytics
    participant U as Custody provider
    participant D as PostgreSQL

    C->>A: Request wallet/address or withdrawal
    A->>D: Check product flag, KYC/AML, jurisdiction and network control
    A->>S: Screen address and exposure
    S-->>A: Allow, review, or block
    alt review or blocked
        A->>D: Store screening and compliance case
    else allowed
        A->>U: Create address or movement with idempotency key
        U-->>A: Custody reference and pending state
        A->>D: Append chain transaction state/events
        U->>A: Signed confirmation/failure callback
        A->>D: Validate transition and confirmations
    end
```

Private keys are outside this application's intended boundary. Real movement must
remain disabled until custody responsibility, travel-rule applicability, network
allowlists, issuer risk, legal approval, and provider contracts are complete.

## Admin Change And Case Flow

```mermaid
sequenceDiagram
    participant M as Maker admin
    participant A as API
    participant D as PostgreSQL
    participant C as Checker admin
    participant E as Audit export

    M->>A: Propose high-risk change + reason
    A->>D: Store pending request and audit event
    C->>A: Review with MFA/step-up
    A->>D: Enforce different reviewer and required scope
    A->>D: Approve/reject and append history
    A->>D: Apply only approved change
    A->>E: Produce evidence package with actors, timestamps and references
```

Support impersonation is view-only, time-limited, ticket-bound, and audited. It
must not expose credentials, MFA material, PAN/CVV, provider secrets, SAR/STR
material, or permissions the support user does not already hold.

## Availability And Recovery

- Stateless API replicas can be replaced from a signed image digest.
- PostgreSQL requires HA, encrypted PITR backups, tested restore, and private
  access. Database state is not reconstructed from API logs.
- Worker jobs use database state and idempotent provider contracts so claimed work
  can recover after process failure.
- Feature flags isolate high-risk surfaces during provider or ledger incidents.
- Recovery requires health checks plus financial reconciliation; HTTP availability
  alone is not sufficient evidence of recovery.

## Change And Review Rules

Update this document when a trust boundary, provider, data store, authentication
method, money movement, deployment topology, or regulated product changes. Every
review must verify the diagrams against `backend/cmd/api/main.go`,
`backend/internal/httpapi/router.go`, deployment configuration, migrations, and
the contracted provider architecture. Record approval in the release or security
evidence package.
