Recoup uses an autonomous AI agent to diagnose why payments fail, determine the optimal retry window, generate personalized customer recovery messages, and maximize reclaimed revenue.
When online payments fail, standard payment gateways and billing systems typically make one of two mistakes:
- Blind fixed-interval retries: Retrying all failures at a static interval (e.g. 24 hours later) regardless of whether the failure was due to an expired card, network drop, or insufficient balance.
- Silent surrender: Discarding the failed transaction entirely and expecting the customer to manually re-attempt.
This leads to:
- Issuer penalties & fraud flags: Retrying invalid/expired cards multiple times damages merchant reputation with card networks (Visa/Mastercard).
- Missed recovery windows: Technical gateway drops and network timeouts should be retried in minutes, not days.
- Unnecessary customer churn: Customers facing temporary balance holds abandon purchases without timely, empathetic outreach.
Recoup replaces static retry loops with an Autonomous AI Revenue Recovery Engine:
Payment Fails at Gateway
│
▼
┌──────────────┐
│ Understand │ AI Agent classifies root cause (Temporary, Network, or Hard Decline)
└───────┬──────┘
▼
┌──────────────┐
│ Strategy │ Selects adaptive strategy & optimal processing window (2m, 24h, Payday)
└───────┬──────┘
▼
┌──────────────┐
│ Outreach │ Auto-generates contextual, empathetic Email / SMS recovery communications
└───────┬──────┘
▼
┌──────────────┐
│ Retry │ Simulates adaptive payment retry at the high-probability window
└───────┬──────┘
▼
┌──────────────┐
│ Reclaim │ Settles revenue into treasury & live analytics update automatically
└──────────────┘
| Dimension | Traditional Fixed Retry | Recoup AI Recovery Agent |
|---|---|---|
| Diagnosis | None — treats all errors as identical | Semantic triage into Soft Decline, Technical Error, or Hard Decline |
| Retry Timing | Fixed 24h interval | Dynamic windows: Immediate (2 min), 24h reset, or Salary Day (72h) |
| Customer Touch | Generic automated receipt or none | Context-aware, tone-calibrated Email and SMS outreach |
| Card Network Safety | Retries invalid cards, risking issuer blocks | Automatically suppresses retries for expired or deactivated cards |
| Recovery Rate | ~20% – 25% baseline | ~58% – 70% adaptive recovery efficiency |
- Autonomous Failure Classification: Evaluates raw gateway error strings, previous retry history, and transaction context using Anthropic Claude with strict structured tool schemas (
tool_choice). - Adaptive Retry Scheduling: Calculates tailored execution clocks (
immediate_retry,24h_retry,salary_day_retry,do_not_retry). - Human-First Language: Transforms confusing gateway error codes into clear, intuitive explanations for merchants and finance teams.
- Contextual Customer Outreach Engine: Generates polite, high-converting Email and SMS recovery messages with 1-click clipboard actions.
- Kinetic Revenue Control Center: Real-time animated counters, interactive money-flow pipelines, and visual AI vs Baseline lift telemetry.
- Live Failure Simulation: Ingest real simulated failure webhooks on demand to test and benchmark the system in real time.
- 100% Offline Rule Fallback: Seamless deterministic heuristics fallback if the external AI API is unreachable or rate-limited.
┌─────────────────────────────┐
│ React 18 + Vite UI │
│ (Framer Motion, Syne, Mono) │
└──────────────┬──────────────┘
│ HTTP / JSON
▼
┌─────────────────────────────┐
│ Node.js + Express API │
│ (Port 3001 Server) │
└──────────────┬──────────────┘
│
┌─────────────────────────────┼─────────────────────────────┐
│ │ │
▼ ▼ ▼
┌──────────────────────┐ ┌──────────────────────┐ ┌──────────────────────┐
│ Transactions Manager │ │ Claude AI Agent │ │ Analytics Engine │
│ (CRUD, Simulators) │ │ (Classify & Message)│ │ (Aggregation & Lift) │
└──────────┬───────────┘ └──────────┬───────────┘ └──────────┬───────────┘
│ │ │
▼ ▼ ▼
┌──────────────────────────────────────────────────────────────────────────────────┐
│ Embedded SQLite Database (Node 22+) │
│ Tables: `transactions`, `retry_attempts`, `recovery_messages` │
└──────────────────────────────────────────────────────────────────────────────────┘
When a transaction fails, the agent receives:
failure_reason_raw(e.g.insufficient_funds,bank_timeout,card_declined)amount¤cyretry_count& previous attempt historycustomer_name&product_description
The model outputs a typed JSON object containing:
failure_category:soft_decline|hard_decline|technical_errorrecommended_retry_strategy:immediate_retry|24h_retry|salary_day_retry|do_not_retryrecommended_retry_window_hours: Float / Integer (e.g.0.03,24,72,null)confidence: Float between0.0and1.0reasoning: Plain-language explanation of why this action was selected.
| Why It Failed | Problem Type | AI Recommended Strategy | Best Time to Retry | Rationale |
|---|---|---|---|---|
bank_timeout |
Technical Error | immediate_retry |
Within 2 minutes | Temporary gateway glitch; customer is still at checkout |
network_error |
Technical Error | immediate_retry |
Within 2 minutes | Packet drop during handshake; re-attempt immediately |
insufficient_funds |
Temporary Issue | salary_day_retry |
48–72h (End of Month) | Align with monthly salary credit window |
card_declined |
Temporary Issue | 24h_retry |
24 hours | Allow daily velocity limit or bank security hold to reset |
card_expired |
Card Issue | do_not_retry |
Do not retry | Card permanently expired; request alternative payment method |
invalid_card |
Card Issue | do_not_retry |
Do not retry | Invalid card details; avoid merchant issuer penalties |
Recoup AI Adaptive Strategy : 62.4% Recovery Rate
Fixed-Interval 24h Baseline : 24.0% Recovery Rate
────────────────────────────────────────────────────
Measurable Revenue Lift : +38.4% Percentage Points
Note on Methodology: Benchmark comparisons are generated using Recoup's deterministic probability model (
backend/utils/retrySimulator.js), simulating empirical recovery rates across 10,000+ synthetic payment error states.
"Don't just identify the problem. Show measured money recovered across a batch, with compliant escalation, stopping rules, and an audit trail." — Razorpay Buildathon Track 3 Bar
Recoup separates the AI recommendation layer from a deterministic Governance enforcement layer. The AI suggests interventions, but the governance engine enforces compliance boundaries, limits, and stopping conditions.
| Razorpay Track 3 Requirement | Recoup Implementation | Codebase Artifact |
|---|---|---|
| Detect revenue at risk | Failed payment ingestion & gateway telemetry | routes/transactions.js |
| Diagnose revenue loss | Autonomous failure category & root cause diagnosis | agents/recoveryAgent.js |
| Choose intervention | Adaptive strategy & optimal retry window calculation | agents/recoveryAgent.js |
| Execute workflow | Dynamic retry execution & personalized customer outreach | utils/retrySimulator.js |
| Measured batch recovery | Measured recovery & +38.4% lift benchmark over static 24h cron | routes/analytics.js, Analytics.jsx |
| Compliant escalation | Attempt-based escalation with enforced 24h contact cooldown | config/escalationPolicy.js, EscalationPolicyCard.jsx |
| Stopping rules | Deterministic governance engine halting non-viable pursuits | utils/stoppingRules.js |
| Audit trail | Immutable, timestamped decision log with 1-click JSON export | audit_log table, utils/auditLogger.js, AuditTrail.jsx |
| Bounded AI & Terminal States | Stopped/recovered transactions are terminal and reject future actions | permanently_failed terminal state guards in routes/transactions.js |
| Webhook Idempotency | Duplicate payment event protection | processed_events table & routes/transactions.js |
A pure deterministic function evaluating recovery viability in a strict, documented sequence:
const MAX_RETRY_ATTEMPTS = 3; // Cap recovery retries at 3 attempts
const MAX_CONTACT_ATTEMPTS = 3; // Cap communications at 3 contacts
const HARD_DECLINE_STOP = true; // Halt immediately on card_expired / invalid_card
const MAX_PURSUIT_DAYS = 14; // Archive pursuit after 14 days
const REPEATED_FAILURE_STOP_THRESHOLD = 2;// Halt on 2 repeated failures on identical error code- Terminal State: When triggered,
status = 'permanently_failed'andnext_retry_at = null. All subsequent retry or outreach actions are blocked with HTTP 400.
const ESCALATION_POLICY = {
steps: [
{ attempt: 1, tone: 'friendly', channel: 'email', minHoursSinceLastContact: 0 },
{ attempt: 2, tone: 'friendly', channel: 'email', minHoursSinceLastContact: 24 },
{ attempt: 3, tone: 'neutral', channel: 'sms', minHoursSinceLastContact: 24 },
],
maxAttempts: 3,
cooldownHoursBetweenContacts: 24, // Never contact customer more than once every 24 hours
suppressOnHardDecline: true, // Suppress "retry" language for expired/invalid cards
requireCustomerActionLinkOnFinalAttempt: true,
};- Live Cooldown Guard: If outreach is attempted within 24 hours of previous contact, the request is blocked (
HTTP 403,{ blocked: true }), leaving the transaction recoverable while recording amessage_blockedaudit event.
Every state transition records an immutable, structured audit entry:
-
Event Types:
classified|message_generated|message_blocked|retry_attempted|stopped|recovered -
Actors:
ai_agent|stopping_rules_engine|escalation_policy|system -
UI: Rendered in
AuditTrail.jsxwith monospace timestamps, color-coded badges, collapsible JSON metadata, and 1-click Export Audit Log (JSON). -
Frontend: React 18, Vite, Framer Motion, Recharts, Lucide React, Canvas Confetti
-
Typography:
Syne(Display / Hero),Plus Jakarta Sans(UI Chrome),IBM Plex Mono(Tabular Numbers) -
Backend: Node.js, Express.js
-
Database: SQLite (
node:sqlite/DatabaseSyncon Node 22+) -
AI Model: Anthropic Claude (
claude-3-5-sonnet-20241022with structured tool calling)
recoup/
├── backend/
│ ├── agents/
│ │ └── recoveryAgent.js # Claude AI classification & outreach engine
│ ├── db/
│ │ ├── schema.js # SQLite database schema & migrations
│ │ └── seed.js # Seed script with realistic demo transactions
│ ├── routes/
│ │ ├── transactions.js # Transaction CRUD, triage & simulation routes
│ │ └── analytics.js # Analytics aggregation & AI vs baseline metrics
│ ├── utils/
│ │ └── retrySimulator.js # Weighted probability recovery simulator
│ ├── package.json
│ └── server.js # Express application entry point
├── frontend/
│ ├── src/
│ │ ├── api/
│ │ │ └── client.js # Centralized API client
│ │ ├── components/
│ │ │ ├── AnimatedNumber.jsx # Kinetic ease-out counter
│ │ │ ├── DemoGuideModal.jsx # 5-minute judge walkthrough modal
│ │ │ ├── JourneyTimeline.jsx# Multi-stage recovery life-cycle timeline
│ │ │ ├── MessagePreview.jsx # High-fidelity Email & SMS preview
│ │ │ ├── RecoveryChart.jsx # Recharts visualizations
│ │ │ ├── RecoveryFlow.jsx # Kinetic money flow pipeline
│ │ │ ├── RecoveryHero.jsx # Hero command center
│ │ │ ├── SimulateFailuresModal.jsx # Interactive failure ingestion modal
│ │ │ ├── StatusBadge.jsx # Status beacons & strategy chips
│ │ │ └── StrategyMatrix.jsx # AI lift telemetry component
│ │ ├── pages/
│ │ │ ├── Dashboard.jsx # Overview dashboard
│ │ │ ├── Transactions.jsx # Payments master ledger (search/filter/sort)
│ │ │ ├── TransactionDetail.jsx # Transaction journey & retry climax
│ │ │ └── Analytics.jsx # Dedicated analytics & lift benchmark
│ │ ├── utils/
│ │ │ └── formatters.js # Human-friendly terminology dictionary
│ │ ├── App.jsx # Responsive shell & navigation
│ │ ├── index.css # 2026 design system & mobile responsive CSS
│ │ └── main.jsx
│ ├── index.html
│ ├── package.json
│ └── vite.config.js
├── package.json # Root orchestrator package.json
└── README.md
- Node.js: v18.0.0 or higher (Node v20/v22 recommended)
- Anthropic API Key (optional for AI live calls; built-in heuristic fallback operates without it): Get a key here
git clone https://github.com/your-repo/recoup.git
cd recoup# Root and workspace dependencies
npm install
npm install --prefix backend
npm install --prefix frontendCreate a .env file in the backend/ directory:
# backend/.env
PORT=3001
ANTHROPIC_API_KEY=your_anthropic_api_key_here(If no API key is provided, Recoup automatically engages its built-in rule-based adaptive engine).
npm run seedInitializes backend/recoup.db with 20 realistic payment transactions across various failure states.
npm run dev- Backend starts at
http://localhost:3001 - Frontend starts at
http://localhost:5173
Open http://localhost:5173 in your browser.
- Step 1 — Overview (
/): View the headline hero showing total revenue recovered, recovery rate, and the live interactive Money at Risk ➔ Recovered pipeline. - Step 2 — Ingest Failures: Click "Simulate Failures" in the top right. Select
5payments and click Create Failed Payments. - Step 3 — Open Payments (
/transactions): Search for a customer (e.g.Arjun) or filter by "Waiting for Retry". Click on any failed payment. - Step 4 — AI Diagnosis: On the payment detail page, click "Analyze payment". Watch the AI diagnose the root cause, output its reasoning trace, and calculate the win probability.
- Step 5 — Customer Outreach: Click "Create customer message" to preview a personalized recovery Email and SMS notice.
- Step 6 — Retry & Recover: Click "Retry payment". Observe the recovery animation, celebratory burst, status transition, and upward tick of reclaimed revenue.
- Step 7 — Dedicated Analytics (
/analytics): Open the Analytics tab to view the +38.4% AI lift benchmark and failure recovery breakdowns.
Injects simulated failure records into the database.
// Request
{ "count": 5 }
// Response
{
"created": 5,
"transactions": [
{ "id": "uuid-...", "customer_name": "Arjun Sharma", "amount": 4999, "failureReason": "insufficient_funds" }
]
}Retrieves transactions with optional filtering and sorting.
- Query Parameters:
status,failure_category,search,sort(newest,oldest,amount_desc,amount_asc,status),limit,page.
Returns a single transaction with complete retry history and drafted recovery messages.
Invokes the Claude AI agent to classify the payment failure and calculate optimal retry timing.
Generates a context-aware Email / SMS recovery communication draft.
Simulates payment retry based on the recommended strategy and records the outcome in retry_attempts.
Returns aggregate statistics, AI vs baseline comparison, category breakdowns, and strategy win rates.
- Payment attempts and retry outcomes are currently simulated via a weighted empirical model.
- Email and SMS messages are generated and previewed within the UI; live SMTP / SMS gateway delivery is mocked.
- Live Razorpay Webhook Ingestion: Automatically trigger AI classification upon receiving
payment.failedwebhooks from Razorpay. - Automated Retry Daemon: Background cron runner executing retries at
next_retry_atusing Razorpay's recurring payment API. - Multi-Channel Dispatch: Production integrations with SendGrid (Email), Twilio (SMS), and WhatsApp Business API.
- Card Update Self-Serve Portal: Tokenized customer portal allowing buyers with expired cards to securely update payment methods in one tap.
- All API credentials (
ANTHROPIC_API_KEY) are kept exclusively on the server side in environment variables and never exposed to the client. - No real credit card numbers, CVVs, or sensitive PII are stored or transmitted.
- Parameterized SQL queries are used across all database operations to eliminate SQL injection risks.
This project is licensed under the MIT License — see the LICENSE file for details. Built for the Razorpay AI Buildathon 2025.