High-Level Design
Consolidated design that bridges the SRS to development — module designs, key algorithms, end-to-end flows, design decisions and how the platform realises its non-functional targets.
Purpose & References
This HLD turns the requirements in the SRS (CR-SRS-003) into a design developers can build against. It complements — and does not repeat — the Architecture (CR-ARC-004), DB Schema (CR-DBS-013) and API Spec (CR-API-006). Build tracking is governed by the Module Dev Checklist (CR-DCL-014).
Design Goals
| # | Goal | How it is met |
|---|---|---|
| 1 | Correct, auditable points | Immutable ledger as system of record; balances are a reconciled projection; exactly-once via idempotency keys. |
| 2 | Configurable, no redeploy | Rules/campaigns/catalogue/tiers/templates are versioned data; maker-checker gated. |
| 3 | Bank-controlled data | All PII/txn data inside the Bank; only catalogue/fulfilment/notification egress. |
| 4 | Scalable & resilient | Event-driven, stateless services, partitioned ledger, sagas with compensation. |
| 5 | Comprehensive rewards | Earn (base→tier→merchant-funded), tiers, pooling/transfer, redemption everywhere, integrity controls. |
Logical View
Thirteen functional modules over four data domains, fronted by an API gateway and an event bus. See Architecture Figures 1–2 for context & container views.
Module Designs
M1 — Accrual Engine
Responsibility: turn eligible transactions into ledger credits. Inputs: transaction events. Outputs: PointsAccrued / AccrualReversed events & ledger entries. Owns: accrual_rule, rule_version.
Earn calculation algorithm
# pseudocode — evaluated per eligible transaction points = 0 if not eligible(txn): record(excluded); return base = floor(txn.amount / rule.per_amount) * rule.points mult = 1 if matches(txn, rule.accelerator): mult *= rule.factor # MCC/merchant/channel mult *= tier_multiplier(account.active_tier) # M10 points = round(base * mult, rule.rounding) points += active_campaign_bonus(txn, account) # M2 hooks points = apply_caps(points, account, rule.caps) # per txn/day/cycle/lifetime post_ledger(account, +points, ref=txn.id, rule=rule.id, idem=txn.ext_ref)
idempotency_key = external_txn_ref. Re-delivery returns the original posting; reversal posts a compensating entry referencing the original (FR-M1-07).M2 — Campaign & Milestone Engine
Evaluates rules (segment + spend + count + MCC/merchant + channel + period, AND/OR groups), tracks per-customer progress, unlocks rewards once, enforces budgets with auto-pause. Owns: campaign, milestone, segment, campaign_enrolment, milestone_progress. Listens to accrual/transaction events; emits MilestoneUnlocked. Lifecycle rewards (welcome/anniversary/birthday/surprise) are date/event-triggered campaigns.
M3 — Loyalty Ledger
Append-only entries (ACCRUAL/REDEMPTION/REVERSAL/EXPIRY/ADJUSTMENT/CLAWBACK/TRANSFER/MIGRATION). point_balance (available/pending/locked/lifetime) is a projection rebuilt & reconciled nightly. Expiry uses FIFO over point_lot. See lifecycle state machine in Architecture §Points Lifecycle.
Atomic redemption debit
BEGIN SELECT available FROM point_balance WHERE account_id=? FOR UPDATE IF available < needed: ROLLBACK; raise INSUFFICIENT_BALANCE INSERT ledger_entry(REDEMPTION debit, locked) # lock first UPDATE point_balance SET available-=needed, locked+=needed COMMIT # then fulfil (saga); on success → commit lock to redeemed; on failure → reverse
M4 — Redemption & Fulfilment
Orchestrates burn as a saga: authorise → lock points → fulfil (voucher API / CBS credit / POS) → commit, with compensation on failure (auto-reverse + notify). Supports partial & points+cash, auto-redeem, charity, EMI waiver and partner transfer. See Architecture §Redemption Saga.
M5 — Merchant-Funded
Onboards merchants, configures funded offers, attributes eligible transactions, computes funded liability, generates settlement. Owns: merchant, merchant_offer, settlement.
M6 — Communication
Template engine (variables, locale, channel rendering) triggered by domain events; dispatches via the Bank gateways (Push/SMS/Email/WhatsApp/In-App) honouring consent & quiet hours; records delivery status. See Architecture §Domain Events.
M7 — Admin & Governance
RBAC (SSO + scopes), maker-checker workflow (segregation of duties), budgets and system parameters. Every change versioned and audited.
M8 — MIS, Reconciliation & Audit
Read-model reporting from the analytics store; nightly reconciliation of ledger vs source & fulfilment with exception workflow; immutable audit query. See Architecture §Reconciliation & Settlement.
M9 — Customer Experience
Customer API + embeddable the Bank-branded UI for points, catalogue, redemption and voucher vault inside the Bank channels.
M10 — Tiers & Status
Scheduled tier evaluation against tier_rule (qualification window, spend/points thresholds), upgrade/downgrade with grace, tier benefits feeding the accrual multiplier. Emits TierChanged → comms.
M11 — Integrity & Risk
Clawback on fraud/chargeback (compensating ledger entries), velocity/abuse controls on earn & referral, negative-balance recovery and a points-dispute workflow.
M12 — Transfer, Pooling & Partners
Family/supplementary pooling (account_pool), member gifting/transfer (points_transfer), partner-programme transfer at configured ratios (partner_program), and referral rewards.
M13 — Engagement: Event Triggers, Scratch Cards & Milestones
Responsibility: ingest external bank events and convert them into engagement rewards. Inputs: POST /api/v1/events (USER_REGISTERED, CARD_ACTIVATED, KYC_COMPLETED, UPI_TRANSACTION, BILL_PAYMENT, SALARY_CREDIT, FD_BOOKED) plus internal CARD_SPEND after each posted card transaction. Outputs: issued scratch cards, direct point grants and milestone progress; ledger credits post through M3 with idempotency keys (scr:{scratchCardId}, evt:{eventRef}:{triggerId}). Owns: bank_event (unique event_ref — replay-safe), trigger_rule (conditions JSONB: first_occurrence, min_amount_minor, max_per_window; weighted prize table), scratch_card (prize drawn hidden at issue; reveal idempotent; expires 30 days, 409 after expiry), milestone_def, milestone_progress (lifetime/weekly/monthly windows).
End-to-End Flows (design summary)
| Flow | Path | Key guarantees |
|---|---|---|
| Earn | Txn → ingest → eligibility → rule+tier+campaign → ledger credit → notify | Exactly-once; auditable; cap-bounded. |
| Milestone unlock | Accrual/txn events → progress update → threshold met → reward grant → notify | Once-per-customer; budget-guarded. |
| Redeem | Request → OTP → lock → fulfil → commit / compensate | Atomic; auto-reverse on failure. |
| Expiry | Nightly batch → FIFO lots due → expiry entries → near-expiry nudges | Grace-aware; reconciled. |
| Tier review | Scheduled eval → upgrade/downgrade w/ grace → benefit change → notify | Deterministic; auditable. |
| Settlement | Attribute funded txns → compute liability → settlement report | Reconciled; idempotent re-run. |
| Event → scratch card | Bank event → trigger match → scratch card issued (prize drawn hidden) → reveal → ledger credit → notify | Replay-safe on eventRef; reveal idempotent; expiry-guarded. |
Key Design Decisions
| ID | Decision | Rationale |
|---|---|---|
| ADR-01 | Immutable ledger + projected balances | Auditability & integrity; balances rebuildable from entries. |
| ADR-02 | Event-driven with transactional outbox | Reliable, decoupled processing; no lost events. |
| ADR-03 | Idempotency keys on all value mutations | Exactly-once accrual/redemption under retries. |
| ADR-04 | Saga + compensation for redemption | Safe distributed burn across ledger & external fulfilment. |
| ADR-05 | Config-as-data + maker-checker + versioning | No-deploy changes with governance & rollback. |
| ADR-06 | Monthly range-partitioning of ledger/txn | Scale to 50M+ txn/month; efficient archival. |
| ADR-07 | Tokenised identifiers, in-bank deployment | Data residency & reduced PCI scope. |
Error Handling & Idempotency Strategy
- All value-mutating operations carry an idempotency key; duplicate keys return the prior result.
- Transient failures retried with exponential backoff; partner calls wrapped in circuit breakers.
- Sagas compensate on failure (ledger reversal); exceptions captured for reconciliation.
- Consistent error model across APIs (see API §Error Model).
NFR Realisation
| NFR | Design mechanism |
|---|---|
| Performance / throughput | Stateless services, account-keyed partitions, caching, batch workers. |
| Integrity (exactly-once) | Idempotency keys + outbox + atomic ledger debit. |
| Availability / DR | Multi-AZ active, warm DR, RPO ≤15m / RTO ≤2h (see Architecture §HA/DR). |
| Security / residency | In-bank zones, mTLS, RBAC, tokenisation, audit (see CR-SEC-009). |
| Observability | Logs/metrics/traces + SLOs (see Architecture §Observability). |
Assumptions & Open Items
- Backend stack decided: Node.js (LTS) + TypeScript + NestJS; messaging (Kafka/RabbitMQ) confirmed at mobilisation — see CR-APP-007.
- Interface contracts with CBS/switch/channels/gateways finalised in Phase 1.
- Partner-programme transfer ratios & catalogue partners confirmed with business.
- Low-level design (LLD) per service produced during build, tracked in the Dev Checklist.