# Settlement

Settlement cycle management, netting calculations, reconciliation, and balance management between PIX participants.

## Prerequisites

- Understanding of PIX settlement mechanics
- Admin access with settlement permissions
- Backend running with NATS workers active

## Settlement Overview

PIX settlement occurs in two modes:

1. **Real-time**: Individual transaction settlement (pacs.008 -> pacs.002 -> STLD)
2. **Periodic netting**: BCB aggregates bilateral positions to minimize liquidity requirements

```mermaid
graph LR
    TX[Transaction] --> NET[Netting Cycle]
    NET --> CALC[Calculate Positions]
    CALC --> SETTLE[Settle Net Amounts]
    SETTLE --> RECON[Reconciliation]
```

## Settlement Workers

| Worker | Purpose | Schedule |
|--------|---------|----------|
| Scheduler | Initiates settlement cycles | Configurable interval |
| FileImporter | Imports BCB settlement files | On file arrival |
| CoreEventProcessor | Processes Core Banking events | Continuous |

### Scheduler

The Scheduler worker:
- Fetches transactions for the current settlement window (LIMIT 500K with 30s timeout)
- Groups by participant pair
- Calculates net positions
- Creates settlement records

## Reconciliation

The reconciliation module identifies discrepancies between:
- Internal transaction records
- BCB settlement confirmations
- Participant balance reports

```bash
# API endpoint
GET /api/v1/settlement/reconciliation
```

All reconciliation queries have a `LIMIT 10,000` safety bound to prevent OOM on large datasets.

## Balance Management

| Endpoint | Method | Description |
|----------|--------|-------------|
| `/api/v1/settlement/balances` | GET | Current balances per participant |
| `/api/v1/settlement/balances/:ispb` | GET | Balance for specific participant |

Balance operations are wrapped in `Repo.transaction` with zero-amount validation to prevent accounting errors.

## Circuit Breaker

Inter-service calls (Settlement -> Dict, Settlement -> SPI) are protected by `SettlementService.CircuitBreaker`:

| State | Behavior |
|-------|----------|
| Closed | Normal operation |
| Open | Fail fast (after 5 failures) |
| Half-Open | Single probe request after 30s cooldown |

Only 5xx and transport errors trip the breaker. 4xx responses are client errors and do not affect circuit state.

## Settlement Events (NATS)

| Subject | Description |
|---------|-------------|
| `monetarie.settlement.cycle.started` | New settlement cycle initiated |
| `monetarie.settlement.cycle.completed` | Cycle completed successfully |
| `monetarie.settlement.reconciliation.discrepancy` | Discrepancy found |
| `monetarie.settlement.balance.updated` | Participant balance changed |

## Expected Outcome

After configuring settlement:

- Settlement cycles running on schedule
- Netting calculations producing correct bilateral positions
- Reconciliation identifying discrepancies
- Balance operations atomic and validated
- Circuit breaker protecting against cascading failures
