Solution Architecture & Diagrams
System context, container & component architecture, event-trigger flow, deployment topology and key data flows for the Engagement & Loyalty Platform, deployed inside the the Bank-controlled environment.
Architecture Principles
| # | Principle | Implication |
|---|---|---|
| 1 | Bank-controlled data | All PII & transactions remain inside the Bank; only catalogue/fulfilment calls leave via controlled APIs. |
| 1b | Event-triggered engagement | Bank events drive rewards in real time; trigger rules & prize tables are configuration, not code. |
| 2 | Configuration over code | Rules, campaigns, catalogue & templates are data; changes need no redeploy. |
| 3 | Event-driven & idempotent | Transactions processed via queues with idempotency keys → exactly-once accrual. |
| 4 | Modular services | Independent, independently scalable services per domain. |
| 5 | Ledger as source of truth | Immutable, auditable double-entry-style loyalty ledger. |
| 6 | Secure by design | Zero-trust, RBAC, encryption, masking, full audit (see CR-SEC-009). |
| 7 | Observable | Central logs, metrics, traces, health & alerts. |
System Context (C4 — Level 1)
Container Architecture (C4 — Level 2)
Event-Trigger Flow (Scratch Card Issue & Reveal)
The heart of the Engagement Suite: external bank systems POST lifecycle events to POST /api/v1/events; the trigger engine resolves the account, evaluates active trigger rules (and advances milestones), and on a match issues a scratch card with its prize drawn at issue time and stored hidden. The customer reveals it in the the Bank's mobile app app via POST /api/v1/scratch-cards/:id/scratch, which posts an idempotent points credit to the ledger (for POINTS prizes). Every step is idempotent — event by eventRef, ledger writes by key evt:{eventRef}:{triggerId} / scr:{scratchCardId}.
POST /api/v1/events → trigger evaluation → scratch card issue (prize hidden) → app reveal → ledger credit. Spend accrual (Figure 3) continues in parallel and feeds spend milestones via the internal CARD_SPEND source.Component Inventory (Apps & Services)
Runtime components and their ports. core-api mounts the new event/trigger/scratch-card/milestone modules and enables CORS for the app, portal and admin origins.
| Component | Port | Role |
|---|---|---|
| core-api | 3001 | NestJS core; accrual, ledger + events / triggers / scratch-cards / milestones; CORS for :4002, :4005, :5173. |
| config-service | 3004 | Config, capabilities, approvals, audit. |
| mis-reporting | 3005 | MIS & reporting. |
| merchant-service | 3006 | Merchant onboarding & funded offers. |
| campaign-engine | 3103 | Campaign evaluation. |
| loyalty-scheduler | 3104 | Batch jobs; also expires overdue scratch cards in the daily run. |
| axis-txn-provider | 3101 | Transaction provider (renamed from iob-txn-provider). |
| axis-comms-gateway | 3102 | Comms gateway (renamed from iob-comms-gateway). |
| transaction-simulator | 4001 | Transaction simulator. |
| rewards-portal | 4002 | Rewards portal; ?card= deep link + Scratch Cards & Milestones sections. |
| comms-viewer | 4003 | Comms viewer. |
| sample-feeder | 4004 | Sample event/data feeder. |
| axis-bank-app | 4005 | NEW — the Bank's mobile app sample app: triggers events & renders the scratch-card journey. |
| admin-dashboard | 5173 | Vite admin; Triggers & Scratch Cards pages. |
Accrual Component & Sequence
Points Lifecycle & State Machine
Every accrued point lot moves through an explicit, auditable lifecycle. Each transition is a ledger_entry on the immutable ledger; the point_balance buckets (pending, available, locked, lifetime) are projections of the current state across a customer's lots.
| State | Balance bucket | Entered by | Exits to |
|---|---|---|---|
| Pending | pending | Transaction ingested, awaiting eligibility/settlement window. | Available · Reversed |
| Available | available | Accrual posted (ACCRUAL credit). | Locked · Reversed · Expired |
| Locked | locked | Redemption request reserves points (hold). | Redeemed · Available (release) |
| Redeemed | — | Atomic debit committed (REDEMPTION debit). | Fulfilled · Available (compensation) |
| Reversed | — | REVERSAL entry referencing original (clawback/refund). | terminal |
| Expired | — | EXPIRY sweep at lot validity end (FIFO). | terminal |
Domain Events & Outbox
Services communicate state changes as immutable domain events published via the transactional outbox: each state change writes its business row and an outbox_event row in the same DB transaction; a relay drains the outbox to the bus (Kafka/RabbitMQ) at-least-once. Consumers are idempotent on event_id, giving effectively-once processing without distributed transactions.
| Event | Producer | Key consumers | Effect |
|---|---|---|---|
| TransactionIngested | ingestion-svc | accrual-svc | Triggers eligibility & rule evaluation. |
| PointsAccrued | ledger-svc | campaign-svc, notification-svc, reporting-svc | Updates balance projection, milestone progress, statements. |
| AccrualReversed | ledger-svc | campaign-svc, notification-svc, recon | Clawback; recomputes affected milestone progress. |
| MilestoneUnlocked | campaign-svc | ledger-svc, notification-svc | Posts bonus accrual; sends reward notification. |
| RedemptionRequested | redemption-svc | ledger-svc | Locks points (reservation/hold). |
| PointsLocked | ledger-svc | redemption-svc | Confirms hold; saga proceeds to fulfilment. |
| RedemptionFulfilled | redemption-svc | ledger-svc, notification-svc, reporting-svc | Commits debit; issues voucher; confirms to customer. |
| RedemptionFailed | redemption-svc | ledger-svc, notification-svc, recon | Triggers compensation (release lock); logs exception. |
| PointsExpired | ledger-svc | notification-svc, reporting-svc | Posts EXPIRY entries; reduces available balance. |
| SettlementGenerated | merchant-svc | reporting-svc, finance | Merchant-funded liability billed for period. |
Redemption Saga & Compensation
Redemption spans the Ledger and an external fulfilment partner, so it is orchestrated as a saga by redemption-svc: a reversible lock → debit → fulfil sequence with an explicit compensation path. The lock keeps the customer's available balance correct while the (slower, externally-dependent) fulfilment completes, and guarantees no points are lost or double-spent if a step fails (FR-M4-05, NFR-04).
- Authorise — Customer selects a reward in the the Bank channel; step-up OTP (FR-M4-04) verified; eligibility & available balance checked against Ledger & Catalogue.
- Lock — Redemption-svc reserves points (Available → Locked);
RedemptionRequested/PointsLockedevents emitted. - Fulfil — Partner voucher API or CBS credit instruction (statement credit / cashback) invoked with the redemption idempotency key, timeout & circuit breaker.
- Commit — On success the locked points are debited (Locked → Redeemed), voucher stored in the vault, history updated,
RedemptionFulfilledemitted. - Compensate — On failure/timeout the saga releases the lock (Locked → Available), emits
RedemptionFailed, notifies the customer and logs a reconciliation exception. Slow-but-not-failed fulfilment is parked and retried (graceful degradation) rather than auto-reversed.
Deployment Topology
Integration Patterns
| Pattern | Used for | Notes |
|---|---|---|
| Batch file (SFTP) | Daily txn / master loads | Checksums, control totals, idempotent re-load. |
| Streaming / queue | Near-real-time txns & events | At-least-once delivery + idempotency keys. |
| Synchronous REST | Customer redemption, admin | OAuth2/mTLS, timeouts, circuit breakers. |
| Webhooks/callbacks | Fulfilment status | Signed payloads, retry with backoff. |
| Outbox pattern | Reliable event publication | Transactional outbox → bus → consumers. |
Secured Integration & Signature Verification
Value-bearing calls that cross a trust boundary — redemption requests from the Bank channels, fulfilment callbacks from partners, and CBS credit instructions — are authenticated and integrity-protected at the application layer on top of mTLS. Each request carries a digital signature (HMAC-SHA256, or RSA-PSS/ES256 by key id), a nonce and a timestamp; the gateway and target service verify signature + nonce + timestamp window before any side effect, then apply the idempotency key. Responses on the redemption path and inbound webhooks are likewise signed. Scheme, headers and worked examples are in CR-API-006; key management & rotation in CR-SEC-009.
Caching & Data Consistency
The Ledger is the single source of truth; point_balance is a read model (CQRS-style projection) maintained from ledger entries, and Redis caches hot reads. To keep these consistent the platform applies write-through invalidation keyed to ledger commits.
| Read model / cache | Built from | Consistency & invalidation |
|---|---|---|
| point_balance (projection) | PointsAccrued/Reversed/Expired, redemption commits | Updated in the same transaction as the ledger entry (or via outbox consumer); reconciled nightly against the ledger entry-sum — divergence raises an alert. |
| Balance cache (Redis) | point_balance projection | Invalidated on every ledger commit for the account; short TTL backstop; cache-aside read with single-flight to avoid stampede. |
| Catalogue cache (Redis) | reward_catalogue, stock | TTL + explicit bust on catalogue/stock change events; stock decrements are authoritative in DB, not cache. |
| Rules / config cache | accrual_rule, config_param | Versioned; busted on activation (maker-checker) so rule changes take effect without redeploy. |
Reconciliation & Settlement
Two scheduled control flows close the loop between the Engagement Suite, source systems and partners (FR-M8-02, FR-M5-02). Both write to the reconciliation / recon_exception and settlement tables and feed the exception workflow.
- Reconciliation (daily): accrual & redemption counts/sums are matched against source files, fulfilment partner reports and CBS credit confirmations; variances become
recon_exceptionrows with an ageing/assignment workflow. Unmatched fulfilments drive auto-compensation of stuck redemptions. - Settlement (periodic): merchant-funded eligible transactions are aggregated into
settlement/settlement_line, the funded liability computed and billed; outputs feed finance and theSettlementGeneratedevent. - Idempotent & restartable: both jobs are keyed by run-date/scope so re-runs are safe; control totals & checksums guard batch loads.
Resilience & Scaling
- Stateless services autoscale on CPU/queue-depth; workers scale for batch windows.
- Idempotency keys + outbox guarantee no double accrual/redemption.
- Circuit breakers & retries with backoff around partner calls; graceful degradation (queue redemptions if fulfilment slow).
- HA databases with synchronous replicas; async DR replica; automated backups (RPO ≤ 15 min).
- Caching for catalogue & balances; cache invalidation on ledger commit.
Scalability & Capacity
Capacity targets are derived from the NFRs (NFR-01..03): 10M+ cards, 50M+ monthly transactions, accrual ≤ 2s (API) / ≥ 1,000 txn/s (batch), redemption P95 ≤ 1.5s.
| Dimension | Strategy |
|---|---|
| Service scaling | Stateless pods scale horizontally; HPA on CPU and on Kafka consumer lag / queue depth; batch workers scale up during ingestion windows and down after. |
| Throughput | Partitioned Kafka topics keyed by account_id preserve per-account ordering while parallelising across consumers; accrual is embarrassingly parallel per account. |
| Data growth | ledger_entry & transaction range-partitioned by month (see CR-DAT-005); cold partitions archived to the warehouse; read replicas for reporting/balance reads. |
| Sharding path | Account-id is the natural shard key should a single Postgres cluster be outgrown; the projection model isolates write hotspots from read traffic. |
| Backpressure | At-least-once + idempotency lets the system shed load to the queue under spikes; redemption degrades gracefully (park & retry) if fulfilment is slow. |
| Autoscaling triggers | Queue lag > threshold, CPU > 70%, P95 latency SLO burn; scale-in guarded by cool-down to avoid flapping during batch. |
Observability & SLOs
Per NFR-09, the platform emits the three pillars plus health and alerting (Prometheus/Grafana, ELK, OpenTelemetry — see CR-APP-007). Every request and event carries X-Request-Id/trace context for end-to-end correlation across services and the bus.
| Signal | What is captured |
|---|---|
| Logs | Structured JSON with correlation id, actor, masked identifiers; financial & config events also written to the immutable audit_log. |
| Metrics | RED/USE per service; domain KPIs: accrual lag, accrual error rate, redemption success %, fulfilment latency, queue depth, points-liability. |
| Traces | Distributed traces across gateway → service → DB → bus → consumer; saga spans for redemption. |
| Health | Liveness/readiness probes; synthetic checks for redemption & balance read paths. |
| Alerts | SLO burn-rate alerts, recon variance, budget threshold breach, DLQ growth, partner circuit-breaker open, signature-failure / nonce-replay spikes. |
audit_log (hash-chained / WORM) that is forwarded to the the Bank SIEM; access to logs and audit records is itself logged. Full retention, what-is-logged and SIEM detail in CR-SEC-009.| SLO | Target | Tied to |
|---|---|---|
| Redemption availability | 99.9% | NFR-03 |
| Redemption latency (P95) | ≤ 1.5s | NFR-01 |
| Accrual freshness (near-real-time) | ≤ 2s API / streaming lag < 60s | NFR-01 |
| Ledger ↔ balance integrity | 0 unreconciled at nightly close | NFR-04/06 |
High Availability & Disaster Recovery
The platform runs active across availability zones within the primary the Bank site with an active-passive secondary site for DR, meeting RPO ≤ 15 min and RTO ≤ 2 h (NFR-10).
| Aspect | Approach | Target |
|---|---|---|
| In-site HA | Multi-AZ stateless pods; synchronous DB replica; replicated bus; auto-failover. | 99.9% (NFR-03) |
| DR failover | Warm standby site, async replication, DNS/GSLB cutover, runbook + periodic drill (PRE-PROD). | RTO ≤ 2 h |
| Data loss | Async replication + WAL/PITR backups. | RPO ≤ 15 min (NFR-10) |
| Degradation | Read-only balance/catalogue browsing remains available if write path is impaired; redemptions queued. | graceful |
Technology Mapping
Concrete stack choices are detailed in CR-APP-007 (Application Structure & Tech Stack); data design in CR-DAT-005; security zoning in CR-SEC-009.