During the Seed Phase of the Guidewire DevTrials, our team introduced Paymigo, an AI-powered parametric insurance platform. Our mission is to build a structured, automated safety net for urban food delivery partners, protecting them from sudden income loss caused by external disruptions like severe floods, hazardous pollution, or sudden government strikes.
Now, in the Scale Phase, the challenge is moving from a conceptual prototype to a robust, production-ready system capable of handling real-time data ingestion, complex ML inference, and instant financial disbursements.
To achieve this, we executed a major architectural pivot: migrating from a monolithic React/Django setup to a high-performance Next.js 14 and FastAPI Monorepo. Here is a comprehensive look at how we engineered our scalable folder structure and the automated workflows powering Paymigo.
🏗️ 1. The Monorepo Architecture: Why We Pivoted
Handling real-time API polling alongside heavy ML computations requires strict separation of concerns without sacrificing developer velocity. We adopted Turborepo to manage our Next.js frontend and Python FastAPI backend within a single repository.
Why this stack?
Next.js 14 (App Router): Allows us to use React Server Components (RSCs) to securely fetch policy data directly from our database, drastically reducing client-side JavaScript.
FastAPI: Python is the undisputed king of ML. FastAPI provides asynchronous, high-performance API endpoints with built-in Pydantic validation, ensuring the data passed from our Next.js backend is strictly typed before it ever touches our ML models.
Prisma ORM: Acts as our single source of truth for the database schema, residing in a shared packages folder.
The Codebase Structure
paymigo/
├── apps/
│ ├── web/ ← Next.js 14 — Worker PWA + Admin Portal
│ │ ├── app/
│ │ │ ├── (worker)/ ← Worker PWA: Live disruption widget, UPI payouts
│ │ │ ├── (insurer)/ ← Admin Portal: Analytics, fraud queue, LSTM forecasts
│ │ │ └── api/ ← Next.js API Routes: Auth, Razorpay Webhooks
│ │ ├── lib/ ← Core logic: Payout calculations, ML HTTP clients
│ │ └── i18n/
│ │ ├── en.json, hi.json, ta.json ← Native localization for seamless regional onboarding
│ │
│ └── ml-service/ ← FastAPI Python — Core AI/ML Engine
│ ├── api/ ← Endpoints: /premium (XGBoost), /fraud (Isolation Forest)
│ ├── models/ ← Trained artifacts (.pkl, .h5) loaded into memory on startup
│ ├── tasks/ ← API polling (Bull Queue) & Monday 6 AM IST cron renewals
│ └── data/ ← Synthetic worker data & historical IMD rainfall datasets
│
├── packages/
│ └── database/ ← Prisma ORM (schema.prisma)
└── turbo.json ← Turborepo build caching & pipeline configurations
⚙️ 2. Deconstructing the Core System Workflows
Building an "automated" insurance platform means aggressively eliminating manual bottlenecks. We designed three primary workflows that allow the system to operate with near-zero human intervention.
Workflow A: Dynamic Onboarding & AI Premium Generation
Traditional insurance relies on static, historical tables. Paymigo calculates premiums dynamically based on the delivery partner's real-time operational risk.
Multilingual Registration: The worker accesses the Next.js PWA (/app/(auth)/register). Because our target demographic includes diverse regional workers, the UI is fully localized (English, Hindi, Tamil) using Next.js middleware and i18n routing.
Data Ingestion: The worker inputs their vehicle type, primary delivery zone (pincode), and historical daily working hours. This payload is passed securely to the FastAPI service(POST /premium/calculate).
AI Pricing Matrix: First, a K-Means clustering model maps the worker's pincode to a specific historical risk cluster (e.g., "High Flood Risk" vs. "Stable Zone").
- Next, an XGBoost regressor takes the worker's data, the zone cluster, and real-time seasonal data to generate a personalized, dynamic premium (e.g., adjusting from a baseline ₹80/week to ₹95/week based on impending monsoon forecasts).
Policy Activation: The worker pays the initial premium via a Razorpay gateway. Prisma creates the active policy record, and a portion of the premium is instantly allocated to an "Emergency Wallet" for catastrophic events.
Workflow B: The Parametric Trigger & Auto-Payout Loop
This workflow completely replaces the manual claims process. If the environment stops the worker from earning, the system pays them automatically.
Background Polling: Inside our Next.js backend, a Bull Queue job runs every 10–15 minutes, pinging external Weather and Air Quality APIs for the worker's registered zones.
Trigger Classification: If an API reports an anomaly (e.g., Rainfall > 50mm/hr or AQI > 400), the raw data is sent to our FastAPI Random Forest Trigger Classifier (POST /trigger/classify). The model validates if the conditions are severe enough to halt city movement.
The Payout Formula: Once validated, Next.js calculates the exact compensation using a deterministic formula in payout-calculator.ts:
Payout = (Base Hourly Rate) × (Lost Hours) × (ZoneRiskMultiplier) × (Worker Loyalty Tier)
Instant UPI Disbursement: A webhook fires to Razorpay Route, instantly transferring the calculated compensation directly to the worker's verified UPI ID. The worker receives an SMS and a digital receipt in their /(worker)/payouts dashboard.
Workflow C: Fraud Defense & Admin Oversight
To ensure the long-term financial viability of the platform and protect the balanced insurance pool, we engineered a rigorous, multi-layered fraud defense system.
Anomaly Detection: Before any payout (automated or manually requested) is finalized, the claim payload is routed to POST /fraud/check.
Dual-Model Verification:
- Isolation Forest: Analyzes the frequency and timing of the claim against the worker's historical behavior to flag statistical anomalies.
- GPS Random Forest: Cross-references the worker's simulated delivery telemetry. Did the worker actually spend time in the affected zone during the disruption window?
Action Routing:
- Clear: The claim executes the UPI payout automatically.
- Flagged: The system halts the transaction and pushes it to the Admin Dashboard under the "Fraud Review Queue."
Predictive Admin Oversight: In the Admin portal, operators do not just review flagged claims. They utilize a custom LSTM 7-day forecasting dashboard (/forecast/{zone}). By predicting severe weather or disruptions a week in advance, admins can ensure the platform maintains enough liquidity for upcoming automated mass-payouts.
🚀 Looking Ahead to the Finals:
Scaling Paymigo has been a massive technical and operational challenge. By coupling the frontend speed of Next.js 14 with the machine-learning horsepower of FastAPI, we have built an InsurTech pipeline capable of processing environmental API data, scoring complex risks, and initiating localized UPI payments seamlessly.
As we polish the PWA interface and lock down our Razorpay webhooks for the final Guidewire DevTrials submission, we are more confident than ever that AI-driven parametric insurance is the future of the gig economy.
Top comments (0)