---
title: "How to Build a SaaS Billing System With Usage-Based Pricing"
author: "Nate Laquis"
author_role: "Founder & CEO"
date: "2028-08-31"
category: "How to Build"
tags:
  - build SaaS billing system usage-based pricing
  - usage-based pricing metering
  - SaaS billing infrastructure
  - event-driven billing
  - revenue recognition SaaS
excerpt: "Usage-based pricing sounds great on a slide deck. Then you realize you need to meter millions of events, rate them in real time, generate accurate invoices, and handle edge cases that flat-rate billing never forced you to think about. Here is how to build it correctly."
reading_time: "15 min read"
canonical_url: "https://kanopylabs.com/blog/how-to-build-a-saas-billing-system"
---

# How to Build a SaaS Billing System With Usage-Based Pricing

## Why Usage-Based Pricing Changes Everything About Billing

Flat-rate subscription billing is straightforward. Customer picks a plan, you charge a fixed amount each month, and you are done. Usage-based billing is a different animal entirely. You are no longer charging for access. You are charging for consumption, and that means your billing system needs to do real work.

Think about what Twilio does. Every API call, every SMS sent, every phone minute used gets tracked, rated, aggregated, and billed. Snowflake does the same with compute credits. AWS does it across hundreds of services with per-second granularity. These companies did not bolt usage billing onto an existing system. They built purpose-designed infrastructure for it.

You probably do not need Snowflake-level complexity, but you do need a billing system that can answer one question accurately: how much does this customer owe for what they used this billing period? Getting that answer wrong in either direction is painful. Overbill and you destroy trust. Underbill and you bleed revenue.

The shift toward usage-based pricing is accelerating. OpenView's 2024 survey found that 61% of SaaS companies have adopted some form of usage-based pricing, up from 34% in 2020. Customers love it because they pay only for what they consume. But from an engineering standpoint, it introduces problems that most billing platforms were never designed to solve.

![Analytics dashboard showing usage metrics and billing data for a SaaS platform](https://images.unsplash.com/photo-1551288049-bebda4e38f71?w=800&q=80)

## Usage-Based Pricing Models and Which One Fits Your Product

Before you write a single line of billing code, you need to decide which usage-based model matches your product. This decision shapes your entire metering and billing architecture.

### Per-Unit Pricing

You charge a fixed rate per unit consumed. Examples: $0.01 per API call, $0.50 per GB stored, $2.00 per active user. This is the simplest model to implement because the math is straightforward: multiply the unit count by the unit price. Stripe Metered Billing supports this natively. If your usage is this predictable, you can lean heavily on Stripe and avoid building custom infrastructure.

### Tiered Pricing

The per-unit rate changes as usage increases. First 1,000 API calls are $0.02 each, the next 9,000 are $0.01 each, and everything above 10,000 is $0.005 each. There are two variants here. "Graduated" tiers apply each rate to the units within that tier only. "Volume" tiers apply the single qualifying rate to all units. This distinction matters enormously for your invoice amounts and you need to be explicit with customers about which model you use.

### Credit-Based Pricing

Customers pre-purchase credits and consume them over time. Different operations can burn credits at different rates. An AI inference might cost 10 credits while a simple API call costs 1 credit. This model gives you flexibility to abstract away infrastructure costs and gives customers spending predictability. Anthropic, OpenAI, and most AI API providers use variations of this.

### Hybrid Pricing

This combines a flat platform fee with usage charges. For example, $99/month base fee plus $0.005 per API call. This is increasingly the norm because it guarantees minimum revenue per customer while still aligning price with value. If you are building something new, hybrid is usually the smartest starting point. Your [usage-based pricing implementation](/blog/usage-based-pricing-implementation) will need to handle both the recurring and variable components cleanly.

## Building Your Metering Infrastructure

Metering is the foundation of usage-based billing. Every billable event in your system needs to be captured, validated, deduplicated, and stored. If your metering layer is unreliable, everything downstream breaks.

### Event Ingestion Pipeline

Your application emits usage events every time a customer performs a billable action. Each event needs a unique idempotency key (to prevent double-counting), a customer identifier, a timestamp, an event type, and the relevant quantity. Send these events to a message queue rather than writing them directly to your billing database. Kafka is the gold standard for high-volume event ingestion. For lower volumes (under 10,000 events per second), Amazon SQS or Google Cloud Pub/Sub work fine and cost less to operate.

The idempotency key is the single most important field. Network failures, retries, and duplicate webhooks will send the same event multiple times. Without idempotency, you will double-bill customers. Store processed event IDs in a fast lookup store like Redis and reject duplicates before they enter your billing pipeline.

### Event Storage

Raw usage events need to be stored for auditing, dispute resolution, and debugging. This is a write-heavy, append-only workload. A time-series database like TimescaleDB or ClickHouse works well here. For simpler setups, a partitioned PostgreSQL table with monthly partitions and proper indexing handles millions of events without issue.

Keep raw events separate from your aggregated billing data. You will aggregate events into billing summaries (daily, hourly, or per-billing-period), and those summaries feed into your rating engine. If a customer disputes a charge, you need the raw events to show exactly what happened.

### Pre-Aggregation

Counting millions of raw events at invoice time is slow and expensive. Instead, pre-aggregate usage into rollup tables. Every hour (or every few minutes for high-volume systems), run an aggregation job that sums usage by customer, event type, and time bucket. Your rating engine then works against these compact summaries rather than scanning every individual event.

![Software developer building a metering and event ingestion pipeline for billing](https://images.unsplash.com/photo-1555949963-ff9fe0c870eb?w=800&q=80)

## The Rating Engine: Turning Usage Into Dollars

The rating engine is the core logic that takes aggregated usage data and applies your pricing model to calculate what each customer owes. This is where tiered pricing, volume discounts, credits, and custom enterprise deals all get resolved into invoice line items.

### How Rating Works

At its simplest, rating multiplies quantity by price. Customer used 50,000 API calls at $0.01 each, so they owe $500. But real-world rating is rarely this clean. You need to handle graduated tiers (where the first 10,000 calls are one price and the next 40,000 are another), committed-use discounts (customer pre-committed to 100,000 calls/month at a lower rate), overage charges (usage beyond the committed amount at a higher rate), and per-customer negotiated pricing that overrides your standard rate card.

Build your rating engine as a standalone module with a clear interface: it takes a customer ID, a billing period, and aggregated usage data as inputs, and outputs a list of rated line items with amounts. This separation is critical because you will call the rating engine in two contexts. First, for real-time usage dashboards that show customers their current spend. Second, for end-of-period invoice generation.

### Rate Card Management

Your pricing will change. You will add new tiers, adjust rates, introduce new billable dimensions, and negotiate custom deals for enterprise accounts. Your rate card system needs to be versioned and time-aware. When you change pricing on March 1st, usage before that date should be rated at the old price. Never mutate pricing data in place. Instead, create new rate card versions with effective dates and let your rating engine select the correct version based on the usage timestamp.

### Enterprise and Custom Pricing

Almost every B2B SaaS company ends up with custom pricing for their larger accounts. Your system needs to support per-customer price overrides, custom discount percentages, committed-use agreements with overage rates, and minimum spend commitments. Store these as customer-specific rate card overrides that take precedence over the default pricing. If this sounds complex, it is. This is one of the strongest arguments for using a purpose-built billing platform like Orb or Metronome rather than building from scratch.

## Invoice Generation, Payment Processing, and Dunning

Once your rating engine produces line items, you need to assemble them into invoices, collect payment, and handle the inevitable failures.

### Invoice Generation

At the end of each billing period (or on a customer's specific billing anchor date), trigger your invoice generation pipeline. Pull all rated line items for the period, apply any credits or prepayment balances, calculate taxes (Stripe Tax, Avalara, or TaxJar handle this), and produce a finalized invoice. The invoice needs to include a line-by-line breakdown of usage, the applicable rates, the subtotal, taxes, credits applied, and the amount due.

Finalization matters. Once an invoice is finalized, it should be immutable. If you need to correct a mistake, issue a credit note or a new corrective invoice. Mutating finalized invoices creates audit nightmares and can violate accounting regulations in many jurisdictions.

### Payment Collection

For most SaaS companies, Stripe handles payment collection. Create a Stripe Invoice object from your rated line items, and Stripe handles charging the customer's stored payment method. For larger enterprise deals, you might need to support invoicing with net-30 or net-60 payment terms, ACH bank transfers (lower fees than credit cards), wire transfers for large amounts, and purchase order workflows. If you are early stage, do not build all of this on day one. Start with credit card billing via Stripe and add alternative payment methods as enterprise customers require them. If you need help evaluating payment platforms, our [comparison of Stripe, Paddle, and Lemon Squeezy](/blog/stripe-vs-paddle-vs-lemon-squeezy) covers the trade-offs.

### Dunning and Failed Payment Recovery

Credit cards fail. They expire, hit spending limits, get flagged for fraud, or simply have insufficient funds. For subscription billing, Stripe's Smart Retries handle most of this automatically. For usage-based billing, you need a more thoughtful approach because the amounts are variable and often larger than predictable subscription fees.

Build a dunning sequence: attempt the charge, wait 3 days, retry, send a notification, wait 5 more days, retry again, send a warning about service downgrade, and finally downgrade or suspend the account after 14 days of failed payment. The key is to be firm but not punitive. A customer whose card expired is not trying to steal from you. Make it easy to update their payment method and resume service.

![Payment processing checkout interface for SaaS billing system](https://images.unsplash.com/photo-1556742049-0cfed4f6a45d?w=800&q=80)

## Revenue Recognition and Financial Compliance

Revenue recognition for usage-based billing is more complex than for flat-rate subscriptions, and you will need to get it right from the start if you plan to raise funding or pursue an acquisition.

### ASC 606 and Usage Revenue

Under ASC 606, you recognize revenue when the performance obligation is satisfied. For usage-based pricing, that means you recognize revenue as the customer consumes the service, not when you invoice or collect payment. If a customer uses $5,000 worth of API calls in March but you invoice them on April 1st and collect payment on April 15th, the $5,000 is March revenue.

This gets complicated with prepaid credits. If a customer buys $10,000 in credits, you cannot recognize that as revenue immediately. You recognize it as the credits are consumed. The unearned portion sits on your balance sheet as deferred revenue. Your billing system needs to track credit consumption in real time to support accurate revenue schedules.

### What Your Finance Team Needs

Your billing system should produce or integrate with systems that generate these outputs: a monthly revenue recognition schedule broken down by customer and product, deferred revenue reports for prepaid credits and commitments, accounts receivable aging reports, usage and revenue trend data for forecasting, and audit trails showing how every invoice amount was calculated from raw usage events.

If you are using a billing platform like Orb or Metronome, they handle much of this reporting. If you are building on Stripe Billing alone, you will need to build revenue recognition logic yourself or integrate with an accounting platform like Sage Intacct or NetSuite. Stripe Revenue Recognition (an add-on product at 0.25% of recognized revenue) automates ASC 606 compliance for Stripe-processed transactions.

### Tax Compliance

Usage-based charges need tax treatment just like any other sale. The complexity is that your tax obligation depends on the customer's location, the type of service (SaaS taxation rules vary by state and country), and whether the customer is a business or consumer. Stripe Tax handles this automatically for Stripe-processed invoices. If you invoice outside of Stripe, integrate Avalara or TaxJar to calculate and collect the correct tax amounts.

## Build vs Buy: Choosing Your Billing Stack

This is the most consequential decision you will make. Building a usage-based billing system from scratch takes 3 to 6 months of engineering time for a basic version and 12+ months for something production-grade. Buying means adopting a platform that handles most of the complexity but comes with platform fees and constraints.

### When to Build on Stripe Billing

Stripe Billing with metered subscriptions works well if your pricing model is simple per-unit pricing, you have fewer than 10,000 billable events per day, you do not need real-time usage dashboards (Stripe aggregates usage asynchronously), and you are comfortable reporting usage to Stripe via their API. Cost: 0.5% of billing volume for Stripe Billing plus standard Stripe processing fees (2.9% + $0.30 per charge). This is the cheapest and fastest path, but it breaks down with complex tiered pricing, high event volumes, or real-time rating requirements.

### When to Use a Billing Platform (Orb, Metronome, Lago)

Purpose-built billing platforms shine when your pricing is complex. Orb (starting around $1,500/month) offers a powerful rate card system, real-time event processing, and handles graduated tiers, package pricing, and matrix pricing out of the box. Metronome (custom pricing, typically $2,000+/month) is built for high-volume usage billing and can handle billions of events. Lago is open-source, so you can self-host it for free (paying only infrastructure costs), but you take on operational responsibility.

The build vs buy math usually favors buying. If a senior engineer costs you $15,000/month fully loaded, and building a billing system takes 4 months, that is $60,000 just in direct engineering cost. A billing platform at $2,000/month pays for itself in 2.5 years, and that ignores the ongoing maintenance cost of a custom system.

### Our Recommendation

For most startups, start with Stripe Billing and simple per-unit metering. As your pricing evolves (and it will), migrate to Orb or Lago when you outgrow what Stripe supports natively. Do not build custom billing infrastructure unless you are a billing company. Your engineering time is better spent on your core product. If you are already running [subscription billing](/blog/how-to-implement-subscription-billing) and want to layer on usage-based components, a hybrid approach with Stripe handling subscriptions and a metering layer handling usage is often the cleanest migration path.

If you are planning a usage-based billing system and want to avoid the expensive mistakes we have seen teams make, we can help you choose the right architecture and tools for your specific pricing model. [Book a free strategy call](/get-started) and let us map out your billing infrastructure together.

---

*Originally published on [Kanopy Labs](https://kanopylabs.com/blog/how-to-build-a-saas-billing-system)*
