Skip to content

About

Autonomous AI revenue recovery engine for Razorpay. Intercepts payment failures, enforces deterministic RBI guardrails, and recovers lost TPV over UPI & WhatsApp in <60s.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

⚑ RazorBack β€” Autonomous Revenue Recovery Agent

Production-Grade AI Revenue Recovery & Deterministic Guardrail Engine for Razorpay

Python FastAPI SQLite Tests Docker Track

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


πŸ“Œ The Problem Statement

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:

  1. Downstream Banking Rail Downtimes: Issuer timeouts (BANK_TIMEOUT), gateway downtime (GATEWAY_OUTAGE), and NPCI UPI traffic spikes cause immediate transactions to fail.
  2. Payment Method Friction: High-dropoff methods like Netbanking fail frequently, while customers would convert instantly if nudged with a pre-filled UPI Intent link.
  3. 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.
  4. 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.
  5. Overdue B2B Receivables: Commercial invoices sit unpaid for 30–90 days without automated escalation, resulting in severe cash flow drag.

Why Existing Solutions Fail

❌ 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.

πŸš€ The Solution: RazorBack

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
Loading

πŸ’‘ How This Empowers Razorpay

1. Direct TPV (Transaction Processed Value) Expansion

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.

2. Eliminating Double-Charge Liabilities

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.

3. Protecting Bank & Gateway Partner Relationships

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).

4. Zero-Hallucination Compliance (RBI e-Mandate Framework)

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 7 Deterministic Guardrails

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=ESCALATED
final_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=QUEUED
final_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=ESCALATED
final_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=BLOCKED
final_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=APPROVED
final_action=SEND_PAYMENT_LINK
final_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=APPROVED
final_action=proposed_action
final_discount=effective_discount
Validated and safe proposal is authorized for execution.

🏒 How Companies Can Use This in Their System

Integrating RazorBack into an existing fintech or e-commerce backend requires less than 15 minutes.

Step 1: Configure Your Razorpay Webhooks

In your Razorpay Dashboard (Settings βž” Webhooks), point the following event types to RazorBack's endpoint:

  • payment.failed
  • order.paid
  • checkout.abandoned
  • receivable.overdue

URL: https://your-domain.com/webhook
Secret: Set your webhook secret in RAZORPAY_WEBHOOK_SECRET for automated HMAC-SHA256 signature verification.

Step 2: Deploy RazorBack via Docker Compose

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 -d

Step 3: Customize Multi-Tenant Guardrails for Your Brand

Every 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).

Step 4: Stream Live Audits to Your Operations Dashboard

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);
};

Step 5: Staff the Human-in-the-Loop Review Desk

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"

Production CORS Hardening (One-Line Change)

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.


⚑ Interactive Quickstart

Prerequisites

  • Python 3.12+ (or Docker)
  • SQLite3

Local Environment Setup

# 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 --reload

Interactive API documentation will be available at:


πŸ’» Complete API Reference

1. Ingest Webhook (POST /webhook)

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"
      }
    }
  }
}

2. Verify Audit Log Cryptographic Hash Chain (GET /audit/verify)

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
}

3. Fetch Event Audit Trail (GET /audit/{event_id})

Returns the immutable, explainable lifecycle step trail (ingest βž” diagnosis βž” policy βž” execution).

curl -X GET "http://localhost:8000/audit/evt_live_89102"

4. Human-in-the-Loop Review Queue (GET /escalations)

Lists all transactions flagged by Guardrails 1 & 3 (b2b_escalation_threshold or mandate_afa_limit) for human manager intervention.

5. Trigger Outage Recovery Sweep (POST /admin/sweep-now)

Synchronously executes a sweep across all queued recovery events against the live bank health monitor.


πŸ“Š Benchmarks & Test Verification

1. Metric Segmentation (The Fair Comparison)

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.

2. Comprehensive Test Suite (64 / 64 Passing)

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 =========================

πŸ—‚οΈ Project File Structure

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 ✨

Built with ❀️ for the Razorpay AI Buildathon 2026

Track 03: AI Revenue Recovery

About

Autonomous AI revenue recovery engine for Razorpay. Intercepts payment failures, enforces deterministic RBI guardrails, and recovers lost TPV over UPI & WhatsApp in <60s.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages