🌐 EScRᴏᴡ: Resilient, Fraud-Safe & Optimized
Digital Transaction System
🔹 Core Concept
EScRᴏᴡ is a next-generation transaction safety and optimization framework designed to enhance
existing digital payment systems (UPI, NEFT, wallets, debit/credit cards). It ensures: - Fraud and Accident
Recovery - Optimization and Smart Retry Handling - Critical Failure Resilience - Scalable Performance
(scale-up + scale-out)
The system provides a protective layer over transactions, making digital payments more trustworthy,
reliable, and efficient.
🔹 How It Works (Detailed)
1. Threshold System (Protected State)
• Entry: Every transaction first enters a temporary escrow buffer ( THRESHOLD_HELD ) before being
finalized. The system reserves the amount in the payer's ledger and creates an internal escrow entry;
external interbank settlement is deferred when ESCROW mode applies.
• Window: The transaction remains in the threshold window for a configurable period (default: 30
minutes) unless an earlier terminal event occurs (auto-cancel, payee accept, immediate settlement
by policy).
• Continuous Evaluation: During this period the transaction is continuously scored and checked by
the Decision Engine (fraud model + rule engine + verification service).
2. Core Components (expanded)
• API / Gateway — handles incoming payment and retrieval requests; enforces idempotency and rate-
limits.
• Transaction Store & Immutable Journal — single source-of-truth with append-only journal entries
for every financial action.
• Escrow Ledger — internal pool accounts that temporarily hold funds for ESCROW-mode
transactions.
• Decision Engine — combines rule-based logic and ML models for continuous scoring
( fraud_score , proof_score , anomaly_score ).
• Verification Service — automated proof validation (image tamper check, text extraction, timestamp
validation) and manual ops UI for edge cases.
• Outbox & Broker — transactional outbox pattern ensuring reliable message emission to banks/
NPCI, with idempotent consumers.
1
• Reconciliation Service — correlates bank/NPCI settlement files with internal transactions and
resolves breaks.
• Monitoring & Autoscaling Controller — triggers scale-up/scale-out actions, health checks, and
routing changes.
• Notification Service — in-app push, SMS, email to payer and payee with status updates.
3. Data Model (key fields)
Add/extend these fields in transactions table: - txn_id UUID (global idempotency key) - mode
ENUM {ESCROW, IMMEDIATE} - state ENUM {INIT, THRESHOLD_HELD, VERIFYING, PROCEED_TO_SETTLE,
SETTLED, REFUNDED, FAILED} - threshold_expires_at TIMESTAMP - decision_score FLOAT -
proof_score FLOAT - retrieve_requests JSONB - escrow_account_id UUID (nullable)
New tables: - retrieve_requests {id, txn_id, payer_id, proof_docs JSONB, status,
created_at, operator_id, decision_at} - verification_logs {id, request_id,
model_outputs, tamper_score, text_matches, timestamp} - claim_tickets {id, txn_id,
severity, assigned_to, status, notes}
4. Decision Logic & Policies (precise)
Continuous scoring (runs every few seconds while txn in THRESHOLD_HELD): - Inputs: payer reputation,
payee reputation, device fingerprint, geovelocity, VPA age, payee-added-age, transaction velocity, merchant
risk, message memo, proof data (if submitted). - Models produce: fraud_score ∈ [0,1] ,
anomaly_score , and proof_score (if proof provided).
Policy rules (deterministic layer): 1. If fraud_score >= 0.98 → AUTO_CANCEL (if ESCROW:
immediate reversal; if IMMEDIATE: attempt automated NPCI reversal + claim ticket). 2. If
proof_score >= 0.85 (valid proof for accidental payment) → AUTO_CANCEL . 3. If amount >=
MANUAL_REVIEW_THRESHOLD → VERIFYING (manual ops required regardless of scores). 4. If
payee_accepts (merchant explicitly confirms) → PROCEED_TO_SETTLE (early settle). 5. If
threshold_expires_at reached and no blocking conditions → PROCEED_TO_SETTLE → initiate
settlement.
5. Reliability & Critical Failure Handling
• Bank/PSP Node Failure Detection: health-check endpoints + rolling success-rate per node tracked
in metrics.
• Retry Strategy: on transient failure (HTTP timeout, socket errors), perform short-interval retries
(e.g., 0.5s, 1s, 2s, 5s) up to a bounded number of attempts. If all attempts fail, keep transaction
THRESHOLD_HELD and queue a background retry worker.
• Back-off & Circuit Breakers: if a bank node shows high error rate, trip circuit and route to alternate
node or mark transactions as PENDING for background reconciliation.
2
• Guaranteed Safe State: funds never considered finally settled until SETTLED state; in ESCROW
mode, the payer's balance is restored automatically on reversal.
6. Autoscaling & Load Management
Scale-Up (vertical): - Increase resources (DB read replicas, worker memory/CPU) during spikes via
orchestration (Kubernetes HPA/VPA or cloud auto-scaling groups). Scale-Out (horizontal): - Add more
stateless gateway and worker pods; partition tasks by txn_id hash to ensure ordering. Queue
Management: - Use sharded durable queues (Kafka partitions keyed by txn_id ) to keep per-transaction
ordering and high throughput. Health-based Routing: - Load balancer consults node health metrics and
latency histograms; routes new requests to healthy nodes only.
🔹 Demonstrative Examples (step-by-step)
Example A: Accidental Payment — Wrong Beneficiary (ESCROW mode)
Scenario: Payer Abhi sends ₹2,500 intended for "Dad" but enters wrong VPA (Person B).
Timeline & Steps: 1. T=00:00 Abhi initiates payment. System creates txn in THRESHOLD_HELD ,
mode=ESCROW , threshold_expires_at=T+30m . Escrow ledger debits payer and credits escrow pool. 2.
T=00:02 Abhi realizes mistake and taps "Retrieve" in app. App captures proof (screenshot of intended
contact) and uploads. 3. T=00:02-00:03 Verification Service runs: - OCR extracts text from screenshot →
matches intended VPA name. - Tamper detection returns low tamper_score. - proof_score = 0.92 . 4.
Decision Engine sees proof_score >= 0.85 → AUTO_CANCEL . 5. System invokes
reverse_from_escrow(txn) → ledger creates reversal entry, payer balance credited. [Link] =
REFUNDED . 6. Notifications: Abhi (payer) receives "Refunded"; Person B (payee) receives "Payment retrieved
by payer".
Outcome: Instant, automated retrieval without NPCI involvement; minimal ops required.
Example B: Social-Engineering Fraud — Merchant Phishing (IMMEDIATE fallback)
Scenario: Scammer creates convincing merchant profile; Payer sends ₹10,000; system uses IMMEDIATE
mode for trusted merchant list but Decision Engine flags anomaly.
Timeline & Steps: 1. T=00:00 Payment submitted; mode=IMMEDIATE due to payee flagged as merchant
(but low reputation). System submits settlement to NPCI. NPCI acknowledges settlement ( SETTLED ) to
payee bank. 2. T=00:01 Decision Engine detects abnormal patterns (new merchant, high velocity from
same payer, suspicious device fingerprint) ⇒ fraud_score = 0.96 . 3. System attempts
automated_reversal_via_npci(txn) immediately. - First attempt fails (payee bank reports funds
credited and moved to merchant wallet outside PSP). - System creates claim_ticket and escalates to
ops. 4. Ops investigates: collects chat logs / merchant KYC. If fraud confirmed, ops initiates legal/regulatory
3
recovery (can be slow). Additional protections: freeze merchant holdings at PSP if merchant on same
platform.
Outcome: Automated recovery likely to fail for cross-bank immediate settlement; manual ops & legal
needed. This shows why ESCROW mode for new/untrusted payees reduces this risk.
Example C: Bank Server Crash + Retry (Optimization & Reliability)
Scenario: During T+0, payer sends ₹5,000. The payee bank's UPI endpoint is temporarily down.
Timeline & Steps: 1. T=00:00 Payment is created in THRESHOLD_HELD ; system attempts settlement. 2.
T=00:00:00 First call to payee bank times out. Worker does short retries: 0.5s, 1s, 2s. All fail. 3. System
detects bank endpoint error rate rising → circuit breaker trips. Remaining new txns routed to alternate
node or marked PENDING . 4. Original txn remains THRESHOLD_HELD and enters background retry
queue. Notification to payer: "Processing — temporary bank issue". 5. T=00:02 Bank recovers.
Background worker reattempts settlement, receives success ACK. [Link] set to SETTLED and payee
credited. 6. If bank did not recover by threshold_expires_at , system auto-refunds payer (if ESCROW)
or creates a claim ticket (IMMEDIATE).
Outcome: No partial debit/credit states; retries avoid premature failure; user experience kept informed.
🔹 Pseudocode — Key Routines
Payment init + monitoring
def initiate_payment(req):
txn = create_txn(req, state='THRESHOLD_HELD')
if policy_requires_escrow(txn):
escrow.debit_payer(txn)
else:
submit_settlement_async(txn)
schedule_monitor([Link], interval=5)
def monitor_txn(txn_id):
txn = load_txn(txn_id)
while now() < txn.threshold_expires_at and not [Link]:
score = decision_engine.score(txn)
if score.auto_cancel:
if [Link] == 'ESCROW':
[Link](txn)
txn.set_state('REFUNDED')
notify_both(txn)
4
return
else:
if attempt_npci_reversal(txn):
txn.set_state('REFUNDED')
notify_both(txn)
return
else:
create_claim_ticket(txn)
notify_payer('Escalated to ops')
return
if txn.payer_requested_retrieval:
handle_retrieve_request(txn)
sleep(poll_interval)
if not [Link]:
proceed_to_settle(txn)
🔹 KPIs & Observability
• Pending Rate: % of txns in THRESHOLD_HELD
• Auto-Refund Rate: % of txns auto-refunded via ESCROW
• Manual Escalation Rate: % requiring ops intervention
• Avg Verification Time: time to accept/decline retrieval
• Reversal Success Rate: % of successful automated reversals (IMMEDIATE & ESCROW)
• Node Health Metrics: per-bank success rate, latency p50/p95/p99
Tracing should carry correlation_id across all hops (client → PSP → Bank → NPCI) for full auditability.
🔹 Operational Runbooks (selected)
• High Pending Spike: increase monitoring worker concurrency, add temporary read replicas, and
route suspect flows to manual review backlog.
• Bank Outage: trip circuits to that bank, route new txns to alternate banks if allowed; notify
customers of degraded service.
• Fraud Surge: globally tighten thresholds, increase manual review capacity, and block repeat
offenders.
🔹 Rollout Recommendations
1. Pilot ESCROW mode for new merchants and flagged payee categories.
2. Monitor KPIs for 4 weeks; iterate thresholds & model features.
3. Expand ESCROW coverage gradually and provide merchant incentives to accept provisional
settlement.
5
🔹 Next Steps I can do for you
• Add sequence diagrams (rendered as ASCII or provide Mermaid code) inside this canvas.
• Generate OpenAPI endpoints & DB migration SQL for new tables/fields.
• Produce sample operator-runbook docs in a separate canvas.
Tell me which of these you want and I’ll update the canvas accordingly.