Digital Retail Lending Product
- Anand Nerurkar
- 6 days ago
- 32 min read
A digital lending platform can support multiple types of loans depending on the target customer segments (Retail, SME, Corporate) and business strategy. Typically, such platforms are designed to be modular and configurable to cater to secured, unsecured, short-term, and long-term loans. Here’s a breakdown:
1. Retail / Consumer Loans
Personal Loan (Unsecured)
Salary-based, self-employed, pre-approved offers
Instant disbursement using e-KYC and alternate credit scoring
Auto Loan / Two-Wheeler Loan
Secured against vehicle
Integration with RTO, dealer systems, and insurance APIs
Home Loan
Secured, long-tenure (10–30 years)
Requires property verification, legal opinion, and valuation integration
Consumer Durable Loan / BNPL (Buy Now Pay Later)
Instant credit for electronics, appliances, e-commerce transactions
Often zero-cost EMI
2. SME / MSME Loans
Working Capital Loan / Cash Credit
Collateral or unsecured
Based on GST filings, bank statements, cash flow analytics
Term Loan
Fixed tenure, secured against business assets
Invoice Discounting / Bill Discounting
Advance against unpaid invoices
Merchant Cash Advance
Linked to POS transactions or UPI inflows
3. Agri and Rural Loans
Crop Loan / Kisan Credit Card (KCC)
Seasonal repayment linked to harvest cycle
Equipment Financing
Tractors, irrigation pumps, solar solutions
4. Corporate / Institutional Loans
Project Finance
Large-scale infrastructure or manufacturing projects
Syndicated Loans
Multiple lenders participate
Trade Finance / Letter of Credit
Cross-border trade facilitation
5. Specialized / Emerging Loan Products
Education Loans
For higher studies in India or abroad
Green Loans
For renewable energy projects (solar rooftop, EV financing)
Microfinance / Nano Loans
Small ticket loans via mobile apps or UPI
P2P Lending
Platform enables matching borrowers with individual lenders
Architecture Implications
Configurable Product EngineSupports defining loan type, tenure, interest rate, collateral requirement.
Eligibility & Scoring ModuleUses alternate data (Aadhaar, PAN, GST, CIBIL, bank statements, social scoring).
Integration LayerAPIs with credit bureaus, eKYC, UPI, RTO, legal property databases, GSTN.
Regulatory ComplianceRBI/SEBI guidelines, AML/KYC, fair lending practices, audit trails.
Multi-channelMobile app, web, branch, partner (dealer, merchant) onboarding.
1. Loan Types Supported (MVP vs. Future Roadmap)
MVP (Launch Phase – 3 to 6 months)
Focus on high-demand, fast-turnaround loans:
Personal Loan (Unsecured)
Consumer Durable Loan / BNPL
Auto Loan / Two-Wheeler Loan
SME Working Capital Loan (Unsecured)
Invoice Discounting
Future Roadmap (Post-MVP – 6 to 18 months)
Expand into higher complexity products:
Home Loan / Mortgage
Education Loan
Green Loans / EV Financing
Corporate Term Loans / Project Finance
Microfinance / Nano Loans (Rural outreach)
2. Microservices Breakdown (Loan Type Coverage)
Microservice | Loan Types Supported | Key Functions |
Customer Onboarding Service | All | eKYC, Aadhaar, PAN, GST validation, CKYC |
Loan Application Service | All | Application intake, workflow orchestration |
KYC & Compliance Service | All | AML checks, PEP screening, regulatory reporting |
Credit Score Service | Personal, Auto, SME | CIBIL, Experian, internal credit scoring |
Loan Eligibility Service | Personal, Auto, SME | DTI ratio, alternate data scoring (bank/GST) |
Collateral Management Service | Auto, Home, Corporate | Asset valuation, lien marking, RTO/property APIs |
Loan Agreement Service | All | E-signature, agreement generation, e-stamping |
Loan Evaluation & Approval Service | All | Risk engine, rules-based + ML-based decisions |
Disbursement Service | All | UPI/NEFT/RTGS payouts, integration with CBS |
Repayment & Collection Service | All | EMI schedules, auto-debit, UPI mandates |
Fraud Detection Service (AI/ML) | All | Device fingerprinting, behavior analytics |
Notification Service | All | SMS, Email, WhatsApp updates |
Reporting & Analytics Service | All | MIS, regulatory, portfolio insights |
3. Azure Cloud Integration (Per Loan Type)
Core Azure Components
Azure AKS: Host all microservices (scalable containers)
Azure API Management (APIM): API gateway for internal/external partners
Azure Service Bus / Kafka (Event Hub): Event-driven orchestration (loan status updates, fraud triggers)
Azure SQL + Cosmos DB:
SQL for transactional data (loan contracts, repayments)
Cosmos DB for high-speed customer profiling, alternate credit scoring
Azure Cognitive Services: OCR for document extraction (PAN, Aadhaar, bank statements)
Azure AD B2C: Customer identity and access management
Azure Key Vault: Secure storage of credentials, keys, secrets
Azure Logic Apps / Durable Functions: Orchestration of workflows (KYC → Score → Approval → Disbursement)
Azure Monitor + Application Insights + Log Analytics: Observability, SLA monitoring
Azure DevOps: CI/CD for microservices deployment
Loan Type Specific Integrations
Personal Loan / Consumer Durable Loan
Instant approval → integrate CIBIL API, eKYC APIs, UPI disbursement
Store application in Azure SQL, cache customer profile in Redis
Auto Loan / Two-Wheeler Loan
Collateral → integrate RTO API, Insurance API
Use Cosmos DB for fast asset data retrieval
SME Working Capital / Invoice Discounting
Integrate GSTN APIs, Bank Statement Analyzers
Event-driven scoring with Kafka → ML Fraud Service
Home Loan / Corporate Loan
Property valuation → integrate Legal, Property APIs
Longer workflow → orchestrated via Logic Apps/Durable Functions
4. Mapping: Loan Types → Microservices → Azure Services
Loan Type | Key Microservices | Azure Services |
Personal Loan | Customer Onboarding, Loan Application, Credit Score, Loan Eligibility, Disbursement, Repayment | AKS, APIM, Service Bus, Azure SQL, Cosmos DB, Cognitive Services |
Auto Loan | Collateral Mgmt, KYC, Loan Evaluation, Agreement, Disbursement | AKS, APIM, Service Bus, Cosmos DB, RTO API via Logic Apps |
SME Loan | Loan Application, Credit Score, Eligibility, Invoice Discounting, Fraud Detection | AKS, Event Hub, Cosmos DB, Cognitive Services, Azure SQL |
Home Loan | Collateral Mgmt, Agreement, Evaluation, Disbursement, Repayment | AKS, Logic Apps, APIM, Azure SQL, Key Vault |
BNPL | Onboarding, Instant Approval, Disbursement, Collections | AKS, Redis, Cosmos DB, Service Bus |
5. Architecture Flow (Loan Lifecycle)
Step 1: Customer Onboarding
eKYC via Aadhaar/PAN → API call to KYC Service → Cosmos DB store → Azure Key Vault for sensitive data
Step 2: Loan Application
Loan Application Service receives request → Event pushed to Service Bus → triggers Credit Score + Eligibility services
Step 3: Credit Evaluation
Credit Score Service fetches from CIBIL → ML scoring (Fraud Detection Service) → results stored in Azure SQL
Step 4: Approval & Agreement
Loan Evaluation Service calculates risk score → Loan Agreement generated (e-sign via Cognitive Services)
Step 5: Disbursement
Disbursement Service triggers payment via UPI/RTGS → updates CBS → event logged in Service Bus
Step 6: Repayment & Monitoring
Repayment Service schedules EMIs → integrates with auto-debit mandates (UPI, NACH) → sends notifications
Step 7: Reporting & Compliance
Reporting Service aggregates data → Azure Synapse/Power BI for dashboards → regulatory reporting
Loan Type Config
Configurable via ProductConfig table in Postgres
Example:
Home Loan → Requires Collateral + Property Verification + Multi-step Approval
Personal Loan → Simple flow (KYC → Credit Score → Loan Evaluation → Disbursement)
Auto Loan → Collateral check (vehicle RC verification)
Education Loan → Co-applicant validation + income verification
🔹 Architecture Building Blocks
UI Layer
Angular UI → exposed via Azure Front Door + WAF
Auth via Azure AD B2C
API Gateway & Security
Azure API Management → central entry point
OAuth2 / JWT tokens from Azure AD
Microservices on AKS
kyc-service
credit-score-service
loan-evaluation-service
collateral-service
fraud-service
manual-review-service
disbursement-service
notification-service
projection-service (read models into Redis/CosmosDB)
Patterns used:
Saga / Event-driven choreography
Outbox → Kafka → Consumers
Idempotency with correlationId
Data Layer
Postgres on Azure Database for Postgres (System of Record)
Redis on Azure Cache for Redis (Hot cache)
CosmosDB (Materialized views, reporting, audit trails)
Blob Storage (documents, collateral, legal files)
Integration Layer
Kafka (Confluent on Azure / Azure Event Hubs Kafka API)
External APIs: CIBIL/Experian (credit score), Legal vendor APIs, Fraud APIs (Refinitiv, Dow Jones), Property verification
Observability
Logs → Azure Monitor + ELK
Metrics → Prometheus + Grafana (on AKS)
Traces → OpenTelemetry
🔹 Example Home Loan Flow
UI → API Gateway → LoanApplicationService
→ KYCService → CreditScoreService
→ LoanEvaluationService
├── CollateralService (Property Valuation + Legal)
├── FraudService
├── ManualReviewService (if triggered)
→ DisbursementService (partial disbursements)
→ NotificationService
🖼 Suggested Diagram Layout (for deck)
Top Row: Loan Types
Home Loan | Personal Loan | Auto Loan | Education Loan | Credit Card Loan(each mapped to ProductConfig)
Middle Row: Microservices (AKS Pods)
KYC → Credit Score → Loan Evaluation → [Collateral, Fraud, Manual Review (conditional)] → Disbursement → Notification → Projection
Bottom Row: Azure Services
Postgres (loan_application, product_config, outbox)
Redis (cache)
CosmosDB (audit/events)
Kafka/Event Hubs (event bus)
Blob Storage (docs)
Azure AD B2C (auth)
API Management (gateway)
Azure Monitor + Grafana (observability)
🏦 Digital Lending – Combined Architecture (All Loan Types)
1. Loan Types & Rules (Configured in product_config table in Postgres)
Home Loan → Requires KYC, Credit Score, Collateral (property valuation, legal), Fraud, Manual Review (multi-step), Disbursement (partial allowed).
Personal Loan → Requires KYC, Credit Score, Fraud, Loan Evaluation, Disbursement (full).
Auto Loan → Requires KYC, Credit Score, Collateral (vehicle RC verification), Fraud, Loan Evaluation, Disbursement.
Education Loan → Requires KYC, Credit Score, Co-applicant Validation, Fraud, Manual Review (if threshold breached), Disbursement (fee installments).
Credit Card Loan → Requires KYC, Credit Score, Fraud, Loan Evaluation, Instant Disbursement.
2. High-Level Architecture Flow (UI → Backend → Azure Services)
[Angular UI]
│ (Login via Azure AD B2C)
▼
[Azure Front Door + WAF]
▼
[Azure API Management (Gateway)]
▼
[Microservices on AKS]
├── Loan Application Service
│ • Stores initial application in Postgres (loan_application table)
│ • Writes OutboxEvent with correlationId + idempotencyKey
│ • Poller publishes Outbox → Kafka
│ • CacheConsumer updates Redis (hot cache)
│ • NoSQLConsumer updates CosmosDB (audit, projections)
│
├── KYC Service → integrates with Aadhaar/PAN/KYC API
├── Credit Score Service → integrates with CIBIL/Experian API
├── Loan Evaluation Service → applies rules (Drools decision table)
│ ├── Collateral Service (property/vehicle/legal checks)
│ ├── Fraud Service (Refinitiv/Dow Jones APIs)
│ └── Manual Review Service (escalation, multi-step approvals)
│
├── Disbursement Service
│ • Updates Postgres (disbursement table)
│ • Supports multiple disbursement events (home/education loan)
│ • Emits Loan.Disbursed event → Kafka → Notification
│
├── Notification Service (email/SMS/push)
└── Projection Service (Redis + CosmosDB read models)
[Integration Layer]
├── Kafka (Event Hub / Confluent Cloud)
├── External APIs (CIBIL, Experian, Refinitiv, Legal Vendors, Property Valuation)
└── Azure Blob Storage (collateral docs, KYC PDFs)
[Data Layer]
├── Postgres (system of record: loan_application, product_config, outbox, disbursement, collateral)
├── Redis (cache for UI)
├── CosmosDB (audit log, materialized projections)
└── Blob Storage (documents)
[Observability & Security]
├── Azure Monitor + Log Analytics + Alerts
├── Prometheus + Grafana (metrics dashboards)
├── OpenTelemetry (traces)
├── Azure Key Vault (secrets, API keys)
└── Azure Policy + RBAC + Blueprints (governance)
3. Sequence of Events (Generic Loan Journey)
User applies via Angular UI → API Gateway → Loan Application Service.
Loan Application stored in Postgres with idempotencyKey + correlationId.
Outbox entry created → Poller pushes to Kafka.
Kafka → KYC Service (API check) → result persisted in Postgres + published as event.
Kafka → Credit Score Service (CIBIL/Experian API).
Kafka → Loan Evaluation Service → Drools evaluates rules:
If Home Loan → calls Collateral Service + Legal Vendor API.
If Auto Loan → calls Vehicle RC check.
If Education Loan → checks co-applicant.
If Personal Loan → skips collateral, simple fraud check.
Fraud Service → Refinitiv/Dow Jones API.
If flagged → route to Manual Review Service.
On approval → Disbursement Service issues loan:
Home/Education → partial disbursement events.
Personal/Auto/CreditCard → single disbursement event.
Loan.Disbursed event → Kafka → Notification Service → SMS/Email to customer.
All events persisted in CosmosDB for audit + projection.
Redis cache updated for fast UI queries.
✅ This text version shows:
Loan-type-specific branching
Microservices choreography (via Kafka, outbox pattern)
Azure-native services mapping
Full sequence from UI → persistence → event bus → external APIs → disbursement
Overview (one-line)
Modular Spring Boot microservices on AKS expose APIs to an Angular SPA via API Management; services communicate via Kafka (event-driven choreography + Sagas), persist transactional state in Azure SQL and fast lookups in Cosmos/Redis, and integrate with external systems (eKYC, bureaus, RTO, payment rails) via dedicated integration adapters.
1 — Retail Loan types covered
Personal Loan (unsecured)
Consumer Durable / BNPL (short-term, merchant-linked)
Auto / Two-wheeler Loan (secured — vehicle collateral)
Home Loan / Mortgage (secured — property; long-running)
Small-ticket micro-loans / EMI financing
2 — High-level loan lifecycle (applies to all retail loans)
Customer onboarding & authentication (Angular SPA)
Application submission (form + docs)
Document ingestion & OCR (ID, income docs)
KYC & AML checks (eKYC, PEP, sanctions)
Credit scoring & alternative scoring (bureau + transaction/GST/bank-parse)
Eligibility & pricing (interest, tenor, fees)
Underwriting (rules engine + ML + human/manual review)
Agreement generation & e-sign (digital signature)
Disbursement (UPI/NEFT/CBS integration)
Repayment scheduling & collections (auto-debit/UPI/NACH)
Servicing (top-ups, prepayment, closure)
Collections & recovery (delinquency workflows)
3 — Microservice decomposition (core services)
Each service is a Spring Boot app, containerized, 12-factor, deployed to AKS.
API Gateway / APIM (not a microservice): external entry point, auth, rate limiting JWT verification.
Frontend App: Angular SPA (customer + agent portals) served via CDN/Front Door.
Customer Service: profile, KYC status, consents.
Auth Service: Azure AD B2C integration, JWT token issuance, session mgmt.
Loan Application Service: receives applications, validates payload, persists application record.
Document Service: upload, virus-scan, store in Blob Storage, call OCR.
KYC & Compliance Service: eKYC, AML/PEP check, CKYC, regulatory reporting events.
Credit Score Service: fetch bureau scores, run internal models, alternative data aggregator.
Eligibility & Pricing Service: product engine, rule engine for rates & tenors.
Underwriting Service: ML model scoring + rules; issues ACCEPT/REFER/REJECT; sends events.
Collateral Service: asset valuation, register liens (auto/home).
Agreement Service: templating, e-sign integration, e-stamping hooks.
Disbursement Service: payment orchestration, CBS reconciliation.
Repayment & Collections Service: schedule EMIs, process receipts, late fee calc.
Fraud Detection Service: real-time scoring, device fingerprinting, velocity rules.
Notification Service: SMS/Email/WhatsApp via providers (SendGrid/Twilio/WhatsApp API).
Reporting & Analytics: event stream into Data Lake/Synapse, dashboards (Power BI).
Integration/Connector Service: adapters for external APIs (CIBIL, Aadhaar, RTO, Payment Gateways).
Audit & Audit Log Service (or centralized DB): immutable event audit.
Orchestration/Workflow: optional (we recommend Saga via Kafka choreography — see Saga section).
4 — Event topics & example events (Kafka)
Use semantic topic naming, partition by tenant/customer/region where needed.
loan.application.created
loan.application.submitted
document.uploaded
kyc.completed
credit.score.available
eligibility.decided
underwriting.decision
agreement.signed
disbursement.requested
disbursement.completed
repayment.scheduled
repayment.received
loan.status.updated
fraud.alert
Use Cloud-native Kafka (self-managed on AKS, Confluent Cloud, or Azure Event Hubs with Kafka protocol).
5 — Saga pattern & choreography (how transactions span services)
Use choreography: services react to events and publish new events. Example flow:
loan.application.created → Credit Score Service consumes → publishes credit.score.available.
Eligibility Service consumes credit.score.available → publishes eligibility.decided.
Underwriting consumes eligibility.decided → publishes underwriting.decision.
Agreement Service consumes decision → generates agreement → publishes agreement.signed.
Disbursement Service consumes agreement.signed → processes disbursement → publishes disbursement.completed.
Compensations: each service must implement a compensating action event (e.g., disbursement.rollback.requested) for failure cases.
Use outbox pattern for reliable event publishing (transactional DB write + event write).
6 — Sequence example (Personal Loan — simplified)
Angular -> POST /api/loan-applications (Loan Application Service)
Loan Application Service persists application; writes outbox; publishes loan.application.created.
Document Service is triggered for uploads → OCR → document.uploaded.
KYC Service picks up document.uploaded → verifies eKYC → publishes kyc.completed.
Credit Score Service consumes loan.application.created → calls bureau → publishes credit.score.available.
Eligibility Service consumes kyc.completed + credit.score.available → publishes eligibility.decided.
Underwriting consumes eligibility.decided → ML + rules => underwriting.decision. If REFER -> create manual review task in Workbench UI.
Agreement Service issues doc + eSign -> agreement.signed.
Disbursement Service processes -> disbursement.completed.
Repayment Service creates schedule and integrates with auto-debit; notifications sent.
7 — Data model (core tables) — simplified SQL schema
customer (customer_id PK, name, dob, pan, mobile, email, primary_address_id, created_at)loan_application (app_id PK, customer_id FK, product_code, amount_requested, tenure_months, status, created_at, updated_at, correlation_id, idempotency_key)loan_account (loan_id PK, app_id FK, principal, outstanding_amount, interest_rate, start_date, maturity_date, status)collateral (collateral_id, loan_id FK, type, value, registration_details)repayment_schedule (schedule_id, loan_id, due_date, principal_due, interest_due, status)transaction (txn_id, loan_id, amount, txn_type, posted_at, external_ref)audit_log (log_id, entity, entity_id, operation, payload, actor, timestamp)consent (consent_id, customer_id, scope, granted_at, expires_at)outbox_event (event_id, aggregate_id, event_type, payload, published_flag, created_at)
Include correlation_id in all messages and DB records; include idempotency_key for endpoints that might retry.
8 — Azure Infrastructure mapping
AKS — host all Spring Boot microservices (use node pools, spot & standard).
Azure API Management (APIM) — public API gateway, rate-limiting, policy enforcement.
Azure Front Door / CDN — serve Angular SPA (global edge).
Azure Blob Storage — document store (encrypted).
Azure SQL — primary transactional DB (loan_account, repayment_schedule). Use Hyperscale if needed.
Cosmos DB — fast lookup & customer profile caching (optional).
Redis Cache (Azure Cache for Redis) — short-lived session/cache.
Kafka — either Confluent Cloud or self-managed Kafka on AKS (statefulset) or use Azure Event Hubs with Kafka compatibility.
Azure Key Vault — secrets/certs/keys.
Application Insights + Log Analytics — tracing, metrics, logs.
Prometheus + Grafana — cluster and service metrics (if preferred).
Azure Container Registry (ACR) — store Docker images.
Azure DevOps / GitHub Actions — CI/CD pipelines building, scanning, deploying images to AKS.
Azure AD B2C — customer identity; Azure AD for staff/admin logins.
Azure Functions (only for small connectors if needed) — but not used for core orchestration.
Azure Policy / RBAC / Azure Security Center — security posture.
Power BI / Synapse — analytics, ETL from event stream to data warehouse.
9 — Security & Compliance
Auth: OAuth2/OIDC via Azure AD B2C for customers; Azure AD for internal users. JWT tokens issued by Auth Service.
Encryption: TLS everywhere, at-rest encryption for Blob/SQL/Cosmos; keys in Key Vault.
Network: AKS in private subnets; restrict egress; use Private Link for Azure SQL, Storage. WAF on Front Door.
Secrets: No secrets in code; injected from Key Vault via managed identity.
Data minimization & consent: Consent service logs customer consents; store minimal PII; retention policies.
Audit trail: immutable audit logs (append-only).
Compliance: Logging for regulatory audits (RBI guidelines in India), AML reporting hooks.
Pen test & SCA: include SAST/DAST + SCA in pipeline.
10 — Observability & Ops
Distributed Tracing: W3C traceparent; use OpenTelemetry; collect traces into Application Insights.
Logs: structured logs -> Log Analytics / ELK.
Metrics: Prometheus metrics exported by services; Grafana dashboards.
Alerts: SLA breaches, error rates, consumer lag on Kafka, infra resource exhaustion.
Chaos & load testing: run chaos experiments and performance tests (k6, Gatling).
11 — CI/CD & Dev Practices
Mono-repo or multi-repo pattern; each microservice has pipeline:
Build, unit tests, SCA, SAST
Build image -> push to ACR
Canary/Blue-Green deploy to AKS using Helm + ArgoCD or Azure DevOps Releases
DB migrations via Flyway or Liquibase.
Feature flags for gradual rollout (LaunchDarkly or homegrown).
Automated E2E tests for critical flows.
12 — Non-functional & capacity planning
Design for horizontal scaling: stateless services; scale consumers by consumer group.
Kafka partitions sized by throughput; retention for audit/analytics.
Use Redis/Cosmos for read-heavy endpoints.
SLA targets: e.g., personal loan pre-approved journey < 5s (excluding external API waits), full loan approval end-to-end depends on manual steps.
13 — Risk & mitigations (top 8)
External API latency/failures — Circuit breakers, retries + fallback rules, async compensation.
Data inconsistency across services — Outbox pattern + idempotent consumers + sagas.
Security breach of PII — Key Vault, encryption, least privilege, regular audits.
Kafka consumer lag — autoscale consumers; monitoring and alerting.
Manual-review bottleneck — workbench with SLAs, auto-escalation, throttling.
Fraud attacks — multi-layer fraud scoring, behavioral ML, device fingerprinting.
Regulatory non-compliance — consent capture, configurable retention, audit logs.
Deployment failures — Canary deploys, rollbacks, automated tests.
14 — Sample API endpoints (customer-facing)
POST /api/v1/loan-applications — submit application (idempotency-key header)
GET /api/v1/loan-applications/{id} — status & events
POST /api/v1/documents — upload doc (returns docId)
POST /api/v1/customers — create profile (OAuth-protected)
POST /api/v1/payments/disburse — request disbursement (internal)
Include OpenAPI/Swagger for each microservice and publish aggregated API docs in APIM.
15 — Implementation suggestions & tech stack
Java 17+, Spring Boot 3.x (WebFlux for high concurrency optional)
Spring Cloud (Kafka), Spring Data JPA, Flyway
Angular 15+ for SPA
Kafka (Confluent / Event Hubs Kafka compatibility)
PostgreSQL/Azure SQL, Cosmos DB (if needed)
Docker, Helm charts, ArgoCD/Flux (GitOps) or Azure DevOps pipelines
OpenTelemetry for tracing
16 — MVP scope (3–6 months) — suggested priority
Supports: Personal Loan, BNPL, Small Auto Loan (basic)
Microservices: Customer, Loan Application, Credit Score (bureau aggregator), Eligibility, Underwriting (rules only), Disbursement, Repayment, Notification, Document (OCR), Integration connectors for eKYC & payment.
Event infra + outbox + basic dashboards.
Different retail loan types follow slightly different journeys — not just the same flow with different data.
Here’s how loan type → journey differences typically work:
1. Personal Loan (Unsecured)
Journey: Fastest & simplest
Steps:
Onboarding → eKYC → Bureau Score
Instant decision (pre-approved offers possible)
Agreement → e-sign → Instant disbursement
Key Characteristics:
No collateral validation
Risk model heavily credit-score-driven
End-to-end TAT: seconds to minutes
Often fully automated (no manual underwriting)
2. Consumer Durable / BNPL Loan
Journey: Embedded financing at point of sale
Steps:
Merchant integration triggers loan flow
Minimal KYC (Aadhaar OTP, PAN check)
Lightweight risk scoring (not full bureau pull sometimes)
Instant approval → generate EMI plan → disburse to merchant
Key Characteristics:
Low ticket, low risk, short tenor
UX must be frictionless
Strong integration with merchant/partner systems
High volume, low latency focus
3. Auto / Two-Wheeler Loan
Journey: Collateral-based, dealer-assisted
Steps:
KYC + Bureau Score
Vehicle details capture (chassis/engine no.)
Collateral valuation (price from OEM/RTO)
Agreement → Hypothecation filing → Disbursement to dealer
Key Characteristics:
Asset verification mandatory
Dealer/DMS integration
RTO lien marking (hypothecation) step required before disbursement
Moderate automation, but manual checks for certain regions
4. Home Loan / Mortgage
Journey: Longest, most complex
Steps:
KYC, income documents (bank statements, salary slips)
Detailed bureau & affordability check
Property documents upload → legal & technical verification
Collateral valuation & title search
Sanction letter → agreement → registration/stamping
Tranche disbursements (not always lump sum)
Key Characteristics:
Multiple manual touchpoints
Third-party verification (legal, technical)
Multiple approval layers (risk, compliance)
TAT: days to weeks
Often integrated with manual workflow systems
5. Micro Loans / Small Ticket Lending
Journey: Ultra-fast, mobile-first
Steps:
Mobile onboarding → OTP-based KYC
Alternative credit scoring (UPI, SMS data, wallet usage)
Instant decision → Instant disbursal
Key Characteristics:
Uses alternate data instead of full bureau pulls
Designed for underbanked customers
Must support very high volumes, low cost per acquisition
How It Differs in Architecture & Microservices
Component | Personal / BNPL | Auto Loan | Home Loan |
KYC Service | Basic eKYC, OTP flow | Full eKYC + additional address proof validation | Full eKYC + manual doc review |
Credit Score Service | Instant bureau + internal score | Bureau + LTV (Loan-to-Value) check | Bureau + DTI + complex affordability models |
Collateral Service | Not used | Vehicle valuation + RTO lien marking | Property valuation + legal title check |
Underwriting | Fully automated | Semi-automated (manual override possible) | Multi-level approval, manual review required |
Disbursement | Instant | Dealer disbursement (post lien) | Tranche-wise disbursement |
Agreement Service | Simple digital e-sign | e-sign + lien registration docs | Sanction letter + registered mortgage |
How You Should Design for It
Instead of creating completely separate journeys per loan type, design configurable workflows:
Workflow Engine / Rules Service (Camunda, Temporal, Zeebe or custom)
Define loan journey as steps (KYC → Score → Valuation → Approval → Disbursement)
Enable/disable steps based on product config
Product Configuration Table
Loan Type
Required steps (boolean flags: KYC, Collateral, Legal, Multi-Level Approval)
SLA per step
Auto/manual decision threshold
This way:
Personal Loan skips collateral/valuation
Auto Loan includes collateral validation
Home Loan includes property verification + manual approval steps
BNPL uses short KYC + instant disbursement
Key Design Principle
🔑 Build Once, Configure ManyRather than separate code paths, create configurable microservice orchestration so new loan products can be onboarded by changing configuration and business rules — not redeploying code.
Digital Lending Architecture & Journey — Retail Loans
Scope: Personal, Consumer Durable / BNPL, Auto / Two-wheeler, Home / Mortgage, Micro-loans (small-ticket). Spring Boot microservices (Java), Angular frontend, Kafka event-driven choreography, Saga pattern, deployed on Azure Cloud.
Executive summary
A single, configurable digital lending platform that supports multiple retail loan products by using a common microservice backbone and a workflow-driven product configuration. The platform uses event-driven choreography (Kafka) for internal orchestration and Saga/compensation for distributed transactions. Azure provides the infrastructure (AKS, APIM, Blob, SQL, Cosmos, Key Vault, Event Hubs/Kafka, ACR, AD B2C). The architecture follows “build once, configure many” to spin different loan journeys through product configuration rather than separate code paths.
High-level architecture (conceptual)
Angular SPA (Customer portal + Dealer/Agent portal) served via Front Door / CDN.
API Gateway (APIM) exposes secure REST endpoints; forwards to microservices on AKS.
Microservices (Spring Boot) on AKS: Customer, Auth, Loan Application, Document, KYC, Credit Score, Eligibility, Underwriting, Collateral, Agreement, Disbursement, Repayment, Fraud, Notification, Integration/Connector, Reporting, Audit.
Event Bus (Kafka / Event Hubs) for internal events; Outbox pattern for reliable event emission.
Data stores: Azure SQL (transactional), Cosmos DB (profile & high-read cache), Blob Storage (documents), Redis (cache), Data Lake / Synapse (analytics).
CI/CD: Azure DevOps / GitHub Actions -> ACR -> AKS (Helm/ArgoCD).
The detailed diagram is represented as sections below (sequence+workflow). If you want a PNG/SVG, tell me and I’ll produce visual exports.
Key design principles
Product-configurable workflows — each loan product is defined by a set of ordered steps and policy thresholds stored in a Product Configuration service.
Event-driven choreography — services react to events and publish subsequent events; keep services loosely coupled.
Outbox + Idempotent Consumers — ensure eventual consistency & exactly-once semantics for critical flows.
Compensating Sagas — each long-running distributed transaction has compensating actions.
Separation of concerns — integrate external partners via dedicated Integration/Connector services.
Security by design — data encryption, Key Vault, private networking, Azure AD B2C.
Product configuration model (example)
A product_config entity controls the journey:
product_code (PERSONAL/BNPL/AUTO/HOME/MICRO)
steps (ordered list) e.g. [KYC, BUREAU, ELIGIBILITY, VALUATION, UNDERWRITING, AGREEMENT, HYPOTHECATION, DISBURSEMENT]
auto_approval_thresholds (score >= X, LTV <= Y)
requires_collateral (bool)
collateral_type (vehicle/property)
manual_review_rules (business rules pointing to Workbench)
sla_per_step (seconds/minutes/hours/days)
When a loan application is created, the Loan Orchestrator (lightweight service) resolves the product config and publishes events to start the corresponding steps.
Microservices (brief responsibilities)
API Gateway / APIM — authentication, rate-limiting, request validation, routing, aggregated docs.
Auth Service — integrates Azure AD B2C for customers; issues JWT to front-end.
Customer Service — master customer profile, KYC status, consent records, correlation IDs.
Loan Application Service — persistent application aggregate, handles idempotency, writes outbox events.
Document Service — handles uploads to Blob, triggers OCR (Cognitive Services) and stores metadata.
KYC & Compliance Service — eKYC (Aadhaar), AML/PEP checks, CKYC integration.
Credit Score Service — bureau integrations + internal models (cache results in Cosmos).
Eligibility & Pricing Service — product rules engine, pricing calculator.
Underwriting Service — ML-based risk scoring + business rule engine; creates manual review tasks.
Collateral Service — valuation, lien registration helpers (RTO, property, eRegistries).
Agreement Service — templating, e-sign integration, e-stamping hooks.
Disbursement Service — orchestrates UPI/NEFT/RTGS/CBS payouts; handles tranche logic.
Repayment Service — schedules EMIs, NACH/UPI mandates, reconciliation.
Fraud Service — real-time flagging, device fingerprinting, velocity checks.
Integration/Connector Service — adapter layer for bureaus, payment gateways, RTO, GSTN.
Reporting Service — stream ETL to Synapse and Power BI; regulatory exports.
Audit Service — append-only audit entries for regulatory compliance.
Event design (topics & example payloads)
Use domain-driven, versioned events. Examples:
loan.application.created { appId, customerId, productCode, amount, correlationId }
document.uploaded { docId, appId, docType, storageUri }
kyc.completed { customerId, kycStatus, evidence }
credit.score.available { customerId, score, bureau, modelVersion }
eligibility.decided { appId, eligible, recommendedAmount, rate }
underwriting.decision { appId, decision, reasons, manualTaskId? }
agreement.signed { appId, agreementId, signedAt }
disbursement.completed { appId, loanId, amount, txnRef }
Partition keys: tenantId or customerId depending on scale and privacy.
Saga choreography & compensations
Approach: Choreography for happy path; compensating events for failures.
Example: Disbursement Saga (high level)
agreement.signed → Disbursement Service attempts fund transfer.
On success -> disbursement.completed (update loan_account state).
On failure -> emit disbursement.failed -> trigger compensations: agreement.revoke (if needed), reserve_release for collateral hold, notify customer and operations.
Every service must implement idempotent handlers and compensating events where a state change affects external systems.
Loan-specific journeys (condensed)
Personal Loan (fast path)
Steps: KYC → Bureau Score → Eligibility → Auto Underwriting → Agreement eSign → Disbursement
Key differences: no collateral, decision thresholds tuned for automation, limited manual review.
BNPL / Consumer Durable (merchant-embedded)
Steps: Merchant trigger → Lightweight KYC → Lightweight score (internal) → Instant Approval → Agreement (simplified) → Pay merchant
Key differences: merchant integration adapters; lower friction; tokenized payment rails; settlement with merchant payout schedules.
Auto Loan
Steps: KYC → Bureau → Eligibility + LTV calc → Dealer inputs vehicle details → Collateral Valuation → Hypothecation/RTO filing → Underwriting → Agreement + Lien docs → Disbursement to Dealer/CBS
Key differences: Collateral service interacts with RTO & Dealer systems; pre-disbursement check for lien registration.
Home Loan
Steps: KYC → Detailed affordability & bureau → Property docs upload → Technical valuation & Legal title search → Manual underwrite & multi-level approval → Sanction letter → Agreement signing & registration → Tranche-based disbursement
Key differences: lengthy 3rd-party processes (legal/valuation); human-in-loop workflows; tranche payments; document-heavy.
Micro-loans
Steps: Mobile onboarding → OTP KYC → Alternate-data scoring (UPI/telemetry) → Instant approval & disbursal
Key differences: alternative data connectors, extremely lightweight UX, high throughput.
Configurable workflow engine (implementation options)
You have 3 choices:
Use Temporal / Camunda / Zeebe (recommended if you prefer explicit workflow modeling & visibility). It maps product-config steps into orchestrated stateful workflows with retries, timers, human tasks.
Pure event-driven choreography (Kafka) with a lightweight Orchestrator service that resolves product config and emits initial events (recommended for high scalability and low centralization).
Hybrid: choreography for internal microservice interactions + Temporal/Camunda for business-visible long-running human tasks (e.g., home loan manual review).
Data model (core aggregates)
Key aggregates/tables (with sample important fields):
customer(customer_id, name, dob, pan, mobile, email, primary_address_id)
loan_application(app_id, customer_id, product_code, requested_amount, tenure, status, correlation_id, idempotency_key, created_at)
loan_account(loan_id, app_id, principal, outstanding, interest_rate, start_date, status)
document(doc_id, app_id, type, storage_uri, ocr_text, verified)
collateral(collateral_id, loan_id, type, value, registration_status)
repayment_schedule(schedule_id, loan_id, due_date, principal, interest, status)
outbox_event(id, aggregate_id, event_type, payload, published_flag)
consent(consent_id, customer_id, scope, granted_at, expires_at)
Design notes: use transaction-per-aggregate and outbox for publishing events.
Azure services mapping (detailed)
AKS — host microservices; node pools split by workload type (system, burst, critical). Use pod-level identity.
APIM — public APIs, aggregation, developer portal.
Azure Front Door + CDN — host Angular SPA; WAF.
Azure Event Hubs (Kafka API) or Confluent Cloud — event backbone.
Azure SQL — primary transactional DB (use geo-replication for DR).
Cosmos DB — customer profile, session store, scoring cache.
Blob Storage — documents (tiering + immutable storage for audit).
Key Vault — secrets, certificates.
Azure AD B2C — customer auth & identity.
Cognitive Services / Form Recognizer — OCR for documents.
Power BI / Synapse — reporting & analytics.
Application Insights + Log Analytics — tracing & logs.
Azure Cache for Redis — caching.
Azure DevOps / GitHub Actions & ACR — CI/CD.
Security & privacy
TLS 1.2+, mTLS for service-to-service where required.
RBAC & least privilege via Azure AD & managed identities.
Encrypt at rest (SQL, Cosmos, Blob) with Customer-Managed Keys in Key Vault.
PII redaction on logs; store only necessary PII; consent capture & retention policy enforcement.
Network isolation: private AKS cluster, private endpoints for SQL & Storage.
Observability & SLOs
Tracing: OpenTelemetry across services, correlate via correlation_id.
Metrics: Prometheus + Grafana for infra; Application Insights for app metrics.
Logs: Structured logs → Log Analytics; high-volume
Done — I created a detailed architecture & journey document on the canvas titled “Digital Lending Architecture - Retail Loans (personal, Auto, Home, Bnpl, Microloans)”.
Digital Lending – Unified Architecture Flow (Text Version)
1. Entry Points
Angular Frontend App
Loan type selection (Personal, Auto, Home, BNPL, Micro)
Captures user inputs → Sends REST/GraphQL request to Loan Origination API Gateway
API Gateway (Azure API Management)
AuthN via Azure AD / OAuth2
Routes to respective Loan Orchestration Service
2. Core Microservices (Deployed on AKS)
Loan Orchestration Service
Publishes loan.initiated event to Kafka with:
Loan Type
Customer ID
Correlation ID
Idempotency Key
KYC Service
Consumes loan.initiated
Performs eKYC (Aadhaar/PAN/DigiLocker)
Publishes kyc.completed
Credit Score Service
Consumes kyc.completed
Calls bureau / internal scorecard
Publishes creditscore.completed
Collateral Service (only for Auto/Home)
Consumes creditscore.completed (if loan type requires collateral)
Triggers:
Vehicle valuation + RTO lien marking (Auto)
Property valuation + legal verification (Home)
Publishes collateral.verified
Risk/Underwriting Service
Listens to creditscore.completed and collateral.verified
Applies rules engine (Drools/Decision Table)
Publishes loan.approved or loan.rejected
Agreement Service
Consumes loan.approved
Generates sanction letter & e-agreement
Publishes agreement.signed
Disbursement Service
Consumes agreement.signed
Triggers payment through Core Banking / Payment API
Publishes loan.disbursed
3. Kafka Event Topics
loan.initiated
kyc.completed
creditscore.completed
collateral.verified
loan.approved
loan.rejected
agreement.signed
loan.disbursed
loan.failed (for saga rollback scenarios)
4. Branching by Loan Type
Personal Loan
loan.initiated → kyc.completed → creditscore.completed →
loan.approved → agreement.signed → loan.disbursed
No collateral check
Fully automated underwriting
BNPL / Consumer Durable Loan
loan.initiated → kyc.completed (OTP only) → lightweight score →
loan.approved → agreement.signed → loan.disbursed (merchant settlement)
Low friction, minimal KYC
Instant decisioning, sub-second SLAs
Auto Loan
loan.initiated → kyc.completed → creditscore.completed →
collateral.verified (vehicle validation + lien marking) →
loan.approved → agreement.signed → loan.disbursed (dealer)
Adds vehicle data capture + lien step
Disbursement only after lien marking confirmed
Home Loan
loan.initiated → kyc.completed → creditscore.completed →
collateral.verified (property valuation + legal check) →
manual underwriting approval →
loan.approved → agreement.signed →
loan.disbursed (tranches if construction linked)
Multi-step manual approvals
Collateral check may involve external legal vendor integration
Disbursement can be partial (multiple loan.disbursed events)
Micro Loans
loan.initiated → kyc.completed (alternate data) →
alt.credit.score.completed → loan.approved →
agreement.signed → loan.disbursed
Uses alternate data (UPI txn, mobile data, etc.)
Real-time scoring models (ML-based)
5. Saga / Compensation Flow
If any service fails:
loan.failed event is published
Orchestration service triggers rollback:
Reverse disbursement (if money already sent)
Cancel lien (Auto)
Void sanction letter (Home/Personal)
6. Cross-Cutting Concerns
Correlation ID + Idempotency Key generated at loan.initiated
Redis Cache to store intermediate state for idempotency & fast reads
Cosmos DB / Azure SQL stores loan application, events, decision logs
Azure Monitor + Grafana for observability
Security: Azure AD + API Gateway throttling + encrypted payloads (PII)
✅ Key Advantage:This design is loan-type agnostic — same set of microservices are used, but behavior changes via:
Product Config Table (decides whether collateral step required)
Business Rules (auto vs manual underwriting)
Workflow Orchestration (skips/branches steps)
1 — Canonical technical assumptions (applies to all flows)
Frontend: Angular SPA (Customer / Dealer / Agent) → calls API Gateway (APIM).
API Gateway: Authentication (Azure AD B2C), request validation, rate limiting; forwards to Loan Orchestration Service.
Source of truth DB: Azure Database for PostgreSQL (transactional).
Outbox: outbox_event table in Postgres written in the same transaction as application changes.
Outbox publisher: Debezium or a scheduled publisher reads outbox rows and publishes to Kafka, marks as published.
Event bus: Kafka (topics per domain event).
Consumers:
CacheConsumer → updates Redis (fast reads).
NoSQLConsumer → writes denormalized documents into Cosmos DB (read-model / UI).
Domain microservice consumers (KYC, Score, Collateral, Underwriting, etc.).
Microservices: Spring Boot services deployed on AKS, each owns its DB/aggregate or uses Postgres with proper aggregate boundaries.
Correlation & Idempotency:
correlation_id included in all events/DB rows.
idempotency_key required on client POSTs; services ensure idempotent handling.
Sagas / Compensation: Each step that changes external systems emits compensating events (example: disbursement.rollback.requested).
Manual tasks: Workflow engine (Temporal/Camunda) or workbench for human approvals; manual steps produce events when completed.
2 — Core domain events (canonical list)
(Version all event names, payloads should include correlation_id, app_id, customer_id, loan_type.)
loan.initiated
loan.application.persisted (outbox transitional)
document.uploaded
kyc.completed
creditscore.completed
eligibility.decided
collateral.verified
valuation.reported
legal.clearance.completed
manual.approval.requested
manual.approval.completed
loan.approved
agreement.generated
agreement.signed
disbursement.requested
loan.disbursed (include tranche number)
repayment.schedule.created
repayment.received
loan.rejected
loan.cancelled
compensation.requested
audit.event (for immutable audit store)
3 — Database + outbox pattern (text)
Client (Angular) POSTs /v1/loan-applications with Idempotency-Key.
Loan Orchestration Service:
Begin Postgres TX.
Insert into loan_application (status = INITIATED) — primary record.
Insert into outbox_event (event_type=loan.initiated, payload with app data).
OutboxPublisher reads outbox row, publishes loan.initiated to Kafka, updates outbox_event.published=true.
Consumers (CacheConsumer, NoSQLConsumer, KYC, Score) pick up loan.initiated and proceed.
4 — Projection consumers (text)
CacheConsumer:
Consumes every loan.* event.
Updates Redis keys for quick UI read: loan:{appId}:status, loan:{appId}:nextStep, loan:{appId}:latestEvent.
TTLs for non-critical items, or immediate deletion on closure.
NoSQLConsumer (Cosmos DB):
Consumes every loan.* event.
Writes denormalized document loan_document combining application + latest events + collateral summary + KYC status for fast UI queries and analytics.
5 — Orchestrator behaviour (how product config is used)
Product Configuration Service (Postgres table product_config) contains:
product_code (PERSONAL, BNPL, AUTO, HOME, MICRO)
steps (ordered list of step ids)
flags (requires_collateral, requires_valuation, requires_legal, requires_manual_approval)
auto_approval_thresholds (score, ltv, dti)
disbursement_mode (LUMP_SUM, TRANCHE)
manual_approval_flow (levels & approvers)
sla_seconds_per_step
On loan.initiated the Loan Orchestration Service:
Reads product_config for product_code.
Creates the workflow instance (lightweight state record in Postgres workflow_instance) with the steps sequence and current pointer.
Emits initial domain event(s) corresponding to first step(s), e.g. document.uploaded if docs were included, else kyc.started / kyc.requested.
Workflow state is advanced by upstream events (e.g., when kyc.completed arrives, orchestrator marks step completed and triggers next event(s) based on config).
If steps include parallelism (KYC + Score) orchestrator can emit both initial requests or let consumers act on loan.initiated.
6 — Business rules engine integration (text)
Rules Engine options: Drools / Decision Tables / DMN, or embedded rules in Eligibility Service.
Where rules live:
Static rules (product thresholds) in product_config.
Dynamic rules (complex underwriting) in Drools knowledge base; rules are versioned and deployed separately.
Runtime:
Underwriting Service calls Rules Engine with input facts: cibilScore, dti, ltv, incomeDocsVerified, legalClearance.
Rules evaluate and output decision: AUTO_ACCEPT, REFER_MANUAL, AUTO_REJECT, plus sanctionAmount, interestRate.
Rule-driven branching:
If result AUTO_ACCEPT → Underwriting publishes loan.approved.
If REFER_MANUAL → Underwriting publishes manual.approval.requested (with required approvers & SLA).
If AUTO_REJECT → Underwriting publishes loan.rejected (reason codes).
7 — Concrete sequences (text) — all loan types
For each sequence I show: UI action → Postgres+Outbox → Kafka → Consumers (Cache, NoSQL) → Domain services → subsequent events → final disbursement/repayment.
A) Personal Loan (fastest path — no collateral)
UI → POST /v1/loan-applications (body includes product_code=PERSONAL) with Idempotency-Key.
Loan Orchestration Service: write loan_application, write outbox_event (loan.initiated); commit.
OutboxPublisher → publish loan.initiated to Kafka.
CacheConsumer → Redis; NoSQLConsumer → Cosmos DB (application snapshot).
KYC Service consumes loan.initiated:
performs eKYC (Aadhaar/PAN)
writes KYC result (Postgres) + outbox kyc.completed.
Credit Score Service consumes kyc.completed:
calls bureau & internal models
writes result + outbox creditscore.completed.
Eligibility Service consumes creditscore.completed (and kyc.completed):
fetches product_config(PERSONAL) (flags: no collateral, auto approval thresholds)
runs rules → decides AUTO_ACCEPT if score >= threshold
writes eligibility.decided event via outbox.
Underwriting Service consumes eligibility.decided:
If auto → publishes loan.approved via outbox.
Else publishes manual.approval.requested.
Agreement Service consumes loan.approved:
generates agreement, triggers eSign → on sign publishes agreement.signed.
Disbursement Service consumes agreement.signed:
initiates payment via Payment Connector / CBS → on success publishes loan.disbursed (tranche=1).
Repayment Service creates schedule on loan.approved or agreement.signed event and publishes repayment.schedule.created.
UI queries read-model (Cosmos or Redis) for status updates.
Key notes:
All writes to Postgres use outbox for event emission.
Cache & NoSQL projections ensure UI remains snappy.
B) BNPL / Consumer Durable (merchant-embedded, low friction)
Merchant Portal / UI triggers loan.initiated with product_code=BNPL and merchant metadata.
Loan Application persisted w/ outbox → loan.initiated.
Outbox → Kafka → Cache/NoSQL updates.
Lightweight KYC step: kyc.completed may be OTP-only; sometimes skipped depending on merchant-level trust.
Internal lightweight scoring service consumes (uses internal risk model, historical merchant settlement data) → creditscore.completed or altscore.completed.
Eligibility Service uses product_config(BNPL) (low thresholds, instant approval policies) → typically AUTO_ACCEPT.
Agreement generated (simplified) and agreement.signed emitted (may be implicit by merchant T&C acceptance).
Disbursement to Merchant Settlement account via loan.disbursed event; settlement engine batches/clears later.
Collections: Merchant settlement reconciles transactions; platform collects from borrower via scheduled EMIs/UPI.
Key differences:
Merchant context included in events: merchant_id, order_id.
Disbursement mode usually LUMP_SUM to merchant (or split by merchant settlement terms).
High-volume, low-latency processing; aggressive caching and partitioning.
C) Auto Loan (collateral + RTO/hypothecation)
UI (Dealer/Customer) POSTs loan.initiated with product_code=AUTO + vehicle details.
Postgres + Outbox → loan.initiated.
Outbox → Kafka → Cache & Cosmos.
KYC & Credit Score proceed as in Personal flow (kyc.completed, creditscore.completed).
Collateral Service consumes creditscore.completed (or loan.initiated depending on config) and:
Validates vehicle details (VIN, chassis, engine) via Dealer / RTO connector → valuation.reported with market value.
Calculates LTV = requestedAmount / valuation.
If hypothecation required: triggers Hypothecation Service → calls RTO for lien registration.
On successful registration publishes collateral.verified (include lien_registration_id).
Eligibility Service receives creditscore.completed + collateral.verified:
Runs rules: checks LTV <= product_config.auto.ltv_threshold; DTI; other checks.
Output: eligibility.decided.
Underwriting executes business rules (may AUTO_ACCEPT or REFER_MANUAL).
If accepted: Agreement Service produces lender & hypothecation docs → eSign & agreement.signed.
Disbursement Service waits for collateral.verified & agreement.signed before issuing disbursement.requested → pays dealer (NEFT) → emits loan.disbursed.
Any failure in lien registration → loan.rejected or compensation.requested if funds already moved.
Key differences:
Collateral & lien registration precondition for disbursement.
Extra external connectors: Dealer/DMS, RTO.
Compensation logic must handle partial external state (registered lien vs not).
D) Home Loan (multi-step manual approvals + external vendors + tranche disbursement) — FULL DETAILED SEQUENCE
(This is the full requested detailed flow — long-running, many external interactions.)
Step 0 — Client submission
Customer submits home loan application with property metadata + document uploads (title docs, sale deed, NOC, builder letters).
Loan Orchestration Service:
Begin TX in Postgres.
Insert loan_application (status=INITIATED).
Insert outbox_event (loan.initiated).
Commit.
Step 1 — Outbox → Initial projections
OutboxPublisher publishes loan.initiated to Kafka.
CacheConsumer updates Redis; NoSQLConsumer writes denormalized doc to Cosmos.
Step 2 — Document ingestion & OCR
Document Service consumes loan.initiated and:
Stores uploads in Blob Storage.
Calls Form Recognizer/OCR asynchronously.
On OCR completion publishes document.uploaded events with document_id.
NoSQLConsumer picks up docs and updates the read model.
Step 3 — KYC & Preliminary checks
KYC Service consumes loan.initiated:
Performs full eKYC (Aadhaar, PAN, CKYC).
Performs AML/PEP screening.
Publishes kyc.completed {status}.
Step 4 — Credit Score & Affordability
Credit Score Service consumes kyc.completed:
Calls bureau & internal affordability engine (DTI, FOIR).
Writes creditscore.completed event with score, affordability metrics.
Step 5 — Collateral: Valuation + Legal (two parallel external vendor flows)
Collateral Service consumes creditscore.completed:
Property Valuation: calls Valuation Vendor API (third-party). Vendor returns valuation.report (market value, vtm).
Legal Title Search: calls Legal Vendor API. Vendor returns legal.clearance.status (CLEAR / EXCEPTIONS).
Collateral publishes valuation.reported & legal.clearance.completed.
NoSQLConsumer updates read model with valuation & legal summaries.
Step 6 — Orchestration: prepare Underwriting Case
Underwriting Service consumes valuation.reported and legal.clearance.completed + creditscore.completed:
Packages facts into Underwriting Case (cibilScore, valuation, legal exceptions, income verification).
Decides based on Rules Engine:
If AUTO_REJECT → publish loan.rejected.
If AUTO_ACCEPT → publish loan.approved.
If REFER_MANUAL → publish manual.approval.requested with work item details.
Step 7 — Manual multi-level approvals (human workflow)
If manual.approval.requested:
Workflow engine / Workbench creates task(s) assigned per product_config.home.manual_approval_flow (e.g., Credit Officer → Legal Head → Risk Head).
Each approver logs into Workbench (UI) and completes their task:
On completion the Workbench emits manual.approval.completed {level, approverId, decision, comments}.
On final approval (all levels completed with APPROVE) Underwriting publishes loan.approved.
Step 8 — Sanction & Agreement
On loan.approved:
Agreement Service creates sanction letter & loan agreement PDFs.
Agreement Service calls eSign providers (Aadhaar eSign / third-party).
On successful eSign publish agreement.signed.
Step 9 — Pre-disbursement validations
Disbursement Service consumes agreement.signed and:
Reads product_config.home.disbursement_mode (TRANCHE vs LUMP_SUM).
For TRANCHE:
Waits for builder/buyer stage evidence:
builder.stage.completed or customer uploads inspection.report.
Each tranche request is disbursement.requested {trancheNumber, amount, evidenceRef}.
Validates lien/registration status if applicable.
Step 10 — Disbursement (multiple loan.disbursed events)
For each tranche:
Disbursement Service initiates payment via Payment Connector (NEFT/RTGS).
On success publishes loan.disbursed {tranche=N, amount, txnRef}.
Update Postgres loan_account outstanding balance.
NoSQLConsumer updates read-model.
Step 11 — Repayment scheduling & collections
After first tranche (or on loan.approved), Repayment Service creates schedule:
Publish repayment.schedule.created.
Integrate with mandate provider (NACH/UPI) for auto-debit; create mandate.registered events.
Repayment events (repayment.received) update loan_account and may lead to notifications and ledger entries.
Step 12 — Exceptions & compensations
If legal vendor later reports encumbrance (post-disbursement), a legal.exception.raised event is emitted:
Risk team notified; may trigger compensation.requested (recall funds) if severe.
If customer cancels after partial disbursements, compensation flow:
compensation.requested → Disbursement Service tries reversal; if reversal impossible creates manual collection task.
Step 13 — Closing
On full repayment loan.closed event published and read-model updated.
Key home-loan specifics reiterated:
Long-running — workflow instances persisted; events may be days/weeks apart.
External vendor calls are asynchronous; platform does not block UI (use notifications to update applicant).
Tranche-based disbursement means multiple loan.disbursed events with idempotency checks (each tranche has unique trancheId).
Audit: every critical event is recorded in an immutable audit store for compliance.
E) Micro-loans (alternative-data, mobile-first)
UI (mobile) POSTs loan.initiated with product_code=MICRO.
Postgres + Outbox → loan.initiated published.
NoSQL & Cache projections updated.
Alt-Scoring Service consumes event:
Pulls UPI txn history, telco data, device signals (via integration service).
Produces altcreditscore.completed.
Eligibility Service evaluates against product_config.micro (looser thresholds, limits).
Underwriting typically AUTO_ACCEPT.
Agreement implied or eSign via OTP; agreement.signed emitted.
Disbursement instant to bank/UPI → loan.disbursed.
Collections use UPI auto-debit or in-app repayment.
Key differences:
Uses alternate data connectors.
Extremely high throughput; needs optimized partitioning & caching.
8 — Product configuration example (JSON) — how to control flow
Store product configs in product_config table and optionally in a feature-flag service:
{
"product_code": "HOME",
"display_name": "Home Loan - Standard",
"steps": [
"DOCUMENT_UPLOAD",
"KYC",
"CREDIT_SCORE",
"PROPERTY_VALUATION",
"LEGAL_CHECK",
"UNDERWRITING",
"MANUAL_APPROVAL",
"AGREEMENT",
"DISBURSEMENT_TRANCHE"
],
"flags": {
"requires_collateral": true,
"requires_valuation": true,
"requires_legal": true,
"requires_manual_approval": true
},
"auto_approval_thresholds": {
"cibilScore": 750,
"dti": 50,
"ltv": 0.8
},
"disbursement": {
"mode": "TRANCHE",
"tranches": [
{ "percent": 0.2, "condition": "agreement_signed" },
{ "percent": 0.5, "condition": "builder_stage_2" },
{ "percent": 0.3, "condition": "building_completion" }
]
},
"manual_approval_flow": [
{ "level": 1, "role": "CreditOfficer" },
{ "level": 2, "role": "LegalHead" },
{ "level": 3, "role": "RiskHead" }
],
"sla_seconds_per_step": {
"KYC": 3600,
"PROPERTY_VALUATION": 86400,
"LEGAL_CHECK": 172800,
"MANUAL_APPROVAL": 259200
}
}
How it’s used:
Orchestrator reads steps and flags.
Orchestrator creates workflow_instance and issues initial events as needed.
Rules engine uses auto_approval_thresholds for auto-decision.
Disbursement service reads disbursement.tranches to know how many loan.disbursed events to expect and when to allow them.
9 — Rules / Decision Table example (text)
Decision table for UNDERWRITING_DECISION:
Condition: CIBIL >= 750 | DTI <= 50% | LTV <= 80% | Legal Clear | Result |
true | true | true | true | AUTO_ACCEPT |
true | true | true | false | REFER_LEGAL |
false | any | any | any | REFER_MANUAL |
any | >70% | any | any | AUTO_REJECT |
Rules can be authored in Drools and updated via CI/CD with versioning.
10 — Idempotency, retries, error handling (practical)
All endpoints require Idempotency-Key header; the Orchestration Service persists the key and ignores duplicate POSTs.
Outbox ensures events are published exactly-once (or at-least-once with idempotent consumers).
Consumers must be idempotent (check if event already applied using event_id).
Use exponential backoff + DLQ for failed event processing (human review for stuck items).
11 — Compensation examples (text)
Disbursement failed after agreement signed:
disbursement.failed → compensation.requested → Underwriting/Operations notified for manual fix.
Legal exception discovered post-disbursement:
legal.exception.raised → compensation.requested → Risk evaluates, may trigger recall event.
Partial funds reversed require ledger operations and manual.collection.task.
12 — Short operational note for UI developers
The UI should consume from the read-model (Cosmos/Redis) and poll or subscribe to push notifications for status change (websocket).
Each loan card should show currentStep (from read-model) and ETA based on sla_seconds_per_step.
For manual approvals, Workbench UI shows taskId, approverRole, SLA, supportingDocs links (pointing to Blob SAS URLs).
13 — Final summary (one-liner)
Use Postgres + Outbox → Kafka → Cache (Redis) + NoSQL (Cosmos) as the canonical data flow; control per-loan behavior via a product_config + rules engine; orchestration uses workflow instances to sequence and branch steps (parallel & sequential) — this supports all retail loan types including home loan multi-step manual approvals, external vendor property checks, and tranche-based disbursement (multiple loan.disbursed events).
1) PERSONAL LOAN — (Full text flow)
Preconditions: Customer provides explicit consent for KYC, credit check, fraud detection, and data sharing (via consent API).
Sequence:
UI (Angular) -> POST /v1/loan-applications with body {product_code: PERSONAL, amount, tenure} and header Idempotency-Key: <key>.
Loan Orchestration Service:
Validate Idempotency-Key (RETURN existing application if found).
Begin Postgres TX:
Insert/Upsert customer (if new).
Insert consent records for scopes: KYC, CREDIT, FRAUD, DATA_SHARING when customer accepts.
Insert loan_application (status=INITIATED, correlation_id, idempotency_key).
Insert outbox_event (event_type='loan.initiated', payload includes consent ids).
Commit.
Outbox Publisher picks loan.initiated and publishes to Kafka topic loan.initiated.
CacheConsumer updates Redis:
loan:<appId>:status = INITIATED
loan:<appId>:currentStep = KYC_PENDING
NoSqlConsumer upserts Cosmos document id=appId with event added.
KYC Service subscribes to loan.initiated:
Verifies consent exists for KYC.
Calls eKYC provider (Aadhaar/PAN). On success:
Update Postgres loan_application status -> KYCDONE and insert outbox event kyc.completed.
Outbox -> Kafka kyc.completed; Cache & NoSQL updated.
CreditScore Service consumes kyc.completed: checks consent for credit, calls bureau, writes score to Postgres and outbox_event creditscore.completed.
Eligibility Service consumes creditscore.completed + reads product_config(PERSONAL):
Calls rules engine with facts.
Outcome AUTO_ACCEPT -> writes loan.approved outbox event and sets loan_application.status = APPROVED.
Agreement Service consumes loan.approved:
Generate doc, triggers eSign (consent for data sharing used for eSign flow if required).
On success write agreement.signed outbox event.
Disbursement Service consumes agreement.signed:
Calls payment connector -> CBS -> on success writes loan.disbursed outbox event and creates loan_account entry.
Repayment Service subscribes to loan.approved or agreement.signed to create schedule (repayment.schedule.created).
Every event is captured in Cosmos (NoSqlConsumer) and Redis (CacheConsumer). UI polls Cosmos/Redis for status updates or subscribes to websocket notifications.
Notes: Idempotency checks at step 2 prevent duplicate applications. Consumers persist processed_event record to avoid duplicate processing.
2) BNPL / CONSUMER DURABLE — (Full text flow)
Preconditions: Merchant integration; customer consents to minimal KYC & data sharing.
Sequence:
Merchant frontend / POS -> POST /v1/loan-applications with {product_code: BNPL, merchantId, orderId} and Idempotency-Key.
Loan Orchestration: Write loan_application + outbox_event loan.initiated. Include merchantId.
Outbox -> Kafka; Cache & NoSQL updated.
BNPL KYC: Quick OTP KYC (consent checked). On success kyc.completed.
ALTSCORE Service or internal scoring consumes kyc.completed and loan.initiated:
Runs merchant-specific risk models (merchant acceptance rate, basket size).
Emits creditscore.completed or altscore.completed.
Eligibility Service uses product_config(BNPL) (low thresholds) and typically AUTO_ACCEPT.
Agreement simple acceptance (T&C) -> agreement.signed (may be implicit).
Disbursement Service issues payout to merchant settlement account via Payment Connector -> loan.disbursed (includes merchantSettlementId).
Reconciliation: Settlement engine handles merchant payouts; platform collects repayments from customer via scheduled UPI/EMIs.
Notes: High throughput — ensure partition key includes merchantId or appId for even partitioning.
3) AUTO LOAN — (Full text flow)
Preconditions: Customer or dealer provides vehicle details; customer consents for KYC, credit check, and data sharing (for RTO/hypothecation).
Sequence:
Dealer/Customer UI -> POST /v1/loan-applications with {product_code: AUTO, vehicle: {vin, model, price}} and Idempotency-Key.
Loan Orchestration writes loan_application + outbox loan.initiated and commits.
Outbox -> Kafka; Cache and NoSQL projection update.
KYC Service consumes and completes -> kyc.completed.
CreditScore consumes -> creditscore.completed.
Collateral Service consumes loan.initiated or creditscore.completed:
Calls Valuation API (market price) -> valuation.reported.
Calculates LTV -> write collateral row (valuation, ltv).
Initiates Hypothecation Service (RTO connector) to register lien; on success set registration_status=REGISTERED and publish collateral.verified.
Eligibility Service consumes creditscore.completed + collateral.verified:
Runs rules (check LTV <= threshold) -> emits eligibility.decided.
Underwriting consumes eligibility.decided -> may AUTO_ACCEPT or REFER_MANUAL.
If approved -> loan.approved -> Agreement Service eSigns docs + agreement.signed.
Disbursement Service validates collateral.verified + agreement.signed -> issues disbursement.requested -> payment to dealer -> on success loan.disbursed.
Repayment: schedule created; ledger entries created; Collections service handles EMIs.
Edge/Compensation:
If hypothecation fails: emit lien.registration.failed -> Underwriting may loan.rejected or manual.approval.requested.
If disbursement done but lien later fails, trigger compensation.requested and manual ops.
4) HOME LOAN — (Full text flow) — NEW vs RESALE branching
This combines both variants; product_config decides which branch to follow based on propertyType (NEW/RESALE) and projectApproved flag.
Common start:
Customer UI -> POST /v1/loan-applications {product_code: HOME, propertyType: NEW|RESALE, projectId | address, idempotency_key}.
Loan Orchestration writes loan_application, consent (for legal checks if RESALE), and outbox_event loan.initiated.
Outbox -> Kafka -> Cache & NoSQL updated.
New Project Flow (projectApproved == true)
4a. KYC -> kyc.completed.5a. CreditScore -> creditscore.completed.6a. Orchestrator reads product_config.HOME.variant.NEW (no valuation/legal):
Moves to Underwriting: Underwriting Service uses project-approved rules and may AUTO_ACCEPT if cibil and dti OK.7a. loan.approved -> Agreement eSign -> agreement.signed.8a. Disbursement Service uses disbursement.tranches config and releases tranches on builder_stage.completed notifications, publishing loan.disbursed for each tranche.9a. Repayment schedule created post first disbursement or as configured.
Resale Flow (propertyType == RESALE)
4b. KYC -> kyc.completed.5b. CreditScore -> creditscore.completed.6b. Collateral Service triggers property valuation (valuation.reported) and legal vendor (legal.clearance.completed).7b. Orchestrator collects valuation.reported + legal.clearance.completed and creates Underwriting Case -> manual.approval.requested per product_config.HOME.manual_approval_flow.8b. Human approvers (CreditOfficer -> LegalHead -> RiskHead) complete tasks in Workbench. Each completion publishes manual.approval.completed.9b. Once all approvals done -> loan.approved -> Agreement eSign -> agreement.signed.10b. Disbursement Single-shot: Disbursement Service pays seller/escrow -> loan.disbursed.11b. Repayment schedules activated.
Tranche handling (detailed):
disbursement.tranches is part of product_config (array of conditions).
For each tranche:
Some trigger event (e.g., builder.stage.completed with evidence) is published.
Orchestrator writes outbox_event disbursement.requested.
Disbursement Service validates evidence and issues transfer -> publishes loan.disbursed with trancheNumber.
Each loan.disbursed updates loan_account table (outstanding) in Postgres via a transaction and writes a outbox_event for ledger/projection.
Compensation / exceptions:
If legal exception arises post-disbursement, legal.exception.raised triggers risk workflows and may publish compensation.requested.
Reversals may be partially manual (bank specific).
5) MICRO-LOAN — (Full text flow)
Preconditions: Mobile-first; customer consents to KYC (OTP), alternate data access (UPI history, telco) and data-sharing.
Sequence:
Mobile UI -> POST /v1/loan-applications {product_code: MICRO, amount, tenure} + Idempotency-Key.
Loan Orchestration writes loan_application + outbox_event.
Outbox -> Kafka; Cache & NoSQL updated.
KYC: quick OTP -> kyc.completed.
AltScoring Service consumes loan.initiated + kyc.completed:
Pulls UPI txn history via UPI connector, telco signals, device fingerprint.
Computes altscore -> writes altscore.completed.
Eligibility service runs micro product rules (low thresholds) -> loan.approved.
Agreement (may be implicit via OTP T&C) -> agreement.signed.
Disbursement instant -> loan.disbursed.
Collections via UPI auto-debit or in-app pay.
Comments