How Do You Implement Usage-Based Billing in a SaaS Product?
Usage-based billing SaaS implementation: metering architecture, rating engines, build vs buy, AI token billing, and quota enforcement for engineering teams.
Usage-based billing has become the default monetization model for AI-first SaaS — and it requires a fundamentally different engineering architecture than subscription pricing. With subscription billing, you charge a flat fee and the billing system barely touches your product. With usage-based billing, metering is woven into every layer of your stack: API calls are instrumented, events flow through a pipeline, pricing logic runs against aggregated counts, and quotas are enforced in real time at the application layer. Getting this wrong means revenue leakage, inaccurate customer invoices, and billing infrastructure that collapses under production load. This guide covers how to implement usage-based billing in a SaaS product from the engineering perspective — not the pricing strategy, but the actual system design.
The adoption curve has accelerated sharply. OpenView Partners' 2025 benchmarks show that more than 60% of B2B SaaS companies now include at least one usage component in their pricing, driven largely by AI features where costs are inherently consumption-based. Charging per-seat for a product that calls an LLM on every request is structurally broken — your cost scales with usage but your revenue does not. Usage-based billing solves the alignment problem, but it introduces a new class of engineering problems that most teams underestimate.
This post covers the three-layer architecture that every usage-based billing system requires (metering, rating, billing), the build-vs-buy decision for billing infrastructure, the edge cases that cause most revenue leakage, and how AI features change the metering problem. If you are building a SaaS product and approaching this decision, our SaaS development practice covers billing architecture as part of every production-grade product we ship.
The Three Layers of Usage-Based Billing
Usage-based billing is not one system — it is three systems that must work together reliably. Conflating them is the root cause of most failed implementations. Each layer has distinct reliability requirements, distinct latency tolerances, and distinct failure modes.
- →Metering: the instrumentation layer that captures raw usage events from your product. Every billable action — an API call, a file processed, a model invocation, a message sent — must emit an event with a customer identifier, a timestamp, and a quantity. Metering must be at-least-once durable: losing events means losing revenue. It must also be idempotent: duplicate events from retries, network errors, or re-delivery must not double-bill customers
- →Rating: the calculation layer that applies your pricing rules to aggregated usage. The rating engine takes a count (1,400 API calls this month for customer X) and applies pricing logic (first 1,000 at $0.001 per call, next 500 at $0.0008 per call) to produce a dollar amount. Rating complexity grows fast: volume discounts, prepaid credits, concurrent commitments, and per-feature pricing all interact in ways that simple multiplication cannot handle
- →Billing: the invoicing and collection layer. This is what most people think of when they hear 'billing system' — but in a usage-based model, billing is actually the simplest layer. The hard work happens in metering and rating. Billing takes the rated amounts, generates an invoice, triggers payment collection via Stripe or similar, and handles failed payments, retries, and dunning
Designing Your Metering Layer
Metering is where most usage-based billing implementations go wrong, because it requires instrumenting code that engineers write without thinking about billing. The metering layer must be low-latency enough not to block the hot path, durable enough to guarantee delivery, and granular enough to support any pricing model you might introduce later.
- →Event-driven metering over polling: instrument usage as events, not as periodic database queries. A database-poll approach — counting rows at end of month — is fragile, misses real-time quotas, and cannot reconstruct usage at arbitrary time granularities. Emit structured events to a durable queue (Kafka, SQS, or Pub/Sub) from the application layer at the point of consumption, not from a scheduled job
- →Identify your value metric before instrumentation: the value metric is the unit your pricing will be based on — API calls, active users, compute minutes, AI tokens, processed documents. Choose it based on alignment with customer value, not technical convenience. Once chosen, instrument at that level — not coarser — because you cannot re-derive fine-grained data from aggregates after the fact. Our post on event-driven architecture for enterprise SaaS covers the underlying event pipeline patterns in depth.
- →Deduplication is non-negotiable: in a distributed system, events will arrive more than once. Every downstream consumer — rating engine, quota enforcer, dashboard — must be idempotent with respect to duplicate events. The standard approach: assign each event a deterministic idempotency key at the source (derived from the request ID and event type, not a random UUID), store seen keys in a time-windowed set (Redis sorted set or DynamoDB with TTL), and discard duplicates before aggregation. At high volume, bloom filters handle first-pass deduplication before the database check
- →Late-arriving events require a grace window: in a distributed system, events arrive out of order. Network partitions, retry storms, and asynchronous processing mean an event for 23:59:58 on the last day of the billing period may arrive 30 minutes later. Your aggregation pipeline must support a late-arrival window — typically 5 to 15 minutes for real-time quotas, up to 24 hours for invoice finalization — during which late events can be absorbed into the correct billing period without reopening closed invoices
The Rating Engine: Pricing Logic as Versioned Configuration
The rating engine is the most underestimated component in usage-based billing. Teams reach for Stripe's product catalog and discover that complex pricing models — volume tiers, committed-use discounts, per-feature pricing — cannot be expressed in the platform's data model without significant workarounds. Rating engines need to be deliberately designed.
- →Model pricing as a rule tree, not hardcoded logic: pricing changes frequently. An implementation that encodes pricing rules in application code requires a deployment to change a price. Model pricing as versioned data: a structure that defines the metric, the tiers, the aggregation window, and the calculation method. Store it in a versioned configuration store or a purpose-built billing platform's API. The application applies the rules; the rules are not the application
- →Support multiple aggregation models: count (number of events), sum (total value across events), max (peak value in a window), and unique count (distinct entities) are the four primary aggregation types. Count covers API calls; sum covers data processed; max covers concurrent connections; unique count covers active seats. Your rating engine needs to support all four — not because you will use them all on day one, but because your pricing will evolve
- →Real-time rating for quota enforcement vs end-of-period rating for invoicing: these are two different use cases with different latency and accuracy requirements. Quota enforcement needs a running count that updates within milliseconds of each event using Redis counters incremented per event. Invoice generation needs exact amounts calculated against full-period data with all late-arriving events absorbed. Running the same pipeline for both is a design smell — they have different consistency requirements
Build vs. Buy: The Billing Infrastructure Decision
The most consequential architectural decision in a usage-based billing implementation is whether to build the metering and rating stack in-house or use a purpose-built billing platform. The default answer in 2026 is to buy — but the decision is more nuanced than vendor marketing suggests.
- →Use Stripe Billing as the baseline: if your pricing model is simple — one or two usage metrics, straightforward tiers — Stripe's metered billing with usage records is sufficient and integrates with your existing payment infrastructure. The limits: Stripe's rating logic is inflexible, deduplication is your responsibility, and the API's rate limits can be a constraint at high event volumes. Start here and migrate when you hit the ceiling
- →Use a purpose-built platform for complex models: platforms like Lago (open-source, self-hostable), Orb, Metronome, or m3ter provide metering pipelines, rating engines, invoice generation, and Stripe integration out of the box. They handle late-arrival windows, deduplication, and currency conversion. Expect 4 to 8 weeks of integration work versus 3 to 6 months for a custom build. The switching cost if you outgrow them is real, but the time-to-market advantage is significant for most teams
- →Build in-house only when: your pricing model is genuinely unusual and no vendor supports it, you have regulatory requirements around billing data residency that managed platforms cannot meet, or your usage volume is so extreme that per-event platform fees exceed the cost of the engineering investment. Building in-house means owning a Kafka-based event pipeline, a rating service, a quote store, and a payment integration — a meaningful ongoing maintenance commitment
Revenue Leakage: The Edge Cases That Break Billing
Most usage-based billing implementations do not fail catastrophically — they slowly leak revenue through a predictable set of edge cases. Identifying and handling these before launch is significantly cheaper than auditing and reconciling after the fact.
- →Retroactive price changes: customers negotiate custom pricing, promotional discounts expire, or you restructure your tiers. If your rating engine applies current pricing to historical usage at invoice time, a mid-month price change produces incorrect invoices. Always store a snapshot of the pricing structure that was in effect at the time of usage alongside the usage record, and rate against that snapshot — not the current configuration
- →Credit burn-down ordering: customers often have multiple credit pools — purchased credits, promotional credits, committed-use discounts — with different expiry dates and scope restrictions. The order in which credits are burned affects revenue recognition. Define the burn order explicitly in your pricing configuration and test it against multi-pool contract scenarios before launch
- →Multi-tenant usage attribution: in multi-tenant SaaS, usage rolls up from individual users or teams to the billing account. Ensure your event schema captures both the originating identity (user ID) and the billing identity (account ID) from the moment of instrumentation — retrofitting this mapping later requires re-processing your entire event history. See our post on multi-tenant SaaS architecture for more on how tenant identity propagates through a multi-tenant system.
- →Clock skew between services: services run on different machines with clocks that diverge by seconds or minutes. A usage event timestamped at 23:59:55 on one service might arrive with an ingestion clock reading of 00:00:05 on the aggregation service. Define usage period boundaries using the event's originating timestamp, not the ingestion timestamp, and monitor clock drift across all services that emit billing events
Usage-Based Billing for AI Features
AI-native SaaS products have made usage-based billing essentially mandatory — you cannot offer a flat subscription for a product where your primary cost is LLM token consumption without absorbing enormous and unpredictable cost variance. But AI billing introduces metering challenges that traditional usage-based systems were not designed to handle. Our AI & Automation engineering practice encounters these patterns in every AI product we build.
- →Token metering requires provider-native counting: token counts are not character counts, and each model family uses a different tokenizer. If you bill on token consumption, you must use the provider's exact count — not an estimate — and capture both input and output tokens separately, since they are priced at different rates. Always read token counts from the provider's API response metadata, not from pre-call estimates
- →Pass-through cost accounting: many AI SaaS products bill customers at a markup on the underlying model cost. This requires capturing the exact provider cost per request — available in the API response or billing dashboard export — and attributing it to the correct customer account in real time. Build a cost attribution layer that sits between your AI provider client and the rest of your application, capturing provider cost alongside the usage event
- →Budget controls and soft limits: AI costs can spike unexpectedly from user errors, runaway batch jobs, or prompt injection attacks. You need both hard limits (block usage above the quota ceiling) and soft limits (alert the customer at 80% of their budget, send a webhook, allow self-serve limit increases). Hard limits must be enforced at the API gateway or middleware layer with a sub-millisecond lookup — Redis is the right data store, not your primary database
- →Agentic run cost estimation: multi-step, tool-calling agent workflows have non-deterministic cost profiles because the number of LLM calls depends on the agent's reasoning path. Common patterns: bill on actual consumed tokens across the run, or cap runs at a configured token budget and terminate gracefully when the budget is exceeded rather than continuing to accumulate unbounded cost
Quota Enforcement and Customer-Facing Usage Visibility
Metering and rating without quota enforcement leaves money on the table and creates customer disputes. The enforcement layer closes the loop between billing infrastructure and the product experience, and customer-facing usage visibility dramatically reduces support load.
- →Enforce at the API gateway layer: quota checks should happen before your application logic runs, not inside it. An API gateway or custom middleware intercepts each request, checks the customer's remaining quota from a fast cache, and returns a 429 Too Many Requests or 402 Payment Required before your application processes the request. This is both more reliable — application code cannot accidentally skip the check — and more efficient — you do not pay for compute on requests you will reject
- →Separate soft and hard limits in your data model: soft limits (notification threshold at 80% of quota) and hard limits (enforcement ceiling at 100% of quota) should be stored separately with separate configuration paths. A customer-service team needs to be able to raise a hard limit for a customer in a billing dispute without changing the notification thresholds that trigger account manager alerts
- →Build a self-serve usage dashboard: customers who can see their own usage in real time do not call your support team when they approach a limit. A usage dashboard showing daily consumption, remaining quota, and projected month-end usage dramatically reduces billing-related churn and support load. A 5-minute aggregation lag is acceptable for customer-facing dashboards. Our SaaS engineering team treats the usage dashboard as a first-class product feature, not an afterthought.
Frequently Asked Questions
What is the difference between metered billing and usage-based billing?
Metered billing is the technical mechanism — counting units of consumption and billing for them. Usage-based billing is the pricing model — charging customers based on what they consume rather than a fixed subscription fee. All usage-based billing uses metering, but metered billing can also be used as an add-on to subscription pricing, such as a base subscription with overage charges above a usage threshold. The terms are frequently used interchangeably in practice.
Should we build our own metering system or use a billing platform?
For most SaaS products, buy before you build. Purpose-built billing platforms such as Lago, Orb, and Metronome handle the hard engineering problems — event deduplication, late-arrival windows, currency conversion, invoice generation — that take months to get right in a custom implementation. Build in-house only when your pricing model is genuinely unusual and no vendor supports it, you have data residency requirements that managed platforms cannot meet, or your usage volume makes per-event platform fees exceed the cost of the engineering investment.
How do you meter AI token usage across multiple LLM providers?
Normalize token counts to a common billing unit in your metering layer, using the provider's exact token count from the API response — not your own estimate. Store the raw provider tokens alongside a normalized billing-token count that applies a provider-specific conversion factor. This allows you to change the underlying model without restructuring your billing schema. Capture input and output tokens separately since they carry different costs at every major provider. Never estimate from character counts.
How do you prevent revenue leakage in usage-based billing?
The main sources of revenue leakage are: duplicate event counting (use deterministic idempotency keys and a deduplication store), events lost before aggregation (use a durable queue, not synchronous database writes), incorrect period attribution (use the originating timestamp, not the ingestion timestamp), and retroactive pricing errors (rate against a pricing snapshot stored with each usage record, not the current configuration). Run a monthly reconciliation that compares raw event counts against invoiced amounts to catch systematic drift before it compounds.
What is the minimum event schema for a usage billing system?
Every usage event needs at minimum five fields: a deterministic idempotency key (derived from the request ID and action type, not a random UUID), a billing account ID (the entity that receives the invoice — not the user ID), an event type (what was consumed), a quantity (how much), and an originating timestamp (when the consumption happened in the source service's clock). Additional fields that prevent common retrofit pain: the originating user ID (for attribution reporting), the feature or product area (for per-feature pricing), and a metadata object for audit and customer-facing display.
How Belsoft Helps SaaS Products Implement Usage-Based Billing
Belsoft designs and builds the full usage-based billing stack for SaaS products moving to consumption-based pricing — from event instrumentation design through rating engine architecture, platform selection, quota enforcement, and customer-facing usage dashboards. We have implemented usage-based billing for AI-native products and traditional SaaS applications, and we bring the production patterns that prevent the most common revenue leakage and scalability problems. If your team is designing the billing architecture for a new SaaS product or migrating from flat subscription pricing, talk to our SaaS engineering team to scope the architecture.
“Usage-based billing is not a pricing strategy you hand off to finance — it is an infrastructure decision that shapes your entire product architecture from day one.”
Written by
Belsoft Team
More from the blog
Ready to build?
Let's talk about your project.
30 minutes. No pitch. We map your requirements and tell you honestly what it will take.
Book a Strategy Call