Documentation

Build with BillAI

Everything you need to integrate intelligent billing into your application — from architecture overview to production launch.

How BillAI Works

BillAI is a microservices-based billing and metering platform that handles the entire billing lifecycle for B2B SaaS companies. At its core, BillAI ingests usage data from your application, aggregates it into billable metrics, applies sophisticated pricing models, generates invoices, and processes payments — all automatically.

Core Architecture

Your App
Usage Ingestion
Redpanda
Event Processor
TigerBeetle
Invoicing
Avalara
Payment
Stripe / Braintree / Razorpay / Adyen

Key Infrastructure

PostgreSQL / TimescaleDB

Transactional data and time-series storage

ClickHouse

Analytics and usage aggregation queries

Redpanda (Kafka-compatible)

Event streaming pipeline

TigerBeetle

Double-entry accounting ledger

Dragonfly (Redis-compatible)

Caching, sessions, and orchestration state

API Quickstart

All API requests require authentication. BillAI supports two authentication methods.

JWT Bearer Token

Internal / Admin APIs

Authorization: Bearer <your-jwt-token>
POST /api/v1/auth/login
Content-Type: application/json

{
  "email": "admin@yourcompany.com",
  "password": "your-password"
}

API Key

External / Customer-Facing APIs

X-API-Key: <your-api-key>
API keys are provisioned per-company through
the Admin Service and are cached in Dragonfly
for fast lookups.

Response Format

Success

{
  "success": true,
  "error": null,
  "payload": [ ... ],
  "input": { ... }
}

Error

{
  "success": false,
  "error": {
    "code": "VAL_001",
    "msg": "Validation error: field 'name' is required"
  },
  "payload": null,
  "input": { ... }
}

Your First API Call

GET /health

Response:
{
  "status": "healthy",
  "dependencies": {
    "database": "ok",
    "cache": "ok",
    "message_broker": "ok"
  }
}

Plan Your Billing Architecture

Before integrating BillAI, plan how your billing model maps to BillAI's core concepts. Walk through each building block.

Billing Models

BillAI supports multiple billing models that can be combined within a single plan.

Usage-Based (Pay-As-You-Go)

Charge customers based on what they consume. Configure a metric + per-unit or tiered price.

Best for: API platforms, cloud infrastructure, AI/ML services

  1. 1.Define a metric (e.g., count of API calls)
  2. 2.Create a per-unit or tiered price linked to the metric
  3. 3.Add the price to a plan
  4. 4.Ingest usage events from your application

Invoicing

BillAI generates invoices automatically at the end of each billing period.

Invoice Lifecycle

Draft ──> Issued ──> Paid
             |
             ├──> Partially Paid
             ├──> Overdue
             ├──> Written Off
             └──> Canceled

What Goes Into an Invoice

  • Line items — Aggregated charges from the subscription period (flat fees + usage charges)
  • Tax calculation — Automatic tax computation via Avalara based on product tax classification and customer location
  • Credits — Any credit memos or adjustments applied
  • Accounting entries — Every invoice posts double-entry records to TigerBeetle

Credit Memos

POST /api/v1/invoicing/credit-memos
Content-Type: application/json
Authorization: Bearer <token>

{
  "invoice_id": "inv_abc",
  "amount": 25.00,
  "reason": "Service disruption credit"
}

Payments

BillAI integrates with multiple payment processors out of the box. Payment processing is abstracted behind a unified interface.

ProviderRegionsCardBank TransferDigital Wallets
StripeGlobal
BraintreeGlobalPayPal
RazorpayIndiaUPI, Netbanking
AdyenGlobal

Spend Controls

Enforce spending limits to prevent unexpected charges and provide cost transparency to your customers.

  • Set budget limits per customer or subscription
  • Automatic suspension when limits are exceeded
  • Automatic resumption when limits are increased or reset
  • Real-time spend tracking via TigerBeetle
  • Alert configuration for approaching limits
POST /api/v1/spend-control/limits
Content-Type: application/json
Authorization: Bearer <token>

{
  "customer_id": "cust_abc",
  "subscription_id": "sub_xyz",
  "monthly_limit": 5000.00,
  "alert_thresholds": [50, 80, 95],
  "action_on_exceed": "suspend"
}

Customer Portal

BillAI includes a built-in customer portal API that you can integrate into your application to give customers self-service access.

  • Profile management — View and update billing profile
  • Subscriptions — View active subscriptions and plan details
  • Invoices — View, download, and track invoice history
  • Usage dashboards — Real-time usage visibility
  • Payment history — View past payments and receipts
  • Credit balances — Check remaining credits
  • Contracts — View active contracts and agreements

The Customer Portal uses a separate JWT authentication realm, keeping customer access isolated from admin operations.

POST /api/v1/portal/auth/login
Content-Type: application/json

{
  "email": "user@globex.com",
  "password": "customer-password"
}

Administration

The BillAI Admin Service provides operational tools for managing your billing platform.

  • Health monitoring — Real-time system health across all services
  • Tenant management — Multi-tenant administration
  • Global search — Search across customers, subscriptions, invoices
  • Orphan event management — View and recover events outside billing periods
  • Audit logging — Complete audit trail with configurable retention
  • User management — Admin user and role management with RBAC
  • Invoice simulation — Run what-if scenarios to preview billing outcomes

Invoice Simulation

POST /api/v1/admin/simulation/invoice
Content-Type: application/json
Authorization: Bearer <token>

{
  "customer_id": "cust_abc",
  "plan_id": "plan_pro",
  "period_start": "2026-02-01T00:00:00Z",
  "period_end": "2026-03-01T00:00:00Z",
  "simulated_events": [
    { "event_type": "api_call", "count": 150000 },
    { "event_type": "storage", "gb": 250 }
  ]
}

Notifications

BillAI sends notifications through multiple channels. Notifications are dispatched asynchronously through AWS SQS and Lambda for reliable delivery.

ChannelProviderUse Cases
EmailAWS SESInvoices, payment receipts, alerts, welcome emails
SMSAWS SNSPayment reminders, spend alerts
PushFirebase Cloud MessagingReal-time usage alerts

Orchestration & Reliability

BillAI uses an internal orchestration engine to coordinate long-running workflows (renewals, invoice generation, payment processing) without tight coupling between services.

How It Works

  1. 1.A service submits a task with a target URL, payload, and scheduled time
  2. 2.The Orchestrator holds the task until it's due
  3. 3.At the scheduled time, the Orchestrator sends an HTTP POST to the target service
  4. 4.The target service processes the work asynchronously and sends a callback
  5. 5.The Orchestrator triggers the next step in the workflow chain

Reliability Features

  • Outbox pattern — Tasks are persisted to the database before dispatch, ensuring no tasks are lost
  • Retry with exponential backoff — Failed tasks are retried automatically
  • Stalled task detection — Alerts are sent when tasks remain unprocessed
  • Dependency chains — Tasks can be chained so downstream work only starts after upstream tasks complete

Integration Checklist

Use this checklist to track your BillAI integration progress.

1

Phase 1: Foundation

  • Set up your company and configure settings
  • Create your customer records
  • Define your product catalog with tax classifications
2

Phase 2: Pricing & Plans

  • Configure metrics for each usage dimension
  • Set up prices with appropriate pricing models
  • Build plans that bundle your prices
  • Define plan transition rules
3

Phase 3: Billing Integration

  • Instrument your application to send usage events
  • Verify event ingestion and idempotency
  • Create test subscriptions
  • Validate invoice generation and tax calculation
4

Phase 4: Payments & Operations

  • Configure your payment processor(s)
  • Set up spend controls and alert thresholds
  • Enable notifications (email, SMS, push)
  • Integrate the customer portal
5

Phase 5: Go Live

  • Run invoice simulations to validate pricing
  • Review audit logs and monitoring dashboards
  • Verify health checks across all services
  • Go live with production billing

Reference

Service Ports

ServicePortPurpose
Auth Service8001Authentication and authorization
Master Data Service8002Products, metrics, plans, pricing
Subscription Service8003Subscription lifecycle management
Invoicing Service8004Invoice generation and management
Admin Service8010Administration and operations
Customer Portal8030Customer-facing self-service API
Orchestration Service8083Workflow coordination
Usage Ingestion8084Usage event ingestion
Payment Service8085Payment processing
Notification Service8090Multi-channel notifications

Error Codes

CodeDescription
AUTH_001Unauthorized — missing or invalid credentials
AUTH_006Insufficient permissions for this action
VAL_001Validation error — check error.msg for details
INT_001Internal server error
REQ_001Endpoint not found

Ready to build?

Start integrating BillAI today. Get from zero to live billing in hours, not months.