Bank8:Lending - Detailed Design Document
1. Scope & Context
Bank8:Lending owns: the lending schema (schema-per-service - domain
tables + lending.outbox / lending.audit_journal producer tables),
lending products, versioned schedule templates, origination,
disbursement, repayment allocation, the accrual and due cycle, the
delinquency ladder and collections queue, restructure and write-off,
collateral and guarantors, and the bank8:lending:* event family.
It does NOT own: money movement or balances (Bank8:Ledger), payment orchestration (Bank8:Payments), the book of account (Bank8:Accounting), prudential measurement (Bank8:Risk), AML detection (Bank8:Compliance), tenant-authored hooks (Sentin8:Func), schedule timing (Sentin8:Cron), or document bytes (Sentin8:Storage).
A loan is a ledger.accounts row (tside = 'ASSET'). Lending owns
the contract - what is owed, when, and what happens when it is not
paid - and the ledger owns the position.
2. Runtime Architecture
Boot is shell-owned. build_state adds wiring and spawns the
embedded cycle worker - a Bus SSE consumer that reacts to cycle
events from Sentin8:Cron and drives accrual, due marking, and the
delinquency ladder.
Money movement is always a ledger call. Lending builds a posting
batch and submits it to POST /v1/postings. It never writes
ledger.*; it holds no grant on that schema.
2.1 Posting mapping (normative)
The ledger classifies an instruction by its type, not by
arithmetic: debits_source() (bank8-ledger/src/handlers/postings.rs)
treats WITHDRAWAL | FEE_APPLICATION | TRANSFER_OUT | REVERSAL_DEBIT | ADJUSTMENT_DEBIT as debit-direction, and the balance update applies
debit -= amount, credit += amount. On an asset (loan) account a
credit therefore increases the outstanding debt. The mapping below is
the only correct one and must not be inverted:
| Business event | Batch legs | Effect |
|---|---|---|
| Disburse | WITHDRAWAL: customer DDA → loan account | DDA down, loan debt up |
| Principal repayment | WITHDRAWAL: customer DDA → loan account | DDA down, loan debt down |
| Interest repayment | WITHDRAWAL: customer DDA → Interest Received internal acct | DDA down, income up |
| Fee at disbursement | WITHDRAWAL: loan account → Upfront Fee Income | Debt up, income up |
| Accrual (daily) | ACCRUAL: loan account at address ACCRUED | Accrual bucket up, debt unchanged |
| Interest application | TRANSFER_OUT: loan ACCRUED → loan DEFAULT | Accrual bucket down, debt up |
| Overpayment refund | WITHDRAWAL: loan account → customer DDA | Debt reduced to credit, cash out |
| Write-off | WITHDRAWAL: loan account → Principal Write-off / Interest Write-off | Debt down, loss recognised |
Accrual and application require address-scoped instructions
(CAP-2); until that lands, accrual is recorded in
loan_accruals and applied at cycle end as a single interest repayment.
3. Data Model
| Table | Purpose | RLS tier |
|---|---|---|
loan_products / loan_product_versions | Lending product definitions, versioned; a loan pins its opening version | env |
schedule_templates / schedule_template_versions | Versioned, simulatable amortization definitions (the WASM-referencable unit) | env |
loan_applications | Origination state machine (draft, submitted, approved, rejected) | env |
loans | The contract: ledger account binding, commitment, principal, term, status, schedule revision | holder + env |
loan_schedules / loan_schedule_periods | Revisioned schedules and their per-period principal/interest/fee split and paid state | holder + env |
loan_transactions | Every movement with its ledger posting id and idempotency key | holder + env |
loan_accruals | Per (loan, date) accrual records | env |
payment_allocations | How each repayment split across penalty/fee/interest/principal | holder + env |
delinquency_state / delinquency_actions | Current ageing state and pause/restore actions | env |
restructures | Reschedule and re-age records with the superseded revision | holder + env |
write_offs | Write-off and charge-off records with the posting id | holder + env |
collateral / guarantors | Security with valuation and coverage | holder + env |
rate_changes | Floating-rate repricing events | env |
lending.outbox / lending.audit_journal | Producer tables | FORCE |
Money precision: all amounts are NUMERIC(28,10). Rounding is
applied per period at generation time and the residual is absorbed by
the final period, so the schedule closes exactly.
4. API Surface
| Audience | Routes | Auth gate | Events emitted |
|---|---|---|---|
| Products | GET/POST /v1/loan-products, GET /v1/loan-products/{id}, POST …/{id}/versions | bank8:lending:products:read / :write | product:upserted |
| Templates | GET/POST /v1/schedule-templates, GET /v1/schedule-templates/{id}, POST …/{id}/versions, POST …/{id}/simulate | bank8:lending:schedules:read / :write | schedule:generated |
| Origination | GET/POST /v1/applications, GET /v1/applications/{id}, POST …/{id}/approve, POST …/{id}/reject | bank8:lending:applications:read / :write | application:{submitted,approved,rejected} |
| Loans | GET/POST /v1/loans, GET /v1/loans/{id}, GET …/{id}/schedule, GET …/{id}/transactions, GET …/{id}/arrears | bank8:lending:loans:read / :write | loan:opened |
| Schedule | POST /v1/loans/schedule/preview, POST /v1/loans/{id}/schedule/regenerate | bank8:lending:schedules:write | schedule:regenerated |
| Money | POST /v1/loans/{id}/disburse, POST /v1/loans/{id}/repay, POST /v1/loans/{id}/refund-overpayment | bank8:lending:loans:write | loan:{disbursed,repayment:applied} |
| Lifecycle | POST /v1/loans/{id}/restructure, POST /v1/loans/{id}/write-off, POST /v1/loans/{id}/charge-off | bank8:lending:loans:write | loan:{restructured,written_off} |
| Collections | GET /v1/collections/queue, POST /v1/loans/{id}/delinquency/pause, POST …/resume | bank8:lending:collections:read / :write | loan:delinquent |
| Security | GET/POST /v1/loans/{id}/collateral, GET/POST /v1/loans/{id}/guarantors | bank8:lending:collateral:read / :write | - |
| Internal | POST /v1/internal/steps/execute (Flow proxy-back), POST /v1/internal/schedules/run (Cron proxy-back: accrual, due, delinquency) | Shield + M2M | loan:accrued, loan:delinquent |
| Admin/SDUI | GET /v1/admin/ui/{page}, GET /v1/admin/overview | bank8:lending:admin | - |
Schedule preview contract (writes nothing; journaled like
/v1/contracts/simulate):
POST /v1/loans/schedule/preview
{ "product_version_id": "...", "principal": "25000.00",
"denomination": "CAD", "start_date": "2026-12-01",
"template_version_id": "..." }
200 { "template_version_id": "...", "periods": [
{ "period_no": 1, "due_date": "2027-01-01",
"principal_due": "…", "interest_due": "…", "fee_due": "…" } ],
"totals": { "principal": "25000.00", "interest": "…" },
"closes_to_zero": true }
422 when the generated schedule does not amortize to zero
Allocation precedence is declared by the product version
(allocation_order, default penalty, fee, interest, principal) and is
applied per repayment; the split is persisted in payment_allocations
so a repayment is always explainable after the fact.
Admin/SDUI pages: overview, products, templates,
applications, loans, collections, collateral, config.
5. Cross-Cutting Concerns
- Auth: platform token pipeline; Shield is the only gate.
- Tenant + RLS:
set_tenant_contexton the same connection as the query; explicitWHERE env_id = $N; every tableENABLE+FORCE ROW LEVEL SECURITY. Loan-level rows additionally carry holder scoping so a customer sees only their own loans. - Identity: the cycle worker's certificate-presenting Bus client is the single outbound identity (CERTFREE-4V); a failed mint fails the consume closed.
- Ledger interaction: posting via
POST /v1/postings; reads via the public account, balance, and product APIs. A cross-schema grant onledger.*is a defect. - Idempotency: every movement carries a deterministic key
(
loan:{id}:{kind}:{reference}); the ledger's partial unique index on(env_id, idempotency_key)absorbs a retry. Accrual is unique per(loan, date); due marking per(loan, period, date); delinquency events per(loan, transition). - Event emission: MemBus refresh (fail-soft) → outbox row in the domain transaction → relay → Bus.
- Audit:
lending.audit_journalin the same transaction plus Sys audit push. Approval, restructure, write-off, and delinquency pause all require an audited actor. - TLS: PQ-TLS via
sentin8-tls.
6. Failure Modes & Recovery
| Failure | Behaviour |
|---|---|
| Ledger rejects a posting (module guard, balance, idempotency conflict) | Loan state not advanced; the ledger's reason is surfaced verbatim rather than rewritten. |
| Ledger unreachable | The movement fails closed with a retryable error; no local-only money state is ever recorded. |
| Local commit fails after the ledger accepted | A compensating reversal posting is issued and an alert raised - the pair is reconciled, never left ambiguous. |
| Cron retries an accrual run | Absorbed by the (loan, date) unique key. |
| Duplicate repayment submission | Absorbed by the ledger's idempotency key; the original result is returned. |
| Schedule generation cannot close to zero | Rejected at preview and at generation (422); no plug, no silent residual. |
| Cycle worker crash | Replays from the Valkey stream; all handlers are idempotent. |
7. Concurrency & Performance Model
Pool capped (3–5). The hot path is the daily cycle: accrual and due
marking over the active loan set, batched per environment with a
bounded page size, single-writer per environment. Repayment is
per-loan row-locked (SELECT … FOR UPDATE on the loan) so two concurrent
repayments cannot both allocate against the same unpaid period; the
ledger's balance-row serialization handles the money side.
Schedule generation is pure computation and can run concurrently.
8. Invariants
- Loan before money. A loan must be opened and not disbursed before a disbursement; a disbursement cannot exceed the remaining commitment.
- Every movement is a posting. No loan balance is ever mutated
locally;
loan_transactions.ledger_posting_idis mandatory for money rows. - Schedules close to zero.
SUM(principal_due) == principal_disbursedwithin currency scale, with the residual absorbed by the final period. - Allocation is explainable. Every repayment's split is persisted; the sum of allocations equals the repayment amount.
- Accrual is per-day unique. One accrual per
(loan, date). - Delinquency transitions are idempotent - one event per transition.
- History is additive. Restructure creates a new schedule revision and supersedes the previous; nothing is deleted. Write-off is a terminal status with postings.
- Product version is pinned. A loan's product version does not change implicitly; migration is explicit and audited.
- No cross-service table access. Lending never reads or writes
ledger.*,accounting.*,risk.*, orcompliance.*tables.
9. Testing Strategy
- Contracts crate - shared loan/schedule/allocation shapes for the SDK facade.
- Policy suite (
tests/policy.rs) - seeded scope-mirror text with the handler-action parity matrix. - DB invariants (
tests/db_invariants.rs, live bank8 DB): FORCE-RLS rejection;(loan, date)accrual uniqueness absorbs a duplicate cycle;payment_allocationssum equals the repayment; schedule principal sums to the disbursed principal; a write-off is terminal and produces a posting id; restructure leaves the prior revision readable; nolendingview referencesledger.*. - Amortization golden tests - hand-calculated schedules for equal-installment and equal-principal over 30/360 and actual/365, asserted to the cent, including the final-period residual.
- Allocation tests - partial payments, overpayment, penalty-first and principal-first orders.
- OpenAPI drift (
tests/openapi_drift.rs). - E2E - UI-only through the BFF: apply → approve → disburse → repay → view schedule, driven from eTeller and eBank.
10. Open Questions
- Whether the schedule generator executes as a ledger-side Func module
(fully sandboxed) or in-process with a Func hook at the boundaries.
Current position: in-process generator with a
scheduled_eventhook, because the schedule is a pure function of contract data. - Tranche disbursement on revolving products.
- Whether arrears include accrued-but-unapplied interest before the cycle boundary.
Architecture & Design: bank8:lending and its underlying concepts were designed by Hamid Jahanzad.