# Architecture

Monetarie Core uses a modern, event-driven architecture designed for high-throughput financial transactions with strong consistency guarantees.

## System Overview

```
                    ┌─────────────────────────────────────┐
                    │           Load Balancer              │
                    │        (GCP HTTPS L7 LB)             │
                    └────────────┬────────────────────────┘
                                 │
              ┌──────────────────┼──────────────────┐
              │                  │                  │
      ┌───────▼──────┐  ┌───────▼──────┐  ┌───────▼──────┐
      │  Banking UI  │  │  Admin UI    │  │ Merchant UI  │
      │  (Vue 3)     │  │  (Vue 3)     │  │ (Vue 3)      │
      └───────┬──────┘  └───────┬──────┘  └───────┬──────┘
              │                  │                  │
              └──────────────────┼──────────────────┘
                                 │ REST / WebSocket
                    ┌────────────▼────────────────────┐
                    │     Phoenix API Gateway          │
                    │     (Elixir/OTP)                 │
                    └──┬─────────┬──────────┬─────────┘
                       │         │          │
              ┌────────▼──┐  ┌──▼────┐  ┌──▼──────────┐
              │TigerBeetle│  │ Redis │  │    NATS      │
              │  (Ledger)  │  │(Cache)│  │ (JetStream)  │
              └────────────┘  └───────┘  └─────────────┘
                       │                        │
              ┌────────▼────────────────────────▼──────┐
              │            PostgreSQL 16                │
              │     (Accounts, Users, Metadata)        │
              └────────────────────────────────────────┘
```

## Technology Stack

### Backend: Elixir/Phoenix

The API server is built with **Elixir** and **Phoenix Framework**, chosen for:

- **Concurrency** — Erlang/OTP lightweight processes handle millions of concurrent connections
- **Fault Tolerance** — Supervisor trees automatically restart failed processes
- **Real-time** — Phoenix Channels provide WebSocket support for live updates
- **Performance** — Sub-millisecond message passing between processes

Key libraries:
- `Phoenix` — Web framework with REST and WebSocket support
- `Ecto` — Database wrapper with migrations and query builder
- `Guardian` — JWT authentication
- `Oban` — Background job processing with PostgreSQL backing

### Frontend: Vue 3

Three Vue 3 applications share a common component library:

| App | Purpose | Port |
|-----|---------|------|
| **Banking** | Internet banking (PIX send/receive, statements, transfers) | 3000 |
| **Admin** | Operations console (user management, monitoring, CCS) | 3001 |
| **Merchant** | Merchant portal (API keys, transactions, settlements) | 3002 |

Shared stack:
- **Vue 3** with Composition API and `<script setup>`
- **TypeScript** for type safety
- **Vite** for fast development and optimized builds
- **Tailwind CSS** for styling
- **Pinia** for state management
- **Vue Router** for client-side navigation

### Ledger: TigerBeetle

**TigerBeetle** is the purpose-built financial ledger providing:

- **77,000+ TPS** sustained throughput (validated via load testing)
- **Double-entry bookkeeping** — Every transfer has balanced debits and credits
- **Strong serializability** — Viewstamped Replication consensus protocol
- **Immutable transfers** — Financial safety guarantees, no edits or deletes
- **Deterministic execution** — Same inputs always produce same outputs

The ledger handles all account balances and transfer records. PostgreSQL stores metadata (user profiles, merchant configs, API keys).

### Automatic Failover

A circuit breaker pattern provides automatic failover from TigerBeetle to a PostgreSQL-based fallback ledger:

```
Normal:     Request → TigerBeetle (10K TPS, <10ms)
Failover:   Request → PostgreSQL Ledger (2K TPS, 45ms)
Recovery:   Request → TigerBeetle (automatic after health check passes)
```

Circuit states:
- **Closed** — All traffic to TigerBeetle (normal operation)
- **Open** — All traffic to PostgreSQL (after 3 consecutive failures)
- **Half-Open** — Test request to TigerBeetle (after 30s timeout)

### Messaging: NATS JetStream

**NATS with JetStream** handles asynchronous event processing:

- **PIX In/Out workflows** — Multi-step payment processing
- **Webhook delivery** — Reliable notification dispatch with retries
- **Ledger events** — Account balance change notifications
- **Audit logging** — Immutable event stream for compliance

Streams configured:
- `MONETARIE` — Main event stream (PIX transactions, account events)
- `MONETARIE_LEDGER` — Ledger-specific events (balance changes, transfers)

### Cache: Redis 7.2

**Redis** provides:

- **Session caching** — JWT token blacklisting and session data
- **Rate limiting** — Per-IP and per-API-key request throttling
- **Idempotency keys** — SHA256 hash caching for duplicate prevention (30-day TTL)
- **Real-time data** — Exchange rates, provider status, feature flags

### Database: PostgreSQL 16

**PostgreSQL** stores all persistent data except ledger balances:

- Users, merchants, and role-based permissions
- Account metadata and product definitions
- Transaction metadata and audit trails
- COSIF chart of accounts (59 accounts, 5 types)
- CCS compliance records

## Data Flow: PIX Payment

### PIX In (Receiving a Payment)

```
1. Provider Webhook → Phoenix API
2. Validate signature (HMAC-SHA256)
3. Publish to NATS (MONETARIE.pix.in)
4. Worker picks up event
5. Create transfer in TigerBeetle (debit provider, credit merchant)
6. Update PostgreSQL metadata
7. Notify merchant via webhook
8. Push real-time update via WebSocket
```

### PIX Out (Sending a Payment)

```
1. Merchant API request → Phoenix API
2. Validate balance in TigerBeetle
3. Create pending transfer (debit merchant, credit provider)
4. Publish to NATS (MONETARIE.pix.out)
5. Worker sends to PIX provider
6. Provider confirms → update transfer status
7. Notify merchant via webhook
```

## Security

- **mTLS** — Mutual TLS for provider communication
- **JWT** — Token-based API authentication with refresh rotation
- **RBAC** — Role-based access control (owner/manager/operator)
- **Rate Limiting** — Per-IP and per-key limits with Redis backing
- **Encryption** — AES-256-GCM for sensitive data at rest
- **Audit Trail** — Complete operation logging for 5-year retention

## Multi-Tenant Architecture

```
Institution A (ISPB: 12345678) ─┐
Institution B (ISPB: 87654321) ─┼─→ Monetarie Core ─→ BACEN (PIX/CCS/COSIF)
Institution N (ISPB: nnnnnnnn) ─┘
```

Each institution has isolated:
- Database schemas (logical separation)
- TigerBeetle ledger codes
- NATS subject prefixes
- Redis key namespaces
- Monitoring dashboards
