--- id: HLD-ATB parent_ids: [UC-001, UC-002, UC-003, UC-004, UC-005, UC-006, UC-007, UC-008, UC-009, UC-010, UC-011, UC-012, UC-013, UC-014, UC-015, UC-016, UC-017, UC-018, UC-019, UC-020, UC-021, UC-022, UC-023, UC-024, UC-025, UC-026] version: 3.0.0 status: Draft — Stage 9 design; Gate 9.1 passed, review pending last_cr: CR-001 --- # High-Level Architecture Design — Agriculture Trading Backoffice | Field | Value | |---|---| | **System** | Agriculture Trading Backoffice (ATB) | | **Pattern** | FastAPI modular monolith with React/TypeScript client; PostgreSQL tenant RLS | | **Technology authority** | `tech-profile.yaml` | | **Architecture baseline** | Stage 7 patterns approved by human lead (`DEC-021`) | | **Stage 9 status** | Full-breadth module ownership and service boundaries designed; runtime validation pending | | **Requirements scope** | 26 UCs, 54 FRs; Stage 8 SRS catalog | ## 1. Deployment and Trust Boundary React SPA communicates with the FastAPI API over HTTPS and uses the configured Keycloak OIDC/PKCE identity flow. The API validates the configured JWT bearer credentials. Exact session termination/revocation semantics remain open under `AMB-009`; no token algorithm, lifetime or revocation SLA is invented here. Tenant membership and role are resolved server-side before a transaction-local PostgreSQL tenant context is established. RLS policies scope every tenant-owned row. A client tenant selector never confers authorization. The API, outbox publisher, and workers run as separately scalable processes from one modular-monolith codebase. PostgreSQL is the authoritative source for domain state, financial/stock ledgers, audit, and outbox. Valkey is used for cache and event delivery only; it is not the source of truth. Object storage is behind a tenant-aware document port; production provider, region, encryption configuration, and retention behavior remain unselected. Hosting provider and topology sizing remain provider-neutral. ## 2. Module and UC Ownership | HLD Component | Owning UCs / FR scope | Responsibility and boundary | LLD | |---|---|---|---| | `HLD-IAM` | UC-001 / FR-AUTH-001–003 | OIDC session validation, authorization policy, logout application contract; membership is owned separately | LLD-001 | | `HLD-TENANCY` | UC-018/019 / FR-TENANTLIFECYCLE-001, FR-TENANTMEMBERSHIPCONTEXT-001/002 | Tenant control-plane lifecycle, membership administration, verified active context | LLD-002 | | `HLD-ISOLATION-AUDIT` | UC-017/020 / tenant isolation, audit and privileged support FRs | RLS wrapper, tenant ownership for async/export/file/cache paths, append-only mutation audit, controlled support access | LLD-002 | | `HLD-MARKET-DESK` | UC-002 / FR-MKT-001/002 | Manual APMC observation, arrival, price range and modal rate capture | LLD-007 | | `HLD-REPORTING` | UC-003/015 / analytics and dashboard FRs | Read models and tenant-scoped reports; no authoritative ledger writes | LLD-005 | | `HLD-PROCUREMENT` | UC-004 / procurement contract, credit terms and levy FRs | Sauda, supplier terms, modal-price comparison, configured levy computation | LLD-004 | | `HLD-RECEIVING` | UC-005 / inward receipt and GRN FRs | Gate entry, manual weighment, calculation and atomic GRN posting | LLD-003 | | `HLD-QUALITY` | UC-006 / QC inspection, hold/release, lineage FRs | Quality measures, state machine, quality calculation, lot lineage | LLD-003 | | `HLD-INVENTORY` | UC-007 / stock, capacity and transfer FRs | Append-only double-entry movement ledger and derived positions | LLD-003 | | `HLD-SALES` | UC-008 / contract, credit check, allocation FRs | Sales contract and atomic eligible-lot reservation | LLD-004 | | `HLD-DISPATCH` | UC-009 / dispatch, manifest, delivery FRs | Eligible dispatch transitions, manual outward weighment, POD references | LLD-004 | | `HLD-FLEET` | UC-010 / FR-FLEETREGISTRY-001 | Tenant fleet master and maintenance assignment exclusion | LLD-009 | | `HLD-RECEIVABLES` | UC-011 / receivable, credit, receipt FRs | Immutable receivable events, exposure/lock, receipt and compensating reversal | LLD-004 | | `HLD-PAYABLES` | UC-012 / FR-SUPPLIERPAYABLES-001 | Accepted-GRN payable projection and aging; no payment execution connector | LLD-004 | | `HLD-EXPENSES` | UC-013 / FR-OPERATINGEXPENSES-001 | Balanced operational-expense vouchers and cash/bank ledger link | LLD-009 | | `HLD-EVENTS-ALERTS` | UC-014 / FR-OPERATIONALALERTS-001 | Transactional outbox, idempotent event consumption, alert lifecycle | LLD-005 | | `HLD-MASTERDATA` | UC-016 / FR-MASTERDATA-001/002 | Tenant-scoped commodity, grade, supplier, customer and godown reference data | LLD-008 | | `HLD-PRIVACY-INCIDENT-LIFECYCLE` | UC-021–024 / purpose, rights, breach, retention FRs | Fiduciary-scoped privacy records, evidence, legal holds and controlled lifecycle | LLD-006, LLD-011 | | `HLD-PROCESSOR-GOVERNANCE` | UC-025 / FR-PROCESSORGOVERNANCE-001 | Operator-controlled processor/subprocessor inventory and due diligence | LLD-011 | | `HLD-TENANT-POLICY` | UC-026 / FR-TENANTOPERATINGPOLICIES-001 | Effective-dated tenant policy, business-owner confirmation, workflow gating | LLD-010 | Bounded contexts may share the same deployment and PostgreSQL cluster; ownership boundaries are enforced in application modules and transaction/repository interfaces. Cross-context state changes use explicit commands/events, not direct mutation of another module's tables. ## 3. Standard Command, Query and Transaction Template 1. API dependency validates identity and resolves role and active tenant membership; system/platform administration uses a distinct control-plane authorization policy. 2. Command schema validates format and source-defined invariants; idempotency key is required for retryable posting/state-changing operations. 3. Application service opens a PostgreSQL transaction, sets verified tenant context transaction-locally, then reads/writes under RLS and applicable constraints. 4. A business transition, its immutable audit record, and any outbox record commit atomically. Financial and stock history is corrected with compensating entries. 5. Queries use tenant-filtered repository contracts and bounded pagination. Report projections are rebuildable from authoritative records and do not silently replace the ledger source. 6. Worker consumers validate tenant/resource ownership in the job payload, establish their own tenant context, and process at least once with idempotent effects. They never inherit ambient request state. ## 4. Cross-Context Patterns - **Isolation and audit:** Approved Stage 7 `DEC-021` patterns; detailed controls in LLD-002 and `database_design.md`. - **Outbox/events:** PostgreSQL outbox is durable source; Valkey Streams is delivery transport; retries are at-least-once, consumers are idempotent. No exactly-once claim. - **Ledger integrity:** Stock, receivables and cash/bank postings are append-only balanced journals; current positions/exposure are derived or transactionally maintained projections with reconciliation. - **Policy:** Effective-dated tenant values are versioned; an unreviewed value blocks only affected risk-sensitive operations. - **Privacy:** Purpose, responsible fiduciary, tenant/platform scope and sensitivity remain separate metadata; legal deadlines/retention durations are configurable approved inputs, not constants (`AMB-006`). - **External services:** Keycloak is configured for identity. No weighbridge or payment execution integration is added; messaging channel and document-storage production providers remain unselected (`AMB-009`). ## 5. Quality and Operational Constraints - Availability ≥99.9% monthly; RTO ≤4 h; RPO ≤15 min; encrypted daily PITR backups retained 35 days and quarterly restore exercises (`BRD-NFR-011`). - Capacity validation envelope: 50 tenants, up to 25 named users/tenant, 250 concurrent active users; report validation at 50,000 ledger rows/tenant; provisional load scenario 200 documents/tenant/operating day with 5× peak-hour burst. No fixed document quota; fair-share thresholds require test evidence (`BRD-NFR-004`, `BRD-NFR-012`, `AMB-008`). - Reports obey FR-specific targets, including dashboard ≤1.5 s and sub-second 20-day report where stated; Stage 13+ load evidence is still required. - Currency/weight precision, privacy handling, and OWASP ASVS v5.0.0 Level 2 trace to source NFRs; exact applicability and legal schedule remain reviewable under `AMB-006`. ## 6. Design Status and Review Points This document completes the Stage 9 logical decomposition; supporting endpoint, entity/constraint, and adapter contracts are in `api_design.md`, `database_design.md`, and `integration_design.md`. It is a design artifact, not implemented/runtime validation. Before construction, confirm the endpoint and entity contracts at Gate 9.1. Provider deployment choices, exact Keycloak logout contract, tax identifier validation, privacy legal timing/retention, and load-derived fairness thresholds remain open as recorded ambiguities.