Blog
/
Guides

API Billing System: 8 Components to Build One in 2026

An API billing system meters usage, enforces limits in real time, and records every charge. Here's how to build one for tokens, credits, and usage in 2026.

Sara NelissenSara Nelissen
Written by
Sara Nelissen
Last updated
October 9, 2026
read time
15
minutes
An API billing system meters usage, enforces limits in real time, and records every charge. Here's how to build one for tokens, credits, and usage in 2026.

Table of contents

Your first API billing system is probably a balance column and a cron job, and it holds until an enterprise customer asks for per-department limits.

The full system adds idempotent metering, real-time enforcement, and an append-only ledger for tokens, credits, and usage. Where each part sits in your architecture determines how it fails under load.

What an API billing system does

An API billing system measures API usage, applies pricing rules, enforces limits in real time, and records every charge for reconciliation, and each of those jobs grows faster than you expect.

Payment gateways like Stripe and Adyen move money by taking a card and settling a charge. A billing system decides what to charge and what is allowed, then hands settlement to one of those providers.

Invoicing comes last in the chain. The hard part lies upstream, in the metering and enforcement that decide what each invoice should say.

Treat the system as product infrastructure that has to move as fast as your pricing does. When product ships a new model or changes a rate, the billing system should follow in days.

The core components and what breaks without each

A working system is a set of stateful components that stay aligned on every request, and each one has a failure mode you inherit if you skip it.

The table below maps the components to their jobs and their failures:

Component What it does Failure mode if missing
Metering/usage ingestion Captures usage events (calls, tokens, compute) Billing drift; you charge for the wrong numbers
Rating and pricing engine Turns raw usage into charges under a pricing model Wrong prices, or models you cannot support
Entitlements and enforcement Decides access and limits in real time Over-consumption; accounts run past their plan
Credit and wallet ledger Tracks balances, grants, and burn order Incorrect depletion; balances that do not reconcile
Invoicing Generates invoices from rated usage Manual billing every cycle
Payment processing Orchestrates settlement through a provider No payment collected
Dunning Recovers failed payments Failed payments go unrecovered
Revenue analytics and rev-rec Recognizes revenue as usage is consumed Finance cannot close the books

Metering ingestion and entitlement enforcement run synchronously in the request path and resolve before compute runs. Invoicing, dunning, and revenue recognition run later, off the hot path.

Every component also has to fail safely. If the entitlement service degrades, enforcement cannot silently wave requests through, which is how accounts go negative at scale.

How billing-system APIs work

A billing-system API exposes a set of resources and consumes usage events from your product, so both sides need design attention.

The core resources are customers, subscriptions, plans and prices, usage events, credits or wallets, and invoices. Most are standard REST resources, and the usage and write endpoints carry the interesting behavior.

Usage ingestion needs idempotency keys because usage pipelines deliver at least once, so the same event will eventually arrive twice. Without a unique event ID and pipeline-level deduplication, retries double-count and every downstream charge inherits the error.

Webhooks push state changes back to your app, such as usage.recorded, invoice.paid, and entitlement.updated.

Delivery is at-least-once here too, so your webhook consumers have to be idempotent.

The enforcement decision is the one call that has to stay synchronous, because every other step can settle later and this one gates compute.

Metering: The layer where accuracy starts

Metering is the layer where accuracy starts because every error made here compounds downstream, and no amount of clean invoicing rescues it. Four decisions keep the numbers honest.

  • The unit you meter should map to your real marginal cost. Request volume is the obvious choice, but AI products meter token counts, compute time, payload size, or unique active users.
  • Idempotent ingestion gives every event a unique ID and deduplicates before aggregating. Skipping it causes the most common billing drift, which stays invisible until a customer disputes an invoice.
  • Late-event handling lets windowing logic tolerate events that arrive late or out of order without dropping them or counting them twice.
  • Versioned rates keep historical usage at the price in effect when it was consumed. That takes versioned rate mappings and immutable usage records, which a single mutable price field cannot provide.

Metered billing needs the same correctness guarantees as the rest of your stack, and these four decisions are where it earns them.

Pricing models your system has to support

Your system has to support flat, per-seat, usage-based, tiered, hybrid, and credit pricing, and each model changes what the rating engine computes. Pricing pages make them all look alike, but the rows below show where they pull on your infrastructure.

Pricing model How it charges Where it strains the system
Flat/subscription Fixed fee per cycle Barely touches metering
Per-seat Fee per active user Seat counting and proration on changes
Usage-based/PAYG Per unit consumed Real-time metering accuracy under load
Tiered and volume Rate changes at thresholds Retroactive vs prospective tier math
Hybrid Base fee plus overage Two engines running together, reconciled
Credits/tokens/wallets Shared balance drawn at varying rates Ledger, burn order, expiry, enforcement

Usage-based charging is where the complexity starts, and the full design decisions behind it deserve a pass before you build. Hybrid and credits push you from a simple counter into real infrastructure.

Packaging changes, such as adjusting a limit or a feature in a plan, can often ship without engineering. Pricing-model changes, such as moving to usage, hybrid, or credits, remain an engineering project.

Credits, tokens, and wallets as first-class primitives

Credits, tokens, and wallets are first-class primitives because one shared balance has to stand in for many features that each cost a different amount.

Stability AI's credit pricing shows the pattern, with cost that varies by endpoint and request parameters and a samples parameter that multiplies the credits spent per call.

That variety is why a single counter falls over. It breaks under concurrent load, leaves no audit trail, and can't enforce burn order or block-level expiry, so a production credit system tracks blocks, and each grant carries its own metadata.

  • Effective and expiry dates say when credits become usable and when they lapse, which keeps monthly resets and time-boxed promotions honest.
  • Cost basis records what was paid per credit at grant time. Paid credits carry the purchase rate and promotional credits carry zero, so finance can recognize revenue at consumption.
  • Category or scope pins a grant to certain features, such as image generation.
  • Burn priority picks which block depletes first, with promotional and sooner-expiring credits going before paid, longer-lived ones.

Every grant and debit then lands as an event on an append-only ledger. Finance gets an audit trail, and enforcement gets the data to apply the right rule on the very next request.

Stigg models credits this way, as ledger blocks with expiry, cost basis, category, and burn order, and its credits documentation goes deeper.

Then comes the question every credit system eventually answers, which is what happens at zero. A hard limit denies usage when the balance runs out, and a soft limit lets the balance go negative and reconciles later.

Miro's rollout of AI credits in a hybrid seat and usage model took under 6 weeks and saved 5,000 engineering hours, a fair benchmark for credit behavior that never turns into a second product.

Enforcement in the request path: Recording versus deciding

Enforcement in the request path decides what a customer may do right now, before execution, while billing records what already happened.

Most implementations nail metering and skip enforcement, so usage gets recorded and nothing stops the request once the balance hits zero.

Enforcement runs on entitlements, commercial allowances that define what a customer can access and how much they can use.

In practice, a customer's effective entitlements are the sum of several sources, like their active plan, any parent plan they inherit from, add-ons that increment or override plan limits, active trials, and promotional entitlements granted directly to them.

Unlike RBAC (role-based access control), which governs who inside an organization may use a feature, an entitlement carries a limit and a running count of consumption.

Limits come from several places at once, including the base plan, a parent plan, add-ons, active trials, and promotional grants, and the most generous valid value wins.

Ask the check for more than yes or no. Stigg's getEntitlement response does this out of the box by returning the feature's access status, usage limit, current usage, and whether the customer has unlimited access, so your frontend has everything it needs without extra calls or custom logic.

Each enforcement scenario asks something different of your system, and the rows below show what goes wrong when you skip it.

Scenario System requirement Risk if missing
Balance available Real-time check plus atomic deduction Inconsistent state across services
Hard limit hit Low latency block at request time Uncontrolled usage and cost leakage
Soft limit passed Support for negative balances, reconciled to billing Billing disputes and unreconciled overage
Overage enabled Enforcement wired to the billing system Product and billing drift apart

Agents make all of this harder. One agent action fans out into sub-calls and tool invocations that draw from the same pool at once, with no natural serialization point, so an entry-point check misses most of them.

Enforcement has to follow every step with atomic reads and writes against current credit state.

A runtime layer earns its keep here, since Stigg ties credit balances to entitlement enforcement and resolves the decision before compute runs.

On a cache hit, entitlement checks resolve instantly from local Redis. On a cache miss, the Sidecar fetches from Stigg's Edge API at around 100ms, with a configurable timeout.

The Sidecar runs as a Docker container in your own cloud (BYOC), and persistent caching keeps reads flowing if the upstream service becomes unreachable, which covers reliability.

Where API billing systems break in production

API billing systems break in production in five predictable places, which are concurrency races, cache drift, burn-order bugs, partial failures, and reconciliation drift, and most of them turn out to be one concurrency problem in five disguises.

Each failure has a signature and a solution, and the rows below pair them up.

Failure mode What is happening under the hood How to fix it
Concurrency race Two requests pass the same balance check before either debit commits Atomic deduction; serialize the write at the storage level
Cache drift A plan change lands, but cached entitlements serve the old state through the TTL Invalidate the cache on entitlement change as well as expiry
Burn-order bugs Paid credits deplete before promotional or expiring ones Keep burn order in the data model
Partial failure The debit succeeds, the request fails, the customer is charged for nothing Transactional debit plus a ledger trace, then reconcile
Reconciliation drift Wallet, billing, and analytics disagree on the numbers One source of truth; downstream systems derive from the ledger

Idempotency, consistency, and enforcement timing all trace back to the same concurrency problem. Treat them as separate edge cases and you end up with enforcement scattered across services and middleware, with none of it authoritative.

You can test this cheaply. Fire parallel requests at a single balance and watch whether it ever goes negative. It often does, and that test is the cheapest bug report you will ever get.

Invoicing, payments, dunning, and compliance

Invoicing, payments, dunning, and compliance make up the back half of the system, the unglamorous part where money moves and records get kept.

Invoicing turns rated usage into a bill, and it has to handle proration when a customer changes plan mid-cycle. Payment processing orchestrates settlement, with card data staying in a PCI DSS compliant processor, so your system triggers the charge and never touches a card number.

Dunning chases failed payments with timed retries and a grace window before a hard cutoff. Match that cutoff to your hard and soft limit behavior, or customers will hit two different walls for the same problem.

The append-only ledger ties it all together. It lets finance recognize revenue on consumption under ASC 606 or IFRS 15 and backs your SOC 2 evidence, audit logs, and access controls.

Auditors will ask you to trace a charge back to its source event. If you can't, the audit ends there.

Build versus buy, and how long it really takes

Build first and buy once the requirements stack up, and expect the timeline to run longer than your estimate.

Building is the right first move. A balance field, a decrement function, and a cron job for expiry carry an early product further than most people expect, and you control every line of it.

The trouble starts when the requirements pile on. Burn priority across grant types, real-time enforcement under load, finance-grade audit trails, and configurable depletion per feature each become their own project.

Together they form a maintenance load that grows with your customer base, and someone on your roster ends up owning it full time.

Timelines stretch too. Introducing usage-based or credit pricing at an enterprise takes months, and a "couple of sprints" estimate rarely survives the first edge case.

You also have a third option. A control and runtime layer can sit beside a billing provider like Stripe, Zuora, or Orb, so you keep the system that settles invoices and add the layer that enforces entitlements and credits in the request path.

What API billing systems leave uncovered

API billing systems leave request-time enforcement uncovered, because they record usage and settle invoices after the fact, and nothing in that flow decides whether the next call should run.

Stigg fills that space as the usage runtime for AI products, with entitlements, credits, usage limits, and spend governance enforced synchronously in the request path.

Stripe, Zuora, or your custom billing keeps settling invoices while Stigg sits beside it, holding entitlement latency in single-digit milliseconds on cache hits, persistent caching.

This way, reads keep flowing if the upstream service goes down, and configurable timeouts on the Edge API fetch so a slow upstream never cascades into your request path.

Think of it as a set of answers to questions your billing system was never built to ask:

  • When a call needs an answer before compute runs, the Sidecar, a Docker container beside your app, caches entitlement data in Redis. Cache hits resolve instantly, and misses fetch from Stigg's Edge API at around 100ms with a configurable timeout.
  • When data has to stay home, BYOC (Bring Your Own Cloud) runs the same runtime inside your VPC and covers data residency requirements.
  • When credits outgrow a counter, the credits engine adds blocks with expiry, cost basis, paid and promotional categories, configurable burn order, hard or soft depletion, and an append-only ledger.
  • When a customer holds a plan, an add-on, and a trial at once, entitlements resolve the limit across all of them, with the most generous value winning.
  • When budgets follow an org chart, limits apply per agent, user, team, product, or department.
  • When product wants to change a plan, packaging moves through config without a deploy, while engineering owns pricing-model changes.
  • When you want to start small, metering, entitlements, and the credits engine each run on their own, and startups often begin with a single SDK integration.

Your billing system already knows how the month ended. Stigg's docs show where the Sidecar, entitlement layer, and credits ledger decide how the next request begins.

Frequently Asked Questions

1. What is an API billing system?

An API billing system measures API usage, applies a pricing model, enforces limits in real time, and records every charge for reconciliation. It sits between your product and a payment provider and decides what to charge and what is allowed, and it leaves moving the money to the provider.

2. How is an API billing system different from a payment gateway like Stripe?

The main difference between an API billing system and a payment gateway like Stripe is that a gateway moves money by capturing a card and settling a charge, and a billing system decides what to charge and what a customer may consume. They coexist, and most stacks run both.

3. Should you build or buy an API billing system?

You should build an API billing system early and revisit the decision once burn order across grant types, real-time enforcement under load, and audit trails each become their own project. Buying, or adding a runtime layer beside your billing provider, avoids rebuilding the stack in-house.

4. How do you prevent double-charging during usage spikes?

You prevent double-charging during usage spikes with idempotent metering and atomic deduction. Every usage event carries a unique ID so retries deduplicate, and credit debits commit atomically so two concurrent requests cannot both pass the same balance check.

5. How do credits and tokens fit into an API billing system?

Credits and tokens fit into an API billing system as a shared currency metered across features at different rates. A production system tracks them as append-only ledger blocks with their own expiry, cost basis, category, and burn order, and enforces it in the request path before compute runs.

Latest news.

One email per month.
From engineers, for engineers.

Thank you! Your submission has been received.
Oops! Something went wrong while submitting the form.