Guide

Usage-based billing with Stripe: how we built credits

AI products have a billing problem: every action costs a different amount, and some actions fail. We've solved it three times, with a credit balance in Postcrest and with image allowances in Twelve Lumens and Salestreak. This is how those systems work on top of Stripe, with simplified code and the mistakes worth avoiding.

Martin Balk Founder of Balk.dev Updated 7 min read
On this page
  1. Credits, metering or allowances?
  2. Keep the ledger in your own database
  3. Price every action with cost rules
  4. Spend from balances under a lock
  5. Never charge for failed work
  6. Process every Stripe webhook exactly once
  7. Turn a payment into a balance
  8. Pitfalls we'd warn you about
  9. What runs in Stripe

Credits, metering or allowances?

There are three common ways to charge for usage, and we run two of them in production.

Model How it works Good for Watch out for
CreditsCustomers get or buy a balance; every action costs a number of creditsMany actions with very different costs, such as image, video and voice generationCredits feel abstract, so show the cost of every action before it runs
AllowancesA plan includes a number of units per period, with packs for extra unitsOne main unit customers understand, such as images per property or products per monthUnits with a different weight (a 2K image counts as two) need a clear explanation
Per-unit meteringUsage is reported to Stripe and invoiced afterwardsProducts with a steady, predictable unit, such as infrastructureCustomers only see the bill afterwards, so build usage overviews and alerts

Postcrest uses credits, because its AI workspace offers more than 20 models with very different costs. Twelve Lumens and Salestreak use allowances: images per property or per product, with extra image packs, and the promise of no credits and no tokens. Same Stripe underneath, a very different experience.

Keep the ledger in your own database

Stripe is the source of truth for money: subscriptions, invoices, payments, refunds. Your app should be the source of truth for usage. In Postcrest every grant of credits is a row with a source, an amount, an expiry date and a status:

  • Sources: subscription, package (a top-up the customer bought) and invite (credits granted for inviting someone).
  • Expiry: every grant expires; top-up packs after a set number of weeks.
  • Status: a grant stays pending until its invoice is paid, then becomes active, and moves on to used or expired.
  • Monthly reset: the subscription allowance is counted per billing cycle and doesn't roll over.
class Credit < ApplicationRecord
  belongs_to :organization
  has_many :generations

  enum :source, { subscription: "subscription", package: "package", invite: "invite" }
  enum :status, { payment_pending: "payment_pending", active: "active", used: "used", expired: "expired" }

  scope :available, -> { active.where(expires_at: Time.current..) }

  # Usage is derived, not decremented: only successful, billable generations count.
  def used_amount
    generations.not_failed.billable.sum(:cost)
  end

  def amount_left
    amount - used_amount
  end
end

The interesting choice is that usage is derived rather than decremented. A grant doesn't hold a running balance that jobs subtract from; its usage is the sum of the costs of the successful generations attached to it. A failed generation simply doesn't count, so there is nothing to refund.

Price every action with cost rules

With more than 20 models, prices hard-coded in controllers would turn into chaos. Each model in Postcrest declares a base cost per run and the options that change it:

class Generations::Core::ExampleImageModel < Generations::Core::Base
  cost_per_run 10
  cost_rule :resolution,        multiplier: { "4K" => 2 }
  cost_rule :enable_web_search, addition:   { true => 6 }
end

# One run costs ceil(cost_per_run * product of multipliers) + sum of additions,
# rounded up so a debit never undercharges.
def self.cost_for(field_values = {})
  multiplier = 1.0
  addition   = 0

  cost_rules.each do |field, rule|
    value = field_values[field]
    multiplier *= rule[:multiplier].fetch(value, 1).to_f
    addition   += rule[:addition].fetch(value, 0).to_i
  end

  (cost_per_run * multiplier).ceil + addition
end

Video is priced per output second, with a rate per resolution, so a five-second clip at 1080p costs five times the per-second rate for 1080p. Some costs are only known afterwards, such as the final length of a generated file; those jobs recalculate their cost once the file is in.

The same rules drive the interface. The model picker shows ‘from X credits’ based on the cheapest combination of options, and before anything runs the user sees a breakdown: the base cost, the effect of each option and the total.

Spend from balances under a lock

Two jobs that start in the same second can both see enough balance and both spend it. Wherever you keep a counter that goes down, lock the rows you're about to change. Twelve Lumens consumes purchased image packs oldest first, inside a transaction that locks them:

# Spend purchased image packs oldest first, under a row lock.
def self.consume!(organization, count: 1)
  ImagePackPurchase.transaction do
    purchases = organization.image_pack_purchases.usable.oldest_first.lock # SELECT ... FOR UPDATE
    available = purchases.sum(&:images_remaining)
    raise InsufficientBalance, "needs #{count}, has #{available}" if available < count

    remaining = count
    purchases.each do |purchase|
      break if remaining.zero?

      take = [purchase.images_remaining, remaining].min
      purchase.update!(images_used: purchase.images_used + take)
      remaining -= take
    end
  end
end

Oldest first means the packs that expire soonest are used first, which is what customers expect. Images included in the plan are spent before packs, and every render logs a usage row with its weight: a 2K render counts as two images.

Never charge for failed work

Generative models fail: timeouts, content filters, provider outages. Customers accept that; they don't accept paying for it. There are two ways to make sure they don't.

  • Derive usage from successful jobs. Postcrest only counts generations that didn't fail, so a failure needs no refund at all. Jobs that are stuck for an hour are marked as failed, which takes them out of the count automatically.
  • Refund explicitly. Twelve Lumens charges the allowance up front and gives it back when a render fails, crediting the most recently used pack first and never more than that pack used.
# Called when a render fails: give back exactly what it used.
def self.release!(version:)
  ImageUsage.transaction do
    version.image_usages.lock.each do |usage|
      ExtraImages.refund!(version.organization, count: usage.from_extra) if usage.from_extra.positive?
      usage.destroy!
    end
  end
end

Whichever you choose, make it automatic. A refund that depends on someone in support reading an email is a refund that doesn't happen.

Process every Stripe webhook exactly once

Balances change when money moves, and money moves through webhooks: checkout.session.completed for a top-up, invoice.paid for a renewal. Stripe retries a webhook until you answer with a 2xx, for up to three days in live mode, and can deliver the same event more than once. So your handler has to be safe to run twice.

class StripeWebhooksController < ActionController::API
  def create
    event = Stripe::Webhook.construct_event(
      request.body.read, request.headers["Stripe-Signature"], endpoint_secret
    )
    Billing::WebhookHandler.new(event).process
    head :ok
  rescue JSON::ParserError, Stripe::SignatureVerificationError
    head :bad_request
  end

  private

  def endpoint_secret = Rails.application.credentials.dig(:stripe, :webhook_secret)
end

module Billing
  class WebhookHandler
    def initialize(event)
      @event = event
    end

    # BillingEvent has a unique index on stripe_event_id, so a redelivery is a no-op.
    def process
      record = BillingEvent.find_by(stripe_event_id: @event.id)
      record ||= begin
        BillingEvent.create!(stripe_event_id: @event.id, event_type: @event.type)
      rescue ActiveRecord::RecordNotUnique
        BillingEvent.find_by!(stripe_event_id: @event.id)
      end
      return record unless record.pending?

      case @event.type
      when "checkout.session.completed" then grant_purchased_pack
      when "invoice.paid"               then renew_allowance
      end
      record.mark_processed!
    rescue StandardError => e
      record&.mark_failed!(e)
      raise # answer 5xx so Stripe retries the event
    end
  end
end

Two more rules. Use idempotency keys when your server creates objects in Stripe, so a retried request can't create a second checkout or charge. And change balances and statuses under a row lock, inside the same transaction that records the event.

Turn a payment into a balance

A top-up pack is a one-off Stripe Checkout session in payment mode. We put the organization and the pack in the session's metadata, so the webhook knows exactly what to grant, and we store the Checkout session id on the purchase. That id is the second guard against granting twice.

def handle_checkout_completed
  session = @event.data.object
  return unless session.mode == "payment"
  return if ImagePackPurchase.exists?(stripe_checkout_session_id: session.id) # granted already

  organization = Organization.find(session.metadata["organization_id"])
  pack = ImagePack.find(session.metadata["image_pack_id"])

  ExtraImages.grant!(organization,
                     images: pack.image_count,
                     image_pack: pack,
                     validity_months: pack.validity_months,
                     stripe_checkout_session_id: session.id,
                     stripe_payment_intent_id: session.payment_intent)
end

Grant on the webhook, not on the success page the customer lands on after paying. The success page is a good moment to say thank you, but people close tabs, while Stripe keeps retrying the webhook until your server confirms it. Stripe also sends checkout.session.expired when a Checkout session runs out without a payment (after 24 hours by default), a useful signal that someone abandoned a purchase.

Pitfalls we'd warn you about

  • Double counting workflows. When one action runs several models, bill the individual steps or the total, never both. In Postcrest a workflow shows a total for information, and only its child generations count.
  • Rounding down. Fractions add up over thousands of runs. Round every run up to a whole credit.
  • Unclear expiry. If credits expire, show when, and spend the ones that expire first.
  • Trial abuse. Free usage attracts people who sign up again and again. Postcrest uses a paid trial with a card check, abuse scoring and a one-trial-per-person ledger.
  • Prices that drift from costs. Model prices change. Keep costs in one place (the cost rules), so a price change is a one-line change.
  • Invisible balances. Customers should see what they have, what an action costs and what they've used, without opening an invoice.

What runs in Stripe

Remarkably little of this logic lives in Stripe itself, and that's deliberate. Stripe does what it's great at: Checkout for subscriptions and one-off packs, the customer portal for card changes and cancellations, Stripe Tax and VAT IDs, invoices, refunds and disputes. Salestreak picks euros or dollars based on the visitor's country. Everything that decides what a customer may do lives in the app, next to the jobs that use it.

If you're planning a SaaS with usage-based pricing, design this part first, not last. It's a core part of how we approach SaaS development and Stripe integrations.

Frequently asked questions

Should I use Stripe's usage-based billing or my own credit ledger?

Stripe offers its own usage-based billing, including prepaid credits, and it works well when usage mainly needs to be invoiced. Keep your own ledger when your app has to decide before every job whether it may run, when the cost of an action is calculated in your app, or when you want to show usage in your own interface. Our products keep the ledger in the app and let Stripe handle the payments.

How do I stop customers paying for failed AI generations?

Either count usage only from successful jobs, or refund automatically when a job fails. Also mark jobs that hang as failed, so they don't stay charged forever.

Do credits need to expire?

That's a product decision. Expiry keeps balances current when your prices or models change. If credits expire, say so at purchase, show the date and spend the oldest first.

How do I handle duplicate Stripe webhooks?

Store every event id with a unique index before you handle it, skip events you've already processed, and answer with an error when processing fails, so Stripe tries again.

Can you build usage-based billing for our product?

Yes. We've built credit ledgers, allowances and top-up packs on Stripe for our own products. Read more about our SaaS development.

Planning usage-based pricing?

Tell us what your product does and how you'd like to charge for it. We'll tell you which model fits and what it takes to build it properly.

martin@balk.dev

Typically a reply within one business day.

Useful to mention

  • What you want to build, in a few sentences
  • Who is going to use it
  • Any deadline or launch date
  • Tools and systems it should connect to