Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

⚡ Razorpay AI Revenue Recovery Platform

Razorpay AI Buildathon 2026 — Track 03: AI Revenue Recovery

Python 3.11+ FastAPI Streamlit Plotly Zero Harassment


📌 Executive Summary & Problem Statement

In the Indian payments ecosystem, up to 18–25% of e-commerce, D2C, and SaaS transactions fail due to transient bank downtime, UPI timeout spikes, card spending limits, or checkout dropoffs. Merchants routinely lose crores in revenue every month because existing retry mechanisms are either:

  1. Dumb & Blind: Repeatedly firing immediate retries against failing bank switches, exhausting daily limits and causing customer harassment.
  2. Slow & Manual: Relying on scheduled cron jobs or manual marketing emails hours after the buyer has abandoned the purchase.
  3. Unsafe & Duplicative: Lacking distributed idempotency locks, risking duplicate charges or multiple payment links during webhook retry storms.

The Razorpay AI Revenue Recovery Platform solves this with an end-to-end autonomous recovery engine that:

  • Ingests failed payment webhooks in real time.
  • Diagnoses root causes with a hybrid Deterministic + AI Diagnostic Classifier.
  • Enforces strict Zero-Harassment Guardrail Policies (Max 3 retries, Cooldowns, TRAI Night DND).
  • Executes bounded recovery workflows using Razorpay Smart Payment Links, Mandate Auto-Retries, and WhatsApp 1-Tap Nudges.
  • Provides a real-time Streamlit & Plotly Analytics Dashboard with an immutable audit log.

🏛️ System Architecture

flowchart TD
    A[Failed Payment Event / Webhook] --> B[FastAPI Webhook Receiver / Signature HMAC]
    B --> C[AI Diagnostic Classifier]
    
    subgraph Diagnosis [Multi-Signal Root Cause Analysis]
        C -->|Technical| D1[Gateway 504 / Bank Outage / Socket Hangup]
        C -->|Financial| D2[Low Balance / Daily Card Limit / Inactive Account]
        C -->|Behavioral| D3[OTP Dropoff / MPIN Hesitation / App Switch]
    end

    D1 --> E[Guardrail Policy Engine]
    D2 --> E
    D3 --> E

    subgraph Guardrails [Zero-Harassment Policy Checks]
        E --> G1{Max Attempts >= 3?}
        E --> G2{Cooldown Active?}
        E --> G3{Contact Fatigue / DND Night?}
        E --> G4{Account Frozen / High-Risk?}
    end

    G1 -->|Violated| H[Block & Record in Audit Log]
    G2 -->|Violated| H
    G3 -->|Violated| H
    G4 -->|Violated| H

    G1 & G2 & G3 & G4 -->|All Passed| I[Deterministic Idempotency Key Lock]
    
    subgraph Execution [Razorpay API Dynamic Recovery]
        I --> J1[Razorpay Smart Payment Link]
        I --> J2[WhatsApp Interactive 1-Tap Nudge]
        I --> J3[NPCI E-Mandate Auto-Debit Reschedule]
        I --> J4[Background Exponential Backoff]
    end

    J1 & J2 & J3 & J4 --> K[Structured Audit Logger JSON & Trace IDs]
    K --> L[Streamlit & Plotly Interactive Dashboard]
Loading

🚀 Key Innovations & Core Modules

1. Hybrid AI Diagnostic Classifier (recovery_engine.py)

  • Distinguishes Technical, Financial, and Behavioral payment drop causes.
  • Ingests multiple signals: error codes (GATEWAY_TIMEOUT, INSUFFICIENT_FUNDS, AUTHENTICATION_FAILED, MANDATE_AUTH_TIMEOUT, BAD_REQUEST_PAYMENT_FAILED), error descriptions, customer historical LTV, payment method (UPI vs Card vs Netbanking vs Mandate), and bank issuer state.
  • Generates high-confidence diagnoses (85%–99%) with transparent human-readable reasoning.

2. Zero-Harassment Guardrail Policy Engine

  • Hard Stop Retry Cap: Rejects automated retries when attempt count $\ge 3$.
  • Mandatory Upstream Cooldown: Enforces minimum 30s to 15-minute wait windows to allow NPCI and bank switches to recover.
  • Customer Fatigue Limiter: Enforces max 1 notification per 4-hour window per customer to avoid notification spam.
  • TRAI Night Hours (DND) Compliance: Automatically suppresses outbound interactive WhatsApp/SMS nudges between 21:00 and 09:00 IST, routing them to scheduled morning queues.
  • High-Value Circuit Breakers: Transactions $\ge$ ₹1,00,000 require high-assurance smart payment links rather than blind retries.

3. Mock Razorpay Test API & Idempotency Store

  • High-fidelity simulated Razorpay client implementing:
    • razorpay.PaymentLink.create()
    • razorpay.Subscription.retry() / Mandate Charge
    • razorpay.Invoice.create()
    • Cryptographic HMAC-SHA256 signature verification for webhook payloads.
  • Thread-safe, atomic idempotency storage preventing race conditions and duplicate payment links.

4. Synthetic Indian Payment Benchmark (data/synthetic_payments.json)

  • 50 diverse Indian transaction failure records featuring:
    • Realistic amounts: ₹199 to ₹1,20,000 (micro-transactions, D2C retail, SaaS subscriptions, corporate B2B).
    • Indian payment modes: UPI (@okhdfcbank, @paytm, @ybl, @icici), RuPay/Visa/Mastercard, Netbanking (HDFC, SBI, ICICI, Axis, Kotak, PNB, Canara).

📊 Benchmark Evaluation Results

Running the recovery engine across the 50 synthetic benchmark test cases:

Metric Result Benchmark Target Status
Total Ingested Failed Events 50 transactions 50 ✅ PASS
Total Revenue at Risk ₹6,84,490.00 — —
Total Revenue Recovered ₹5,38,092.00 > 65% ✅ 78.6%
Harassment / False-Positive Rate 0.00% 0.00% ✅ PASS
Proactive Guardrail Interceptions 5 blocked attempts — ✅ PASS
Average Diagnostic Confidence 89.4% > 80% ✅ PASS

🛠️ Quickstart & Setup

1. Prerequisites

  • Python 3.10 or 3.11
  • Pip package manager

2. Installation

Clone the repository and install dependencies:

git clone https://github.com/your-username/razorpay_revenue_recovery.git
cd razorpay_revenue_recovery
pip install -r requirements.txt

3. Run Automated Tests

pytest test_recovery_engine.py -v

4. Launch the Streamlit Analytics Dashboard

streamlit run app.py

Open your browser at http://localhost:8501.

5. Launch the FastAPI REST & Webhook Server (Optional)

uvicorn api:app --reload --port 8000

API Documentation will be live at http://localhost:8000/docs.


📁 Repository Structure

razorpay_revenue_recovery/
├── data/
│   ├── synthetic_payments.json      # 50 diverse Indian failure records
│   └── audit_logs.json              # Persistent structured audit log store
├── recovery_engine.py                # Core Models, AI Classifier, Guardrails, Mock API, Logger
├── api.py                           # FastAPI Webhook Ingestion & REST API
├── app.py                           # Streamlit & Plotly Interactive Dashboard
├── test_recovery_engine.py          # Automated Test Suite (PyTest)
├── requirements.txt                 # Dependencies
├── INCIDENT_2AM.md                  # 2 AM Post-Mortem on Webhook Retries & Idempotency Locks
└── README.md                        # Documentation & Architecture

🌟 Incident Story: The 02:14 AM Flash Sale Thundering Herd

Read the realistic production incident post-mortem in INCIDENT_2AM.md to explore how a high-concurrency webhook retry storm caused duplicate payment link generation and how we resolved it permanently using distributed idempotency lease locks.


Built with ❤️ for the Razorpay AI Buildathon 2026 (Track 03: AI Revenue Recovery)

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages