Prompt
How do I build usage-based invoicing for a software product?
Latest observation
Building usage-based invoicing usually means designing 4 layers:
- Metering — measure what the customer consumed
- Rating — convert usage into money
- Billing — generate invoices, apply taxes/discounts, handle proration
- Payments + reconciliation — collect payment and match it to the invoice
Here’s a practical blueprint.
1) Define what you’re charging for
First decide the billable metric clearly.
Examples:
- API requests
- GB stored
- compute minutes
- active seats
- messages sent
- events processed
For each metric, define:
- Unit: request, GB-month, minute, seat-month
- When it is counted: at event time, daily average, monthly peak, etc.
- Rounding rules: per second? per MB? minimum billable unit?
- Who it applies to: tenant, workspace, user, project
- Billing period: monthly, weekly, pay-as-you-go, prepaid credits
Be extremely precise. Most invoicing bugs come from ambiguous definitions.
2) Design the metering pipeline
You need a reliable way to capture usage events.
A good usage event usually contains:
event_id(unique for idempotency)customer_idsubscription_idoraccount_idmetric_namequantitytimestamp- optional dimensions: region, plan, API endpoint, product tier
- metadata for auditing
Example:
{
"event_id": "evt_123",
"customer_id": "cus_456",
"metric_name": "api_request",
"quantity": 1,
"timestamp": "2026-10-15T10:00:00Z",
"metadata": {
"endpoint": "/v1/inference",
"region": "us-east-1"
}
}
Important metering principles
- Idempotency: duplicate events should not double-bill
- Immutability: never overwrite raw usage; append corrections
- Late-arriving events: allow events to arrive after the usage period
- Auditability: store raw events or at least a verifiable aggregate trail
Common architecture
- Product emits events
- Events go to a queue/stream
- A meter aggregates usage
- Aggregates are stored by customer + period + metric
- Billing jobs read the aggregates at invoice time
If volume is high, avoid calculating invoices directly from raw events at billing time.
3) Build a pricing engine
This is where usage becomes charges.
Pricing models
Flat rate per unit
$0.002 per API call
Tiered pricing
- First 1M requests: free
- Next 9M: $0.001/request
- Beyond 10M: $0.0005/request
Volume pricing
- Entire month billed at a rate based on total volume
Graduated pricing
- Each tier is charged separately
Minimums / commitment
$500/month minimum- or
$10,000 committed spend with overages
Prepaid credits
- Customer buys credits
- Usage decrements balance until exhausted
You need a deterministic function:
charge = f(usage, price plan, currency, discounts, taxes)
Keep pricing versioned
Pricing changes over time, so store:
- plan version
- effective dates
- currency
- billing rules
Never rely on “current price” if you’re invoicing past usage.
4) Create an invoice model
A good invoice system usually has:
Entities
- Customer
- Subscription / contract
- Usage event
- Usage aggregate
- Invoice
- Invoice line item
- Payment
- Adjustment / credit note
Invoice line items should include:
- description
- metric
- quantity
- unit price
- amount
- tax
- discount
- period covered
Example line item:
- API requests — 2,450,000 × $0.001 = $2,450.00
Suggested invoice states
- draft
- open / issued
- paid
- partially paid
- overdue
- void
- credited
5) Decide when to invoice
Common patterns:
A. End-of-period invoicing
Bill monthly after the cycle closes.
- simpler
- common for SaaS
- usage accrued during the month, invoice on the 1st
B. Threshold invoicing
Issue invoice once spend exceeds a threshold.
- useful for high usage or credit risk
- can improve cash flow
C. Prepaid with true-up
Customer prepays an estimate, then you reconcile later.
- common in enterprise contracts
D. Real-time or near-real-time billing
Less common for invoices, more common for wallets/credits.
For most products, monthly billing with optional mid-cycle threshold alerts is the best starting point.
6) Handle adjustments and corrections
Usage systems always need corrections:
- duplicate events
- deleted resources
- billing disputes
- backfilled usage
- price plan changes
- refunds
Use:
- credit notes
- negative line items
- usage corrections
- invoice reissue only if legally acceptable in your jurisdiction
Keep raw usage separate from billed totals.
7) Tax, currency, and compliance
If you charge real money, don’t ignore this.
Tax
- determine nexus/VAT/GST requirements
- collect customer tax IDs when needed
- calculate tax based on jurisdiction and product type
- store tax breakdown on invoices
Currency
- invoice in a single currency per invoice
- define FX conversion policy if usage recorded in one currency but billed in another
- round carefully to avoid cent mismatches
Compliance
- invoice numbering rules
- retention requirements
- audit logs
- accounting exports
8) Payment collection
Once invoices are created:
- send invoice by email or portal
- charge saved card automatically
- support ACH/wire for enterprise
- retry failed charges with dunning logic
Dunning basics
- notify on failed payment
- retry intelligently
- suspend service only after grace period
- track collections status
9) Reporting and customer visibility
Customers should be able to see:
- current usage
- estimated charges
- historical invoices
- usage breakdown by metric/date/region/project
This reduces disputes and support load.
A live usage dashboard is often as important as the invoice itself.
10) Implementation approach
If you’re early-stage
Use a billing platform:
- Stripe Billing / Metering
- Chargebee
- Recurly
- Zuora
- Paddle (depending on model)
This gets you:
- invoicing
- payment processing
- tax handling
- webhooks
- credits/discounts
You still need to emit clean usage events.
If you build it yourself
Build these components:
- Usage event API
- Event store
- Aggregation job
- Pricing engine
- Invoice generator
- Payment processor integration
- Admin tools
- Customer portal
- Audit/reporting layer
Self-building is worth it only if your pricing is highly custom or scale/compliance demands it.
11) A simple reference flow
- User uses product
- Product emits usage events
- Events are validated and deduplicated
- Aggregator totals usage by customer and billing period
- Pricing engine computes charges
- Invoice is created at period end
- Tax/discounts are applied
- Invoice is finalized and sent
- Payment is collected
- Usage and invoice data are stored for audit
12) Common pitfalls
- Double-counting due to retries
- Changing prices without versioning
- No visibility into usage before invoice
- Mixing raw events and invoices
- Relying on eventual-consistency without reconciliation
- Billing on the wrong timezone
- Not handling free tiers properly
- Rounding inconsistencies across services
- No dispute-resolution process
- Missing audit trail
13) Recommended MVP
If you want to ship quickly, start with:
- one billable metric
- monthly billing
- one currency
- one pricing plan
- usage events with idempotency keys
- aggregate daily and monthly
- invoice at cycle end
- card payments via Stripe
- customer usage dashboard
- admin override tools
That’s enough to prove the model.
14) Data model sketch
Usage event
- id
- account_id
- metric
- quantity
- occurred_at
- ingested_at
- source
- metadata
- dedupe_key
Usage aggregate
- account_id
- metric
- period_start
- period_end
- total_quantity
Invoice
- id
- account_id
- billing_period_start
- billing_period_end
- subtotal
- tax
- total
- status
- issued_at
- due_at
Invoice line item
- invoice_id
- metric
- description
- quantity
- unit_price
- amount
- tax_amount
15) Best practice summary
- Make metering accurate and idempotent
- Version pricing
- Separate raw usage from invoiced usage
- Show customers their usage before billing
- Build auditability and correction workflows
- Use an existing billing platform unless you have a strong reason not to
If you want, I can also provide:
- a database schema for usage-based invoicing,
- a Stripe Billing implementation plan, or
- a sample architecture diagram and API design.