Prompt
Need API billing and usage tracking
Latest observation
Oct 23, 2026
OpenAI APIWeb search: off
Sure — here’s a practical way to set up API billing and usage tracking.
Core pieces you need
-
Authentication
- Give each customer an API key / token.
- Use that key to identify the tenant/account on every request.
-
Usage metering
- Log each request with:
- account/customer ID
- endpoint
- timestamp
- request size / response size
- compute time / tokens / units used
- success/failure status
- Log each request with:
-
Billing rules
- Define how usage converts to charges:
- per request
- per 1,000 requests
- per token / compute unit / GB / minute
- monthly base fee + overages
- Define how usage converts to charges:
-
Usage aggregation
- Roll up raw events into:
- daily totals
- monthly totals
- by endpoint/product
- Keep raw logs for audit/debugging.
- Roll up raw events into:
-
Invoice generation
- At billing cycle end:
- compute total usage
- apply plan pricing
- generate invoice / receipt
- send to payment processor
- At billing cycle end:
-
Customer dashboard
- Show:
- current usage
- projected bill
- billing period
- invoices and payment status
- Show:
-
Alerts and limits
- Set thresholds for:
- 50%, 80%, 100% of quota
- hard/soft usage caps
- Notify customers before surprises.
- Set thresholds for:
Simple architecture
- API Gateway / Backend
- validates API key
- records usage event
- Usage service
- stores events in DB or stream
- aggregates usage
- Billing service
- applies pricing rules
- creates invoices
- Payment provider
- Stripe, Paddle, Chargebee, etc.
Minimal data model
Usage event
- id
- account_id
- api_key_id
- endpoint
- units_used
- request_at
- metadata
Plan
- id
- name
- monthly_fee
- included_units
- overage_rate
Invoice
- id
- account_id
- period_start
- period_end
- usage_units
- amount_due
- status
Common implementation pattern
- On every request:
- authenticate
- execute request
- calculate units used
- write usage event asynchronously
- Nightly or real-time:
- aggregate usage by account
- Monthly:
- bill based on aggregated usage
Good tools
- Billing/payment: Stripe Billing, Chargebee, Recurly, Paddle
- Usage/event storage: Postgres, ClickHouse, BigQuery, Snowflake
- Streaming/queue: Kafka, SQS, RabbitMQ
- Analytics/dashboard: Metabase, Grafana, custom UI
Important considerations
- Handle retries/idempotency so one request isn’t billed twice.
- Decide whether failed requests are billable.
- Store raw events for audit.
- Make billing logic versioned so pricing changes don’t affect old periods.
- Consider timezone and billing period boundaries carefully.
If you want, I can also provide:
- a database schema,
- a Stripe-based implementation, or
- example code for tracking API usage in your backend.