Skip to main content

Billing Architecture

Qarion's billing system provides per-tenant usage tracking, hourly aggregation, automated billing cycle management, and invoice generation for multi-instance deployments.

System Flow

Key Components

BillingUsageMiddleware

ASGI middleware that intercepts every API request and records a raw usage event:

  • Extracts instance ID from the request routing context
  • Records the meter key (e.g., api_calls), timestamp, and quantity
  • Non-blocking — usage events are written asynchronously

Aggregation Service

The BillingAggregationService runs hourly via the run_billing_aggregation arq task:

  1. Queries raw usage records since the last aggregation
  2. Groups by instance + meter + date
  3. Upserts daily summaries (idempotent)

Billing Cycle Service

The BillingCycleService runs daily via run_billing_cycle:

  1. Identifies billing periods due for closure
  2. Calculates total usage per meter
  3. Applies pricing plan rules (flat-rate + metered components)
  4. Generates draft invoices with itemized line items
  5. Applies credit balances

Pricing Engine

Plans support two component types:

TypeResolution
Flat-rateFixed fee per billing period
MeteredPer-unit with optional tiered buckets (e.g., first 10K free, then $0.001/call)

Invoice Lifecycle

Draft → Finalized → Sent → Paid
→ Overdue → Void

Data Model

ModelDescription
BillingPlanPricing plan with components
BillingSubscriptionTenant-to-plan binding
BillingUsageRecordRaw and aggregated usage data
BillingInvoiceGenerated invoice with line items

Key Files

FilePurpose
app/middleware/billing_usage_middleware.pyPer-request usage metering
app/services/billing_aggregation_service.pyHourly usage roll-up
app/services/billing_cycle_service.pyCycle close and invoice generation
app/services/billing_pricing_service.pyPricing plan resolution
app/services/billing_render_service.pyInvoice HTML rendering