Transforming failed checkouts, degraded bank rails, and overdue receivables into recovered TPV.
Generative LLM diagnosis proposes. The Deterministic Policy Engine verifies, clamps, and gates. No hallucination ever touches real money.
The Problem β’ Why Razorpay Needs This β’ Architecture β’ 7 Deterministic Guardrails β’ Enterprise Integration Guide β’ Interactive Quickstart β’ API Reference β’ Benchmarks & Verification
In Indian digital commerce and SaaS, between 20% to 35% of all payment transactions fail or are abandoned before completion. These failures occur across multiple vectors:
- Downstream Banking Rail Downtimes: Issuer timeouts (
BANK_TIMEOUT), gateway downtime (GATEWAY_OUTAGE), and NPCI UPI traffic spikes cause immediate transactions to fail. - Payment Method Friction: High-dropoff methods like Netbanking fail frequently, while customers would convert instantly if nudged with a pre-filled UPI Intent link.
- Regulatory Dropoffs (RBI E-Mandate Rules): Recurring subscription charges above βΉ15,000 mandate explicit customer Additional Factor of Authentication (AFA/OTP). Unintelligent auto-retries silently fail and breach central bank regulations.
- Repeat Insufficient Balance: Customers abandon checkouts when their account balance is momentarily low; without a timed, unit-economically viable incentive, the basket is lost forever.
- Overdue B2B Receivables: Commercial invoices sit unpaid for 30β90 days without automated escalation, resulting in severe cash flow drag.
β Naive Retry Blasts β Spams users with identical retry links, triggering telecom DND penalties & consumer churn.
β Dumb Automation β Retries payments while the issuing bank is down, causing cascade gateway failures.
β Unconstrained LLMs β Hallucinates unapproved 50% discounts, erodes merchant margins, or misses compliance rules.
RazorBack is an autonomous, event-driven recovery agent that acts as an intelligent recovery gateway. It reconciles generative reasoning with non-negotiable fintech risk and regulatory boundaries.
Important
The Non-Negotiable Core Invariant:
The LLM never executes anything directly.
The reasoning engine analyzes webhooks and outputs a DiagnosisProposal (root cause diagnosis, suggested channel, and optional incentive).
The Deterministic Policy Engine evaluates this proposal against 7 prioritized hardcoded & merchant guardrails, outputting an authoritative PolicyDecision. Only approved decisions ever invoke execution tools.
flowchart TD
subgraph Ingest ["1. INGESTION & IDEMPOTENCY LAYER"]
A[β‘ Razorpay Webhook Event\npayment.failed / checkout.abandoned / receivable.overdue] --> B{π DB-Level Idempotency Lock\nwebhook_events.event_id PRIMARY KEY}
B -->|Duplicate Arrival| C[β‘ Return Cached Pipeline Result\nZero Duplicate Execution]
B -->|First Arrival| D[(Persistent SQLite DB\nAudit Hash Chained)]
end
subgraph Intelligence ["2. INTELLIGENCE & DIAGNOSIS LAYER"]
D --> E[π§ Multi-Provider Reasoning Engine\nClaude / OpenAI / Local / Fallback]
E --> F[π DiagnosisProposal\nRoot Cause + Channel Switch + Discount]
end
subgraph Guardrails ["3. DETERMINISTIC POLICY ENGINE"]
F --> G{π‘οΈ 7 Priority Guardrails\nFirst Match Wins}
G -->|Rule 1: High Value > βΉ1L| H1[β οΈ ESCALATED: Relationship Manager Queue]
G -->|Rule 2: Gateway Outage| H2[β³ QUEUED: Suppress outreach & queue for sweep]
G -->|Rule 3: RBI AFA Limit > βΉ15k| H3[π ESCALATED: RBI e-Mandate Compliance]
G -->|Rule 4: Anti-Spam / Opt-Out| H4[π« BLOCKED: Frequency cap reached or opted out]
G -->|Rule 5: Discount Clamp| H5[βοΈ CLAMPED: Clamped to max βΉ150 margin cap]
G -->|Rule 6: Economic Floor| H6[π ZERO-COST: Recovery cost > 40% amount]
G -->|Rule 7: Passed All Checks| H7[β
APPROVED: Authorized for Execution]
end
subgraph Execution ["4. SAFE EXECUTION DISPATCHER"]
H7 --> I{Double-Charge Check\nIs order already captured?}
I -->|Captured| J[π« Reject: blocked_order_already_captured]
I -->|Not Captured| K[Void prior active links\nsuperseded_by_new_link]
K --> L[π Dispatch Tools\nRazorpay UPI Link Tool + WhatsApp / SMS Comms]
end
subgraph Audit ["5. IMMUTABLE AUDIT & LIVE STREAM"]
H1 & H2 & H3 & H4 & H5 & H6 & L --> M[π SHA-256 Tamper-Evident Hash Chaining\nprev_hash β entry_hash]
M --> N[π‘ Real-Time Server-Sent Events SSE\nGET /stream/events]
end
Failed transactions represent money that merchants already fought to acquire. By automatically converting 50% of automated-eligible failed checkouts into successful payments, Razorpay merchants capture revenue that would otherwise leak to competitor gateways or cash-on-delivery.
Customer double-charging during recovery is a major regulatory and chargeback nightmare. RazorBack enforces strict link exclusivity: creating a new payment link automatically invalidates all previous active links (superseded_by_new_link). When an order.paid event arrives, all active links are immediately voided (order_already_captured), completely preventing double-debits.
During major bank outages (e.g., HDFC or SBI core banking slowdowns), naive systems flood banking rails with retries, compounding the failure. RazorBack's Bank Outage Worker detects outages, pauses customer outreach, queues events, and sweeps them for replay only when telemetry confirms the rail is healthy (UP).
Under RBI guidelines, automated recurring debits above βΉ15,000 without fresh OTP authentication trigger severe regulatory penalties. RazorBack's Rule 3 hardcodes RBI compliance at the policy engine level: no merchant config or LLM hallucination can ever bypass or weaken this check.
The Policy Engine evaluates rules in strict priority order (first match wins):
| # | Priority Rule | Trigger Condition | Enforcement Action | Regulatory / Business Rationale |
|---|---|---|---|---|
| 1 | B2B / High-Value Escalation | amount_inr > βΉ100,000 (Configurable) |
status=ESCALATEDfinal_action=ESCALATE_TO_HUMAN |
High-value commercial accounts carry substantial relationship risk. Generic bot messages are prohibited; routed to dedicated account managers. |
| 2 | Bank Outage Queueing | failure_code == GATEWAY_OUTAGE |
status=QUEUEDfinal_action=QUEUE_FOR_OUTAGE_RECOVERY |
Prevents customer panic and rail hammering during banking downtime. Events are queued and replayed once the bank recovers. |
| 3 | RBI Mandate AFA Limit | failure_code == MANDATE_AFA_EXCEEDED and amount_inr > βΉ15,000 |
status=ESCALATEDfinal_action=ESCALATE_TO_HUMAN |
NON-CONFIGURABLE RBI COMPLIANCE: Recurring charges > βΉ15k legally require fresh OTP / customer authentication. Automated retries are prohibited. |
| 4 | Contact Frequency & Opt-Out | contact_count_last_24h >= 2 or customer_opted_out == True |
status=BLOCKEDfinal_action=NO_ACTION |
Anti-Spam & TRAI DND Compliance: Customer opt-out is an irrevocable law. Max 2 touches per 24 hours prevents brand fatigue. |
| 5 | Discount Cap Clamping | proposed_discount_inr > βΉ150 (Configurable) |
Clamps discount down to βΉ150.00 and continues pipeline | Protects merchant gross margins from LLM hallucinations offering reckless incentives to artificially inflate recovery rates. |
| 6 | Economic Floor | (discount + βΉ5 messaging) > 40% of amount |
status=APPROVEDfinal_action=SEND_PAYMENT_LINKfinal_discount=βΉ0.0 |
Unit Economic Viability: If recovery cost exceeds 40% of invoice value, strips financial incentives and falls back to zero-cost delivery. |
| 7 | Default Approval | None of the above triggered | status=APPROVEDfinal_action=proposed_actionfinal_discount=effective_discount |
Validated and safe proposal is authorized for execution. |
Integrating RazorBack into an existing fintech or e-commerce backend requires less than 15 minutes.
In your Razorpay Dashboard (Settings β Webhooks), point the following event types to RazorBack's endpoint:
payment.failedorder.paidcheckout.abandonedreceivable.overdue
URL: https://your-domain.com/webhook
Secret: Set your webhook secret in RAZORPAY_WEBHOOK_SECRET for automated HMAC-SHA256 signature verification.
Clone and start the self-contained container:
git clone https://github.com/YEsh-DEV/Autonomous-Recovery-Agent.git
cd Autonomous-Recovery-Agent
# Copy environment template
cp .env.example .env
# Launch with persistent data volume
docker compose up -dEvery merchant has distinct risk tolerance. Configure custom thresholds via the Admin API:
curl -X POST "http://localhost:8000/admin/merchant-config" \
-H "Content-Type: application/json" \
-d '{
"merchant_id": "merchant_enterprise_01",
"discount_cap_inr": 250.0,
"high_value_escalation_threshold_inr": 150000.0,
"economic_floor_pct": 0.35,
"contact_frequency_cap_per_24h": 2,
"llm_provider": "claude",
"notification_provider": "twilio_whatsapp"
}'(Note: Regulatory rules like RBI e-mandate limits and customer opt-outs remain hardcoded and cannot be bypassed).
Connect your internal frontend or admin panel to the Server-Sent Events (SSE) stream for real-time observability:
const eventSource = new EventSource("http://localhost:8000/stream/events");
eventSource.onmessage = (event) => {
const auditEntry = JSON.parse(event.data);
console.log(`[${auditEntry.step.toUpperCase()}] Event: ${auditEntry.event_id}`, auditEntry.detail);
};High-ticket enterprise receivables and complex mandate failures are automatically routed to /escalations. Your support or relationship management team can query this queue directly:
curl -X GET "http://localhost:8000/escalations"The backend reads ALLOWED_ORIGINS from environment (comma-separated).
Default: "*" (all origins).
On Render (or any prod host), set:
ALLOWED_ORIGINS=https://your-frontend.vercel.app
No code change required β the middleware already parses this env var.
- Python 3.12+ (or Docker)
- SQLite3
# 1. Create and activate virtual environment
python3 -m venv .venv
source .venv/bin/activate
# 2. Install production dependencies
pip install -r requirements.txt
# 3. Run the automated test suite (64 tests)
pytest -v
# 4. Start the FastAPI application
uvicorn core.main:app --host 0.0.0.0 --port 8000 --reloadInteractive API documentation will be available at:
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
Processes incoming failed payment webhooks through the full idempotent pipeline: Ingest β Diagnose β Policy β Execute β Audit.
curl -X POST "http://localhost:8000/webhook" \
-H "Content-Type: application/json" \
-d '{
"event_id": "evt_live_89102",
"event_type": "payment.failed",
"order_id": "order_live_4491",
"customer_id": "cust_ananya_99",
"amount_inr": 3499.00,
"failure_code": "BANK_TIMEOUT",
"payment_method": "netbanking_hdfc",
"customer_contact_count_last_24h": 0,
"customer_opted_out": false,
"is_b2b_receivable": false,
"created_at": "2026-09-04T10:00:00Z"
}'Synchronous Response:
{
"status": "success",
"message": "Event processed",
"event_id": "evt_live_89102",
"diagnosis": {
"proposed_action": "send_payment_link",
"proposed_channel": "whatsapp",
"proposed_discount_inr": 0.0,
"proposed_language": "hi-en",
"confidence": 0.75,
"reasoning": "Netbanking (netbanking_hdfc) failed with BANK_TIMEOUT - propose UPI payment link for higher success rate"
},
"decision": {
"status": "approved",
"final_action": "send_payment_link",
"final_discount_inr": 0.0,
"rule_triggered": null,
"reason": "All guardrail checks passed. Approved proposed action: send_payment_link."
},
"execution": {
"executed": true,
"tool_used": "RazorpayLinkTool",
"payload": {
"payment_link": {
"id": "plink_yfsuvks1qpgy",
"url": "https://rzp.io/l/yfsuvks1qpgy",
"amount_inr": 3499.0,
"prefilled_method": "upi"
},
"comms": {
"channel": "whatsapp",
"status": "delivered",
"message_preview": "Hume khed hai, aapka payment βΉ3,499 ke liye complete nahi ho paaya (bank timeout). Yeh raha aapka secure UPI link: https://rzp.io/l/yfsuvks1qpgy"
}
}
}
}Recomputes SHA-256 hashes from genesis across the entire audit database to mathematically verify zero tampering.
curl -X GET "http://localhost:8000/audit/verify"{
"valid": true,
"checked_entries": 56,
"first_broken_entry": null
}Returns the immutable, explainable lifecycle step trail (ingest β diagnosis β policy β execution).
curl -X GET "http://localhost:8000/audit/evt_live_89102"Lists all transactions flagged by Guardrails 1 & 3 (b2b_escalation_threshold or mandate_afa_limit) for human manager intervention.
Synchronously executes a sweep across all queued recovery events against the live bank health monitor.
Evaluated across our held-out test cohort (data/held_out_batch.json):
| Segment | Transactions | Baseline Recovery Rate | RazorBack Recovery Rate | Performance Lift | Revenue Recovered |
|---|---|---|---|---|---|
Automated-Eligible (APPROVED) |
4 | 25.0% | 50.0% | +25.0 pp | βΉ65,082 (+βΉ36.9k lift) |
High-Value B2B (ESCALATED) |
5 | β (Unsafe to bot) | Human Desk | Compliant | βΉ846,022 safeguarded |
RBI Mandate >βΉ15k (ESCALATED) |
2 | β (Illegal to bot) | Human Desk | Compliant | βΉ150,000 safeguarded |
Opt-Out / Frequency Cap (BLOCKED) |
3 | β (DND violation) | Blocked | Compliant | Anti-spam protected |
Bank Outage (QUEUED) |
1 | β (Rail down) | Outage Queue | Compliant | Saved from cascade fail |
Key Takeaway: A naive system claims higher raw numbers only by illegally messaging opted-out customers, violating RBI rules, and spamming rate-limited users. On transactions legally and commercially approved for automation, RazorBack delivers +25.0 pp higher recovery rate and recovers transactions ~26 hours faster.
core/tests/test_api.py ......................... [ 6%]
core/tests/test_end_to_end_smoke.py ............ [ 8%]
core/tests/test_idempotency.py ................. [ 11%]
core/tests/test_policy_engine.py ............... [ 41%]
core/tests/test_production_readiness.py ........ [ 53%]
core/tests/test_stream_events.py ............... [ 55%]
core/tests/test_tamper_evident_audit.py ........ [ 58%]
core/tests/test_webhook_signature.py ........... [ 63%]
intelligence/tests/test_llm_provider_safety.py . [ 78%]
intelligence/tests/test_reasoning_engine.py .... [100%]
======================== 64 passed in 3.36s =========================
Autonomous-Recovery-Agent/
βββ π core/ # Deterministic Core & Guardrail Engine
β βββ db.py # SQLite persistence, idempotency lock, SHA-256 hash chaining
β βββ policy_engine.py # 7 deterministic guardrail rules with regulatory docstrings
β βββ audit.py # Structured audit logger & real-time SSE broadcaster
β βββ executor.py # Execution dispatcher with link exclusivity & double-charge defense
β βββ bank_health.py # Deterministic BankHealthMonitor (UP, DEGRADED, DOWN)
β βββ outage_worker.py # Outage replay background worker (APScheduler)
β βββ main.py # FastAPI service exposing /webhook, /audit, /stream/events
β βββ π tests/ # 40 core automated unit, integration, & stress tests
βββ π intelligence/ # Agent Intelligence & Diagnostics
β βββ reasoning_engine.py # Public diagnose() API with discount sanitizer & fallback
β βββ llm_providers.py # Abstract LLM provider: Claude, OpenAI, Local, Fallback
β βββ notification_providers.py # Real delivery channels: Twilio WhatsApp, SendGrid, Mock
β βββ templates.py # Multilingual Hinglish & English tone families (apology, nudge, b2b)
β βββ tools.py # Mock execution tools (RazorpayLinkTool, CommsTool)
β βββ batch_runner.py # Baseline vs Agent benchmark runner
β βββ π tests/ # 24 intelligence safety & provider tests
βββ π shared/ # Frozen Domain Contracts
β βββ schemas.py # Enums and Pydantic models (FROZEN CONTRACT)
β βββ __init__.py
βββ π data/ # Datasets & Persistent Storage
β βββ synthetic_events.json # 65-event diverse training/testing dataset
β βββ held_out_batch.json # 15-event held-out evaluation dataset
β βββ pitch_demo_set.json # 6 curated archetype demo records
β βββ recovery_agent.db # Active persistent file-backed SQLite database
βββ π scripts/ # Executable Drivers & Demos
β βββ run_demo.py # Pitch demo driver POSTing to live /webhook
β βββ test_nvidia_llm.py # Standalone smoke test for NVIDIA NIM / OpenAI endpoints
βββ π reports/ # Architecture & Verification Documentation
β βββ agent_1_report.md # Handover report for Deterministic Core & Guardrail Engine
β βββ agent_2_report.md # Handover report for Synthetic Data & Intelligence Engine
β βββ batch_run_summary.md # Machine and human-readable benchmark findings
βββ Dockerfile # Multi-stage Python 3.12-slim production container
βββ docker-compose.yml # Container orchestration with persistent volume mapping
βββ requirements.txt # Locked production dependencies
βββ .env.example # Production environment template
βββ README.md # You are here β¨