GH GambleHub

API Billing and Reporting

1) Why own billing for API

Transparent monetization: usage link → revenue.
Scalability and control: quotas, override, loans, price book according to plans.
Financial accuracy: taxes/VAT, multicurrency, acts and closing documents.
Customer trust: detailed usage reports, webhooks, self-service portal.

2) Billing architecture (high-level)

Producers (API gateway, services) → Usage Event Bus (Kafka/Queue) → Metering & Rating → Billing DB → Invoicing/Taxes → Payments (PSP) → Reporting DWH → Client Portal/Webhooks.

Components:
  • Metering - collection and normalization of usage (requests, loans, volumes).
  • Rating - estimate of the cost of the event according to the price book/plan.
  • Invoicing - aggregation for the period, profit, taxes, discounts, credits.
  • Payments - write-offs/refands, dating (dunning).
  • Reporting - MRR/ARPU/LTV, cohort churn, cost-to-serve.
  • Audit - idempotence, unchanging logs.

3) Entities and identifiers

Account (tenant), Plan, Entitlements, Usage Event, Invoice, Credit Note, Tax Profile.
Vital: idempotency_key to usage/invoice/payment, source (gateway/batch), version of the event schema.

4) Usage event: reference scheme

json
{
"event_id": "use_01HXYZ...",
"idempotency_key": "key_6a2f-2025-11-03T18:02:09Z",
"occurred_at": "2025-11-03T18:02:05Z",
"ingested_at": "2025-11-03T18:02:09Z",
"tenant_id": "t_123",
"api_key_id": "k_456",
"plan_id": "pro-2025",
"endpoint": "POST /v1/reports/run",
"unit": "credit",
"quantity": 5,
"region": "eu-west-1",
"metadata": { "request_id": "r_789", "ip": "203. 0. 113. 5" },
"signature": "hmac_sha256_base64(...)",
"schema_version": 2
}

Rules: events are only added; edits - via corrective adjustment events with reference to 'event _ id'.

5) Storage and aggregation layer

5. 1 OLTP (Billing DB)

Таблицы: `tenants`, `plans`, `plan_prices`, `entitlements`, `usage_events`, `rated_lines`, `invoices`, `invoice_lines`, `tax_rates`, `credits`, `payments`, `refunds`, `disputes`.

5. 2 DWH (analytics)

Факты: `f_usage`, `f_billing`, `f_payments`; dimensions: 'd _ tenant', 'd _ plan', 'd _ endpoint', 'd _ region', 'd _ date'.

5. 3 Example of SQL aggregation usage → billed lines

sql
-- 1) Reduce usage per day by units create materialized view mv_daily_usage as select tenant_id, plan_id, endpoint, date_trunc ('day', occurred_at) d,
unit, sum(quantity) qty from usage_events where occurred_at >=:period_start and occurred_at <:period_end group by 1,2,3,4,5;

-- 2) Price book (tiered) applicable
select u. tenant_id, u. plan_id, u. d, u. unit, u. qty,
p. tier_from, p. tier_to, p. price_per_unit,
least(greatest(u. qty - p. tier_from + 1, 0), p. tier_to - p. tier_from + 1) as billable_units,
price_per_unit least(...) as amount from mv_daily_usage u join plan_prices p on p. plan_id = u. plan_id and p. unit = u. unit and u. qty >= p. tier_from;

6) Price book and rating (rating)

Support models: flat, tiered, volume, bundled credits, pay-as-you-go, and override.

Price Book Example (YAML):
yaml plan_id: pro-2025 currency: USD units:
request:
tiers:
- { from: 1, to: 250_000, price_per_1k: 2. 5 }
- { from: 250_001, to: 1_000_000, price_per_1k: 2. 0 }
credit:
flat: { price_per_unit: 0. 001} # 1 credit = $0. 001 overage:
policy: "postpaid"
rounding: "ceil_1k"
minimum_commit: 99 # basic subscription/month

7) Invoicing: account formation

Stages:

1. Cutoff period (by account locale).

2. Rate at up/down-grade plan (by day).

3. Usage rating + fixing invoice lines.

4. Taxes (VAT/GST) by customer location and service point.

5. Credits/discounts/coupons.

6. Signing and publishing, sending for payment (PSP), webhooks.

Invoice line (example):
json
{
"line_id": "invln_01",
"type": "usage",
"description": "API requests (first 250k)",
"unit": "request",
"quantity": 250000,
"unit_price": 0. 0025,
"amount": 625. 00,
"currency": "USD",
"tax_rate": "VAT20",
"amount_tax": 125. 00
}

8) Taxes and multicurrency

VAT/VAT/GST: keep Tax Profile (country, valid VAT-ID, B2B/B2C).
Tax rates by date (version), reverse charge for EU B2B.
FX conversion: rate on the invoice date (ERU/provider), keep the source of the rate.
Documents: invoice, credit note, debit note - with numbers and series.

9) Payments, dating and disputes

PSP (Stripe/Braintree/Adyen): tokenized payments, retrays on refusal, dunning (1-3-7 days).
Disputes/chargebacks: fixing statuses, linking to an invoice, interaction timeline.
Refunds: partial/full, associated with 'payment _ id' and 'invoice _ id'.
Fraud signals: geo/ASN anomalies, usage bursts, different cards - flags in billing.

10) Credits, discounts, SLA credits

Promo loans (wallet), service credits for violation of SLA (auto start in the next period).
Coupons: fixed/interest, minimum term, restrictions on plan/endpoints.
Transparency: in the portal show the balance of loans and the history of write-offs.

11) Idempotency and adjustments

All write operations via Idempotency-Key.
Adjustments - only through adjustments events (positive/negative), without editing the original.
Reconciliation: daily verification of usage ↔ rated_lines ↔ invoices ↔ PSP.

12) Safety and compliance

HMAC/JWT signature usage events from gateway.
mTLS for ingest, individual keys per environment (prod/stage).
PII minimization (do not store PAN/mail unnecessarily), DSAR/Legal Hold.
Audit-log unchangeable (append-only) for financial transactions.

13) Billing Portal API (OpenAPI fragments)

yaml paths:
/v1/billing/usage:
get:
summary: Usage breakdown parameters: [ {name: from, in: query}, {name: to, in: query}, {name: unit, in: query} ]
responses: {"200": {description: OK}}
/v1/billing/invoices:
get: { summary: List invoices }
/v1/billing/invoices/{id}:
get: { summary: Get invoice (PDF/JSON) }
/v1/billing/credits:
get: { summary: Credit wallet balance }
/v1/webhooks/billing:
post:
summary: Billing webhooks description: "invoice. created, invoice. finalized, payment. succeeded, credit. applied"

The headers in the main API responses are 'X-Quota-Remaining', 'X-RateLimit-Remaining', 'X-Usage-Period'.

14) Webhooks and billing events

Events: 'invoice. created`, `invoice. finalized`, `payment. succeeded|failed`, `dunning. retry`, `credit. applied`, `dispute. opened|closed`.
Requirements: signature of webhooks, repetition with backoff, deduplication by 'delivery _ id'.

15) Reporting and business metrics

Financial KPIs:
  • MRR/ARR (plan/geo segmentation), ARPU, LTV/CAC, Churn (logo/revenue), Net Revenue Retention (NRR).
  • Usage → Revenue: bottleneck conversion cards (where they run into quotas).
  • Cost-to-Serve: cost of infrastructure/request → margin on plans.
Sample Queries (DWH):
sql
-- MRR by invoice dates select date_trunc ('month', invoice_date) m, sum (recurring_amount) mrr from f_billing group by 1;

-- ARPU select m, sum(total_amount)/nullif(count(distinct tenant_id),0) arpu from f_billing_monthly group by 1;

-- Cohort by month of activation select cohort_month, month_since_start, sum (total_amount) revenue from f_billing_cohorts;

16) DevEx: Self-service portal

Registration, plans, keys, usage graphs, invoices (PDF/JSON), webhooks.
Upgrade/downgrade, invoice preview (pro-forma), payment method management.

Notifications: "quota <10%," "overidge included," "invoice issued/paid."

17) Testing and environment

Sandbox billing: dummy PSPs, test tax rates.
Contract tests of usage events (schema/required fields).
Replay prod samples in the stag, price beech regression tests.
Backfill is safe: only through batch-ingest with idempotency.

18) FinOps and the economics of tariffs

Consider the margin on endpoints/plans: revenue − cost-to-serve.
Allocate "expensive" operations to loans and limit in low-tiers.
Monitor the query-cost in Observability and link to billing.

19) Launch checklist

  • The'usage _ event '/' adjustment '/' invoice _ line'schemes are committed and versioned.
  • Price book tested (flat/tiered/volume), prorate/override correct.
  • Idempotency of ingestion and webhooks, audit-log append-only.
  • Tax/VAT/FX correct, customer profiles filled in.
  • Portal: usage, invoices, credits, webhooks; PSP integration and dunning.
  • DWH reporting (MRR/ARPU/LTV/Churn/NRR), reconciliation daily.
  • SLA credit and dispute policies are documented.

20) Frequent errors and anti-patterns

No idempotency → duplicate usage/double write-off.
Price "about request" without loans for heavy endpoints → negative margin.
Taxes "at the place of the company," not the client → compliance errors.
Invoices without detail → customer disputes.
No reconciliation between usage↔PSP↔invoysy → reporting discrepancies.

Total

Strong billing for APIs is event-driven metering architecture, clear price book, strict idempotence, correct tax/FX invoicing, and transparent reporting. Link usage to revenue, give the client clear details and automate the entire journey - from event to invoice to MRR dashboard. This will provide predictable incomes, fewer disputes and a manageable product economy.

Contact

Get in Touch

Reach out with any questions or support needs.We are always ready to help!

Telegram
@Gamble_GC
Start Integration

Email is required. Telegram or WhatsApp — optional.

Your Name optional
Email optional
Subject optional
Message optional
Telegram optional
@
If you include Telegram — we will reply there as well, in addition to Email.
WhatsApp optional
Format: +country code and number (e.g., +380XXXXXXXXX).

By clicking this button, you agree to data processing.