Himanshu SharmaCase study

Engineering case study

PeakInsight: an AI-native operating system for travel agencies

A multi-tenant B2B SaaS where LLM workflows, event-driven messaging, usage-based billing, and an automations runtime all run on one domain model. This page covers how it's built, which decisions mattered, and what I'd still fix.

My role
Built independently: product, architecture, backend, frontend, infrastructure
Users
Travel agency owners, sales agents, and ops staff; their customers via WhatsApp and share pages
Stack
Java 21 · Spring Boot 3.4 · MySQL · AWS · React/TS · Flutter
AI
Claude (Haiku 4.5 / Sonnet 4.6) · Sarvam STT · 26 task-specific prompt templates

Overview

The problem and what I built

Agencies run sales across WhatsApp threads, supplier PDFs, phone notes, and spreadsheets. Leads go cold while agents assemble itineraries by hand, and adding LLM features without metering makes costs unpredictable. The goal was one system for the sales and fulfilment loop, with AI built into the steps agents already take and billed like any other commercial SaaS resource.

Role & ownership

  • Designed the domain model, multi-tenancy, and auth.
  • Wrote the Spring Boot backend (3 Maven modules), the React web app, and the AWS setup, including two supporting Lambdas.
  • Designed and implemented every AI workflow: prompts, JSON contracts, grounding, metering.
  • Integrated Meta (WhatsApp, Lead Ads), Gmail/IMAP, Sarvam, Anthropic, and FCM.
  • Ran customer demos with agencies and turned their feedback into product constraints.

Core requirements

  • Agency-scoped tenancy for auth, roles, and data.
  • Lead → trip → package → payment as the core loop.
  • Public surfaces (webhooks, share pages) kept apart from authenticated APIs.
  • AI that is grounded in agency data, reviewable, metered, and async where needed.
  • Integrations that tolerate retries and partial failure.

Major workflows

  1. 01

    Capture

    Leads arrive from Meta Lead Ads webhooks, WhatsApp, Gmail/IMAP, or manual entry; lead-form submissions are scored by Claude.

  2. 02

    Qualify & plan

    A lead becomes a trip. Agents build day-by-day packages by hand, by voice, from a supplier PDF, or through the WhatsApp assistant.

  3. 03

    Propose

    Packages have versions and options, policies, media, and a public share page for the customer.

  4. 04

    Close & collect

    Cost sheets, payment links with UPI QR codes, and AI extraction of payment screenshots into receipts.

  5. 05

    Follow up

    Automations send templates, assign owners, create tasks, and stop when the customer replies.

Product map · one domain, AI inside the workflows
Core sales loop
Leads
Meta Lead Ads, WhatsApp, Gmail/IMAP, manual
→
Trips
Qualified requirement, travellers, dates
→
Packages
Day-by-day itinerary, versions, share page
→
Payments
Cost sheet, payment links, receipts
↓read & write through domain services↑
AI layer
Voice & Chat Assistant
Draft packages, notes, tasks, payments; answer CRM questions
WhatsApp assistant
Package create / modify, hotel Q&A, handoff
PDF scan
Supplier brochure → package
Extraction & scoring
Payment screenshots, lead-form scoring
↓every provider call
Commercial controls
Usage metering
Tokens + audio seconds per call
Credits & subscriptions
Wallets, tariff, tenant lifecycle
Follow-up
Automations engine
Triggers, branches, ACTION / WAIT
Human signals
Customer reply, agent takeover
AI workflows read and write the same agency-scoped records as the manual UI. Every AI call is metered against the agency's credits, and automations react to CRM and messaging events.

Architecture

One backend, one domain, AI as a layer inside it

AI is part of the CRM, not a separate service. Voice, WhatsApp, and PDF workflows read and write the same agency-scoped entities as the manual UI, and all of them go through one metering path.

System architecture
Clients
Web app
React 18 · TypeScript · Vite
Mobile app
Flutter
Chrome extension
Token handoff to CRM session
Public package pages
Customer-facing share links
↓HTTPS · JWT (RSA) · agency-scoped↑
Backend · Java 21 · Spring Boot 3.4 · AWS Elastic Beanstalk
CRM
Leads → trips
Packages
Itineraries, versions, media
Payments
Cost sheets, links, UPI QR
Integrations
WhatsApp, FB leads, Gmail/IMAP
AI workflows
Voice & Chat Assistant
STT, intent, drafts, CRM Q&A
WhatsApp orchestrator
Intent → package / hotel / transport
PDF → package
Staged async scan
Extraction & scoring
Payment screenshots, lead scoring
Usage metering
Operation + hits per provider call
Credits & subscriptions
Wallets, tariff, lifecycle cron
Automations engine
Enrollments, ACTION / WAIT, scheduler
SQS workers
Bounded in-flight pollers
External providers
Anthropic Claude
Haiku 4.5 default · Sonnet 4.6 for heavier stages
Sarvam
Speech-to-text (saaras:v3)
Meta
WhatsApp Cloud API · Lead Ads webhooks
Google
Gmail API · Places · Firebase Cloud Messaging
↓AWS SDK v2↑
AWS
RDS MySQL
JPA / Hibernate
SQS FIFO
WhatsApp inbound · PDF scan
S3
PDFs, media, gallery
Secrets Manager
DB + provider credentials
KMS
Encrypts mail passwords, banking, TOTP secrets
SES
Transactional email
CloudWatch Logs → Lambda → SNS
Alert fan-out (Java 21 Lambda)
Scheduled Lambda
Booking expiry, token cleanup

Technology choices

ChoiceHow it's usedWhy
Spring Boot modular monolithMaven modules: common (auth, entities, AWS clients), crm, mobile. Each app deploys as a WAR.AI workflows, billing, and CRM writes share one database transaction model. For one engineer, module boundaries give separation without distributed-system overhead.
MySQL + JPA/Hibernateddl-auto=none; schema changes are hand-written SQL migrations.Relational domain (agency → users → leads → trips → packages → payments) with strong consistency needs.
SQS FIFOWhatsApp inbound and PDF-scan queues; scheduled pollers with semaphore-bounded workers.Managed queue with per-group ordering, which matches per-conversation processing. Kafka-level throughput isn't needed.
Claude over plain HTTPSpring WebClient to /v1/messages; Haiku 4.5 by default, Sonnet 4.6 for PDF scans and hotel onboarding.Full control over request shape, retries, and usage parsing for metering. Model choice is per workflow, by cost.
Sarvam speech-to-textsaaras:v3, ≤30s per sync clip, parallel multi-clip.Agents dictate in Indian languages and mixed language; Sarvam's models target that.
Elastic BeanstalkWAR bundles with .platform / .ebextensions; Tomcat; JSON logs to CloudWatch.Managed deploys and scaling with little ops work for a solo engineer.
React 18 + Vite + TypeScriptTanStack Query for server state, Redux Toolkit for client state; separate Flutter app.Typed contracts against a large API surface; query caching suits list-heavy CRM screens.

Multi-tenancy

  • The tenant is the agency. RSA-signed access tokens carry agencyId and role.
  • On every request, a servlet filter checks that the session is active, the user exists within that agency and is active, and the agency itself is ACTIVE. Otherwise it returns 401 and revokes refresh and device tokens.
  • Repositories are queried by ID and agencyId (findByIdAndAgencyId), so a guessed ID from another tenant returns nothing.
  • Unauthenticated surfaces (Meta webhooks, share pages, demo booking) live under /public/; webhooks verify HMAC signatures.
  • Subscription expiry suspends the agency, and the same filter then blocks access, so billing and tenancy share one enforcement point.

Trade-off: scoping is by convention in each query, not a framework filter. It's explicit and easy to read, but one missed query leaks data. Hardening this is first on the list below.

AWS infrastructure & operations

  • Compute: Elastic Beanstalk (Tomcat) for the crm and mobile WARs; two Java 21 Lambdas.
  • Data: RDS MySQL; S3 for PDFs, media, and galleries.
  • Messaging: SQS FIFO for WhatsApp inbound and PDF scans; SES for email; SNS for alerts.
  • Secrets: Secrets Manager for DB and provider keys; KMS for field-level encryption of stored credentials.
  • Observability: JSON logs (Logstash encoder) with request, user, and agency IDs in MDC → CloudWatch. Tagged alert lines → Lambda → SNS.
  • Scheduled work: Spring schedulers (subscription lifecycle, automation resume, Gmail sync) and a scheduled Lambda for booking expiry and token cleanup.

Deep dives

Four systems in detail

Each section follows the same order: problem, requirements, workflow, decisions, edge cases, architecture, and trade-offs. Diagrams reflect the production code; product visuals use sample data.

Deep dive 01

In-app Voice & Chat Assistant

Applied AI inside a production workflow: speech or text becomes structured intent, then a draft or a grounded answer. Voice-to-itinerary is the deepest path.

Problem

Travel agents capture work on the move: a spoken package idea, “remind me to call this lead”, “how much did we collect this week?”, a quick note after a WhatsApp call. Mobile CRM forms are slow and free-form speech is ambiguous (“the Munnar one, but add a houseboat night”).

Writing model output straight into packages, payments, or tasks is unsafe. In demos, agencies were clear that AI may draft or answer, but a person confirms before anything is saved.

Requirements

  • One pipeline for voice (POST /voice/process, up to 5 audio clips) and typed chat (POST /chat/process)
  • Two-stage Claude flow: classify the intent, then extract an intent-specific JSON shape
  • Intents: create package or template, save note, add task, record payment, and ASK questions over agency data
  • Resolve spoken or typed references to real leads, trips, destinations, hotels, and sightseeing
  • Ask targeted clarification questions instead of guessing, with a hard cap on rounds
  • Never write from the process endpoint. Mutating intents return a draft that the client confirms through existing APIs
  • ASK answers come from database queries; out-of-scope questions are refused, not improvised
  • Meter every speech-to-text and LLM call for billing
Shared runtime · /voice/process and /chat/process
  1. 1
    Validate & scope

    JWT gives userId, agencyId, and role. Voice: up to 5 clips (1 on follow-ups). Chat: a message, or batch clarification answers.

  2. 2
    Open usage operation

    beginSoft binds a usage operation to the thread; every provider call is recorded as a hit.

  3. 3
    Speech-to-text (voice only)External

    Sarvam saaras:v3. Clips are transcribed in parallel on a 5-thread pool and merged. Chat skips this step.

  4. 4
    Classify intentLLM

    Claude stage 1. Skipped when the mic was opened from a lead or trip screen with a known intent (CONTEXTUAL entry).

  5. 5
    Extract & routeLLM

    Claude stage 2 extracts slots for the intent. ASK first routes the question to one or more domains, then extracts filters per domain.

  6. 6
    Domain executorMySQL

    Package pipeline, note / task / payment draft builders, or ASK answer services read the agency's real data. The model never supplies IDs.

  7. 7
    Respond

    READY_FOR_REVIEW, ANSWERED, NEEDS_CLARIFICATION (with conversation state), UNSUPPORTED, NOT_FOUND, PRECONDITION_FAILED, or TRANSCRIPTION_FAILED.

  8. 8
    Finalize billing

    In finally: per-stage timing log, endSoft() prices the run into credits, MDC cleared.

  9. 9
    User confirms in UI

    Drafts are saved by the existing note, task, payment, and package endpoints, with the same validation and permissions as manual entry.

Deepest path: voice or chat → itinerary draft

Unstructured speech becomes a day-by-day package draft grounded in the agency's own catalog. This is the hardest grounding problem in the assistant: multi-day structure, hotels, sightseeing, destinations, and references to existing packages and templates. The lighter intents reuse the patterns it forced: the model proposes JSON, the backend validates and resolves it, and gaps become questions.

  • Missing days, hotel, or destination → a specific clarification, never a default.
  • Spoken name not in the catalog → mandatory clarification; the model's spelling is never saved as a new entity.
  • Refining an existing package (from chat or a package screen) sends the current draft as the base; modify operations apply onto a copy, and unresolved operations ask before applying.
  • In chat, all open clarification cards can be answered in one request; the backend merges those answers into the known slots without another Claude call.
  • The same matchers and draft builder also serve WhatsApp package requests (deep dive 02).
CREATE_PACKAGE / CREATE_TEMPLATE
  1. 1
    Extract criteriaLLM

    Destinations, days and nights, dates, travellers, stay category, package type, rooms, price, pickup and drop, preferences.

  2. 2
    Load agency corpusMySQL

    VoicePackageCorpusService loads day itineraries from the latest package versions plus destination vocabularies.

  3. 3
    Match entitiesMySQL

    Stay, sightseeing, and country/destination matchers map names to catalog rows.

  4. 4
    Mandatory clarifications

    Backend-owned grouped cards (mirroring the manual create form) replace Claude's per-field questions for core fields not yet known.

  5. 5
    Build draft

    A full day-by-day package draft, or modify operations applied to a copy of the last published version.

  6. 6
    Confirm

    The user reviews and edits, then the existing package create / update APIs save it.

Agency Intelligence

Notes, tasks, payments, and CRM questions share the classify → extract → executor path. ASK answers are computed from agency data, then phrased — the same assistant that drafts itineraries.

Show me every lead stuck in the same stage for 14+ days.

Show me every lead stuck in the same stage for 14+ days.

Ask PeakInsight AI

Key technical decisions

One runtime, many executors

Classification and extraction run once; domain services specialise per intent. The safety model (preview first, backend resolution, capped clarifications) is the same for every intent and for voice and chat, instead of separate bots with separate rules.

The AI path has no write access

VoiceProcessService and ChatProcessService never call a write API. Mutating intents return a draft, so AI-created records pass the same validation and permission checks as manual ones and need no separate audit path.

ASK answers are computed, then phrased

Counts, totals, and lists come from repository queries scoped by agency and role. The model only rewrites a Java-composed draft into natural language, with every number required to appear in the facts it was given. If polishing fails, the Java draft is returned as-is.

Stateless clarification

The server persists nothing between clarification turns. A ChatConversationState object is returned to the client and echoed back. That avoids session storage and expiry logic, and any backend instance can serve the next turn. Rounds are capped at MAX_CLARIFICATION_ROUNDS = 3, shared by spoken and typed replies. ASK's yes/no offers (“show the matching leads?”) don't count against the cap.

Backend owns entity resolution

Claude extracts names and quantities; Java matchers resolve them against the agency's own leads, trips, destinations, properties, and sightseeing. Unresolved entities become clarifications or NOT_FOUND, never invented records.

Contextual vs universal entry

Voice or chat started from a lead, trip, or package screen arrives as CONTEXTUAL with a known intent and entity, which skips classification. The global mic and chat are UNIVERSAL and classify first. Same pipeline, less model work when context exists.

Compact context for follow-up questions

Elliptical chat follow-ups (“same for Abhinav”, “from these”) send a small structured AnalyticsChatContext snapshot of the previous answer instead of the chat history. Prompts stay small and the backend controls what carries over.

Edge cases handled

ScenarioWhat the system does
Hotel, day, or destination missing from a package requestNEEDS_CLARIFICATION with the specific question instead of filling a default.
Spoken name doesn't match the catalogMatcher fails to resolve → backend adds a mandatory clarification; the model's spelling is never saved as a new entity.
Referenced lead or trip doesn't exist, or isn't visible to this userNOT_FOUND with the partial draft, so the user can pick the right record.
User keeps answering vaguelyAfter 3 rounds the flow stops and sends the user to the manual edit screen.
Question outside the supported ASK domainsUNSUPPORTED with a plain message. In a multi-part question, supported parts are answered and the rest are named as unsupported.
Agent asks about a colleague's collectionsRefused: non-admin roles are scoped to their own figures.
Payment recorded before the trip has a usable cost sheetPRECONDITION_FAILED with the reason, before any speech-to-text or Claude spend.
Silence, noise, or a clip that's too shortTRANSCRIPTION_FAILED; no extraction runs.
Long dictationSarvam's sync API accepts ≤30s per clip, so the client sends up to 5 clips, transcribed in parallel and merged into one run.

Architecture

Voice & Chat Assistant · one runtime, many executors
Client
Mic capture
≤ 5 clips of ≤ 30s
Assistant chat
Message or batch clarification answers
Clarification UI
Echoes conversation state
Preview or answer
Edit drafts, then confirm
voice · chat→
Spring Boot · assistant runtime
VoiceProcessService · ChatProcessService
Scope by agency and role; CONTEXTUAL / UNIVERSAL / follow-up
Intent classifier
Claude · stage 1
Slot extraction · ASK routing
Claude · stage 2, per-intent JSON
Intent router → executors
Itinerary pipeline
Corpus, stay / sightseeing matchers, mandatory clarifications
CRM action drafts
Note, task, payment (+ cost-sheet precondition)
ASK answer services
Leads, trips, packages, collections → phrased by Claude
READY_FOR_REVIEW · ANSWERED · NEEDS_CLARIFICATION · UNSUPPORTED · NOT_FOUND · PRECONDITION_FAILED · TRANSCRIPTION_FAILED
Usage operation
beginSoft → hits → endSoft bills credits
Providers
Sarvam STT
Parallel per clip
Claude
Haiku 4.5
MySQL
Agency catalog + CRM
Read-only in the assistant
↓user confirms a draft
Existing write APIs
Create note
Create task
Record payment
Create package / template
Voice and chat share every stage after speech-to-text. Mutating intents only ever return a draft; writes happen when the user confirms, through the same APIs the manual screens use. ASK returns an answer computed from the agency's data.

Trade-offs

  • Preview, then confirm over auto-save. One extra tap, but agencies trust the output and no write path bypasses validation.
  • Many intent executors over one general chat model. More code, but grounding and safety rules are explicit per domain.
  • Several specialised prompts over one large prompt. Each stage has a narrow JSON contract that is easier to debug and cheaper; most stages run on Haiku.
  • Client-held conversation state over server sessions. No session store or TTL to manage; the cost is a larger request payload and no recovery if the client loses it.
  • Itinerary as the deepest path over equal depth for every intent. Notes, tasks, and payments are simpler; ASK covers four domains, with agents and ads still refused.

Validation & evidence

  • Per-stage timing logs ([VOICE_PROCESS_TIMING] stage=…) with the request ID in MDC, queryable in CloudWatch.
  • Each run links request → usage operation → STT and Claude hits → credits, so a bad draft or answer can be traced back to the exact model calls and their cost.
  • Agency demos mainly exposed wrong entity matches and over-eager actions, which led to backend-owned resolution and the draft-only rule.
app.peakinsight.in/studio/new-package
Itinerary StudioLive
0:00
Englishहिन्दीதமிழ்తెలుగుമലയാളംಕನ್ನಡਪੰਜਾਬੀमराठी

Transcript

detected · English

Six days Kerala for a honeymoon couple, mid-October. Start in Kochi, then one night Munnar, Thekkady, a houseboat night in Alleppey, Varkala cliff, and fly out from Trivandrum. Budget around one lakh twenty.

Extracted brief

KochiMunnarThekkadyAlleppeyVarkalaTrivandrum6 daysHoneymoon14–19 Oct2 pax₹1,20,000
Listening

Waiting for the brief…

PDFPublish & send on WhatsApp
Illustrative UI from peakinsight.in · sample data

Deep dive 02

Event-driven WhatsApp sales assistant

Webhook ingestion, queue-based processing, and an LLM orchestrator grounded in each agency's catalog, with escalation to a human.

Problem

Agency deals happen on WhatsApp, but the context (packages, hotels, prices) lives in the CRM. Replying from inside the webhook request ties the response to model latency and Meta's retry behaviour, and duplicate deliveries become duplicate customer messages. Agencies were clear that the assistant should hand off to a person rather than bluff.

Requirements

  • Verify Meta webhook signatures; acknowledge fast
  • Process asynchronously with ordering per customer conversation and bounded concurrency
  • Ignore duplicate deliveries of the same message
  • Route by intent: package questions, new package, modify destinations/stays/transport/sightseeing, escalate
  • Ground replies in the agency's own packages, hotels, and transport
  • Respect WhatsApp's 24-hour customer-service window and template rules
  • Notify a human on low confidence; stop drip automations when the customer replies
Inbound WhatsApp message
  1. 1
    WebhookExternal

    POST /public/webhooks/whatsapp. HMAC-SHA256 of the raw body checked against X-Hub-Signature-256 (constant-time compare).

  2. 2
    EnqueueSQS

    Raw payload sent to an SQS FIFO queue. MessageGroupId = our number + customer number; dedup ID = SHA-256 of the payload.

  3. 3
    Poll with backpressureSQS

    Scheduled long-poll sizes each receive batch to free slots in a semaphore (default 5) and dispatches to a thread pool.

  4. 4
    Persist inboundMySQL

    Skip if provider_message_id (wamid) already exists; otherwise save the message and cancel the lead's waiting automations.

  5. 5
    Classify intentLLM

    Claude returns intent_type, needs_clarification, needs_human, and a package query.

  6. 6
    Route to a flowLLM

    Package create/modify reuses the voice package pipeline through a bridge service. Hotel, transport, and Q&A stages each have their own prompt and context JSON.

  7. 7
    Persist, publish, reply

    Updated packages are saved and a share link is added to the reply. Messaging-window rules decide between a session message and a template.

  8. 8
    Bill or hand off

    Usage closes against the conversation. needs_human or confidence < 0.4 → handoff notification (in-app + FCM push).

Key technical decisions

FIFO groups per conversation

SQS FIFO won't deliver the next message in a group while one is in flight, so each customer's messages are processed in order and one at a time, without application-level locks. Status webhooks are grouped by wamid instead, keeping one message's lifecycle events ordered.

At-least-once, with duplicate suppression

Three layers: FIFO content-based dedup (5-minute window), sequential processing per group, and an existence check on provider_message_id before insert. I don't claim exactly-once delivery.

Orchestration in backend code, not tool-calling

The model classifies and drafts; Java code decides which flow runs, which data goes into each prompt, and what gets persisted. Side effects stay explicit and reviewable.

Reuse the voice package pipeline

WhatsAppVoicePackageBridgeService sends package create/modify requests through the same matchers and draft builder as voice. One grounding implementation serves both channels.

Edge cases handled

ScenarioWhat the system does
Meta retries the same webhookIdentical payload → same SQS dedup ID within 5 minutes; after that, the wamid existence check drops it.
Burst of messages from one customerSame FIFO group → processed strictly in order; context from earlier messages is in the DB before later ones run.
Workers saturatedReceive batch shrinks to free semaphore slots; if dispatch is refused, the message stays in flight and is redelivered after the visibility timeout.
Processing throwsMessage is not deleted, so SQS redelivers it after the visibility timeout.
Low-confidence or unsupported requestneeds_human or confidence < 0.4 → customer told a person will follow up; agent notified in-app and via push.
Outside the 24h service windowWhatsAppMessagingWindowService switches to SESSION, TEMPLATE_ONLY_FREE (72h free-entry window), or TEMPLATE_ONLY_PAID.
Customer replies mid-dripWaiting automation enrollments for that lead are cancelled with reason CUSTOMER_REPLIED.

Architecture

WhatsApp assistant · event path
Meta
Cloud API webhook
POST→
Webhook controller
HMAC-SHA256 check → enqueue → 200
→
SQS FIFO
Group: our line + customer · dedup: SHA-256(payload)
→
Poller + worker pool
Batch = free semaphore slots (5)
↓one message at a time per conversation
Ingest
Persist inbound
Skip if wamid already stored
Cancel waiting automations
Reason: CUSTOMER_REPLIED
Messaging window
Session · template-only free · template-only paid
Conversation orchestrator
Intent stage
intent_type · needs_clarification · needs_human
Package create / modify
Reuses voice pipeline
Hotel & transport
Selection against catalog
Package / hotel Q&A
Grounded context JSON
Persist & publish
Package + share link
Response polish
Final customer text
Handoff
needs_human or confidence < 0.4 → FCM
↓reply + usage
WhatsApp Graph API
Outbound message
Usage operation
Billed against the conversation
CloudWatch
Per-stage input/output logs by conversation ID
The webhook does no AI work: it verifies, enqueues, and returns. Ordering comes from FIFO message groups (one per conversation), and concurrency is capped by a semaphore.

Trade-offs

  • Async replies via SQS over replying inside the webhook. Adds a few seconds of latency, but model slowness can't cause Meta timeouts and retries.
  • Multi-stage orchestrator over a thin chat bot. Much more code (the orchestrator alone is ~3,000 lines), but every customer-visible action is deterministic and logged.
  • Escalate on low confidence over always answering. Fewer automated replies, more agency trust.

Validation & evidence

  • Failures are logged with [CRITICAL_ALERT] / [BUSINESS_ALERT] tags. A CloudWatch Logs subscription feeds a separate Java 21 Lambda that publishes them to SNS, so alerts reach me without watching dashboards.
  • Every LLM stage logs its input context and output per conversation ID, so any reply can be reconstructed.
  • Agency demos and replays focused on duplicate suppression and handoff behaviour.
app.peakinsight.in

Ritu Malhotra

WhatsApp · AI converting

Live
Illustrative UI · sample data

Deep dive 03

AI usage metering, credits & subscriptions

SaaS economics in backend code: per-call metering, pricing, wallets, and tenant lifecycle.

Problem

LLM and speech costs scale with usage, not seats. Without per-tenant metering, one busy agency can erase the margin, and nobody can explain a bill. Usage also comes from places with no logged-in user, such as WhatsApp webhooks and background jobs, and still needs an owner.

Requirements

  • Record every successful provider call (Claude tokens, Sarvam audio seconds) under one parent operation per workflow run
  • Convert usage to credits using a configurable tariff (per-model token rates, STT rate, FX, GST)
  • Per-user wallets with a monthly expirable allotment and non-expiring top-ups
  • Billing failures must never break the user's workflow
  • Subscription lifecycle: active → past due with grace → expired → tenant suspended
  • Idempotent finalize and idempotent admin grants and transfers
One AI workflow run
  1. 1
    beginSoft(operation)MySQL

    Creates an ai_usage_operations row (REQUIRES_NEW tx) and binds its ID to the worker thread.

  2. 2
    Provider callsLLM

    Each successful Claude/Sarvam response is recorded as a hit: input/output tokens or billable duration. Cache hits record nothing.

  3. 3
    endSoft()

    Unbinds the thread and finalizes credits in a separate transaction; errors are logged, never thrown.

  4. 4
    Price

    Σ hits × tariff (Haiku vs Sonnet rates; STT hours × INR/hr ÷ FX) × GST → USD → ceil(USD ÷ credit_usd).

  5. 5
    Debit walletMySQL

    Expirable first, then non-expiring, then overdraw on expirable. Before/after deltas stored on the operation.

  6. 6
    Daily lifecycle job

    00:15 IST: period end → PAST_DUE with 3 grace days → EXPIRED → agency SUSPENDED; monthly credit drip per seat; history rows.

  7. 7
    Every request

    JWT filter rejects users of non-ACTIVE agencies and revokes their refresh and device tokens.

Key technical decisions

Meter at the call site, bill at the workflow boundary

A ThreadLocal-bound operation ID lets deep client code record hits without passing IDs through every layer. Billing happens once per workflow, so a voice run or WhatsApp turn is one line item.

Usage writes in REQUIRES_NEW transactions

Voice requests hold a long transaction. Writing usage in its own transaction avoids lock waits on an uncommitted parent row, and a metering failure can't roll back the user's work.

Credits instead of raw cost pass-through

Agencies see one unit across Claude models and STT. Tariff rows (rates, FX, GST) live in the database and can change without a deploy.

Attribute system usage to the agency owner

Webhook and async paths have no acting user, so usage falls back to the agency OWNER and every credit is attributable to a person in reports.

Edge cases handled

ScenarioWhat the system does
finalize called twice for one operationNo-op if credits_used is already set.
Wallet runs out mid-workflowRun completes; the overdraw lands on the expirable pool, which can go negative. This is a deliberate policy: never cut off a reply mid-conversation.
Usage from a webhook with no userAttributed to the agency owner; logged as a business alert if no owner exists.
Tariff row missingCritical alert, no debit. Usage rows remain, so the run can be re-billed later.
Subscription period endsPAST_DUE with a 3-day grace countdown written to history each day; then EXPIRED and the agency is SUSPENDED.
Suspended tenant still has a valid tokenJWT filter checks agency status on every request; returns 401 and revokes refresh/device tokens.
Retried credit grant or transferUnique idempotency_key on credit transactions; transfers check source balance first.

Architecture

Metering, credits & subscriptions · data model
Metering
ai_usage_operations
One per workflow run · model · user · credits_used · wallet deltas
1 ─ n
ai_usage_hits
Per successful call · input/output tokens or audio seconds
Pricing & wallets
credit_tariff
Haiku / Sonnet $/Mtok · STT ₹/hr · FX · GST · $ per credit
credit_balance
Unique per user · expirable + non-expiring pools
credit_transaction
Grants & transfers · unique idempotency_key
Subscriptions
agency_subscription
One per agency · tier · period end · grace days
agency_subscription_history
PAST_DUE · GRACE_TICK · EXPIRED events
Daily job · 00:15 IST
Lifecycle transitions + monthly credit drip
↓enforcement
ACTIVE
Normal access
period ends→
PAST_DUE
3-day grace countdown
grace over→
EXPIRED
Agency → SUSPENDED
next request→
JWT filter
401 + revoke refresh & device tokens
Usage is recorded per provider call, priced once per workflow run, and debited from the attributed user's wallet. Subscription state is enforced on every request by the JWT filter.

Trade-offs

  • Bill after the run, allow overdraw over blocking before each call. A customer conversation is never cut off mid-reply. The cost is bounded by subscription status, not by balance.
  • Store pricing inputs in the database over hard-coded rates. Rates, FX, and GST change; more rows to manage, but no deploy needed.
  • One wallet per user over one pool per agency. Supports per-agent allocation and reporting; transfers add complexity.

Validation & evidence

  • Each operation stores credits_used plus wallet deltas and post-debit balances, so a balance can be reconciled from usage history.
  • Subscription transitions write history events (PAST_DUE, GRACE_TICK, EXPIRED) for support and audit.
app.peakinsight.in

AI credits

Neha · this billing period

Monthly (expirable)

1,240

Top-up (non-expiring)

500

  • Voice Command

    −1
  • Voice itinerary

    −6
  • PDF Scan

    −10
  • Vendor Onboarding

    −15
Illustrative UI · sample data

Deep dive 04

Automations runtime

Workflow engineering: a state machine, delayed resumption, audit records, and exits driven by humans.

Problem

Agencies want consistent follow-up when leads arrive or change status: a WhatsApp template, an email, an owner assignment, a task. A visual builder is the easy part. The runtime has to know when to wait, when to stop, and what happened. In discovery calls the clearest requirement was “don't keep messaging after the customer has replied.”

Requirements

  • Triggers: lead imported, lead status changed; conditional branches
  • At most one open (active or waiting) journey per lead
  • ACTION and WAIT steps; resume after the wait without holding threads
  • Actions: WhatsApp template, email template, assign owner (round-robin), change status, create task, notify agent
  • Per-step audit trail
  • Exit when the customer replies; skip automated sends when an agent has taken over
Enrollment lifecycle
  1. 1
    CRM event

    Lead import or status change calls AutomationEnrollmentService.

  2. 2
    EnrollMySQL

    Skip if the lead already has an ACTIVE/WAITING enrollment. Match enabled workflows for the agency and trigger; choose a branch.

  3. 3
    Execute

    Run up to 20 steps per pass. ACTION → executor → AutomationStepRun (DONE / SKIPPED / FAILED) → advance.

  4. 4
    WAIT

    Check for a customer reply first; otherwise status = WAITING, next_run_at = now + duration (default 24h).

  5. 5
    Resume

    Scheduler every 30s loads due WAITING enrollments, re-checks for replies, advances past the WAIT, continues.

  6. 6
    Exit

    COMPLETED at end of branch; CANCELLED with a reason (CUSTOMER_REPLIED, MANUAL, …).

Key technical decisions

The enrollment row is the state machine

Status, current step, and next_run_at live on one row. Waiting costs nothing at runtime, and a restart loses no state: the scheduler picks up whatever is due.

Human signals come from the messaging data

customerReplied looks for inbound WhatsApp after the latest outbound. agentTakeover looks for outbound WhatsApp or email after enrollment that this enrollment's own step runs didn't produce, by comparing message IDs stored in step results.

Step runs as the audit log

Every executed action writes a row with status, skip reason, error, and result JSON. An operator can see what was sent, what was skipped, and why.

Round-robin under a row lock

Owner assignment uses a per-(agency, workflow, step) cursor read with PESSIMISTIC_WRITE. A concurrent first-time insert is caught via the unique constraint and re-read under the lock.

Edge cases handled

ScenarioWhat the system does
Lead already in a journeyNew enrollment skipped and logged.
Customer replies while waitingCancelled with CUSTOMER_REPLIED, both on the inbound path and when the wait expires.
Agent messages the customer manuallyLater WhatsApp/email steps are recorded as SKIPPED with AGENT_TAKEOVER.
Lead deleted mid-journeyEnrollment cancelled (MANUAL).
Misconfigured branch loopsMAX_STEPS_PER_PASS = 20 bounds a single pass.
Two leads assigned at the same instantLocked cursor gives each one the next agent in turn; no duplicate picks.

Architecture

Automations · model and enrollment state machine
Definition
automation_workflow
Agency · trigger: LEAD_IMPORTED / LEAD_STATUS_CHANGED
automation_branch
Conditions on the lead
automation_step
ACTION (template, email, assign, status, task, notify) or WAIT (hours)
automation_round_robin_cursor
Per workflow + step · PESSIMISTIC_WRITE
Runtime
automation_enrollment
Lead · branch · current step · status · next_run_at · cancel reason
automation_step_run
DONE / SKIPPED / FAILED · skip reason · result JSON (message IDs)
Scheduler · every 30s
Due WAITING enrollments
Conversation signals
Customer replied · agent takeover
↓enrollment states
CRM event
Enroll if none open
→
ACTIVE
Run ACTION steps (≤ 20 per pass)
WAIT →← due
WAITING
next_run_at = now + hours
→
COMPLETED
End of branch
CANCELLED
CUSTOMER_REPLIED · MANUAL
A workflow defines the steps; an enrollment tracks one lead's progress through them. Every executed action leaves a step-run record.

Trade-offs

  • Polling scheduler on a DB column over a delay queue per wait. Simple, durable, inspectable with SQL; resolution is ~30s, which is fine for hour-scale waits.
  • Conversation-aware exits over pure timer drips. Fewer messages sent, but the engine now depends on the messaging tables.

Validation & evidence

  • An enrollment's history (trigger → step runs → skips → cancel reason) can be reconstructed from the database alone.
  • Agency demos and discovery calls drove the reply-cancel and agent-takeover rules.
app.peakinsight.in
  1. TriggerLead imported
  2. BranchDestination is domestic
  3. ActionAssign owner · round-robin (Neha, Arjun)
  4. ActionSend WhatsApp template · intro + brochure
  5. Wait24 hours · exits if the customer replies
  6. ActionCreate task · follow-up call

Enrollment advancing…

Illustrative UI · sample data

Supporting capabilities

The rest of the product

Not covered in depth, but part of the same system and data model.

PDF → package

Supplier brochure → S3 → SQS FIFO → staged Claude (Sonnet) pipeline: extract itinerary, enrich media, create package, add days, finalize. Each stage reports progress and records failures.

Lead capture

Meta Lead Ads webhook (signature-verified, de-duplicated per agency), Gmail API OAuth sync every 2 minutes, IMAP/SMTP for other providers.

Lead scoring

Claude Haiku scores incoming lead-form submissions with a dedicated prompt template.

Payments

Cost sheets, payment-request links, UPI QR generation, and Claude extraction of payment screenshots.

Package authoring

Day-by-day itineraries, versions/options, policies, media galleries on S3, public share pages.

Catalogs

Destinations, sightseeing, properties, vendors, transport. These ground every AI flow.

Notifications

Firebase Cloud Messaging for handoffs, bookings, and automation alerts.

Security

RSA-signed JWTs with refresh sessions, TOTP MFA, KMS-encrypted mail passwords, banking details, and TOTP secrets, Secrets Manager for all credentials.

Product development

How customer feedback shaped the engineering

I ran product demos and ongoing conversations with travel agencies throughout development. The feedback below led directly to design constraints. Agency counts and commercial figures are left out until I can verify and publish them.

What agencies told meWhat it changed in the system
“We sell on WhatsApp, not through web forms.”WhatsApp Cloud API as a first-class channel on the agency's own number, with an AI assistant and full CRM context.
“Don't let AI change our data without asking.”The voice & chat assistant produces drafts only; existing APIs write after the agent confirms.
“Answers have to come from our packages and our hotels.”Backend entity resolution against each agency's catalog; the model never supplies IDs.
“A person must be able to step in.”Low-confidence handoff with push notifications; automations skip sends after an agent takes over.
“Stop follow-ups once the customer replies.”Reply-driven cancellation of automation enrollments.
“Supplier inventory arrives as PDFs.”The staged PDF → package pipeline.

Evolving the system

What I'd improve next

Cross-cutting improvements, roughly in priority order. Most come from the system being built quickly by one person and are cheap to fix now.

  1. 01Adopt Flyway so schema migrations are versioned and applied automatically instead of run by hand.
  2. 02Enforce tenant scoping at the framework level (Hibernate filter or a scoped repository base) and add tests that fail on unscoped queries. Today isolation relies on every query including agencyId.
  3. 03Build a test suite around the riskiest paths: concurrent billing, webhook redelivery, and automation resume. Only a small set of unit tests exists today.
  4. 04Add a DLQ and idempotent-send records for every external side effect (WhatsApp, email), tracked as one reliability workstream.
  5. 05Publish latency and reliability numbers once there's enough production volume to make them meaningful.

Want to go deeper?

I'm happy to walk through the code, the data model, or any decision on this page. Himanshu Sharma, Senior Software Engineer & Product Builder.