We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
From the blog
Tiered Usage Pricing in Elixir: Graduated vs Volume Tiers with Stripe
By Liam Killingback ·
Tiered Usage Pricing in Elixir: Graduated vs Volume Tiers with Stripe
A single overage rate is where most usage-based plans start: 1,000 API calls included, 2 cents for each one after that. It is easy to explain and easy to bill. Then a large customer arrives, uses 400,000 calls a month, and asks for a better rate. You do not want to hand-edit their invoice every month, so you reach for tiered pricing: the more they use, the cheaper each unit gets.
Stripe supports this natively, with two very different tier modes, and choosing the wrong one produces invoices that surprise customers in ways that are hard to walk back. This post covers tiered usage pricing in Elixir from end to end:
- what graduated and volume tiers actually charge, with worked numbers
- a small, tested Elixir module that computes both, so your app can show the same figure Stripe will bill
- creating the tiered metered price in Stripe from Elixir
- metering the usage with Aurora Meter and showing a live cost estimate in LiveView
- the edge cases (the volume cliff, disappearing allowances, immutable prices) that catch teams out
If you are still deciding whether to charge by usage at all, read metered vs seat-based pricing first. If one flat overage rate is enough for now, overage billing in Phoenix is the simpler starting point. This post is the next step after that.
Graduated vs volume: the same tiers, two different bills
Take one tier table for API calls, billed monthly:
| Tier | Units | Price per unit |
|---|---|---|
| 1 | 1 to 1,000 | $0.00 |
| 2 | 1,001 to 10,000 | $0.02 |
| 3 | 10,001 and above | $0.01 |
Graduated tiers price each unit by the tier it falls into, like income tax brackets. A customer who makes 25,000 calls pays:
- 1,000 calls in tier 1 at $0.00 = $0
- 9,000 calls in tier 2 at $0.02 = $180
- 15,000 calls in tier 3 at $0.01 = $150
- Total: $330
Volume tiers find the single tier the total quantity lands in and price every unit at that rate. The same 25,000 calls all land in tier 3:
- 25,000 calls at $0.01 = $250
Same table, same usage, an $80 difference. And the gap is not always in the customer’s favour. Look at a customer with 5,000 calls:
- Graduated: 1,000 free, then 4,000 at $0.02 = $80
- Volume: all 5,000 at $0.02 = $100
Under volume pricing, the “first 1,000 free” allowance vanishes the moment a customer crosses it, because every unit is repriced at the tier the total reached. That is the single most common surprise with volume tiers, and it is why the included-allowance pattern in Aurora Meter Pro’s docs uses a graduated price.
The volume cliff
Volume pricing has a second quirk. Compare 10,000 calls with 10,001:
- 10,000 calls: all at $0.02 = $200
- 10,001 calls: all at $0.01 = $100.01
One more API call halves the bill. Some businesses want that (it rewards customers for committing to more volume), but it also means a customer sitting just under a boundary is better off padding their usage, and your revenue chart develops odd dips at every tier edge. Graduated pricing has no cliff: the total always rises as usage rises.
Which one to pick
- Pick graduated when you have an included allowance, when you want the bill to grow smoothly, and when you want to be able to explain any invoice line by line. This is the right default for almost every developer-facing API and AI product.
- Pick volume when you are pricing commitment, for example “buy in bulk, get a better rate on everything”, and your customers think in terms of “which bracket am I in”. It suits wholesale-style products more than metered APIs.
Whichever you pick, your application should be able to show the customer the number before the invoice does. That means computing it yourself.
A tested tier calculator in Elixir
Stripe is the source of truth for what gets charged. Your app still needs the same arithmetic for the usage page, quota alerts and “projected bill” emails. Keep it in one pure module:
defmodule MyApp.Billing.Tiers do
@moduledoc """
Price a quantity against a Stripe-style tier table.
Amounts are integer cents. Each tier is a map with `:up_to`
(an integer, or `:inf` for the last tier), `:unit_amount` and an
optional `:flat_amount`, mirroring Stripe's price tiers.
"""
@type tier :: %{
required(:up_to) => pos_integer() | :inf,
required(:unit_amount) => non_neg_integer(),
optional(:flat_amount) => non_neg_integer()
}
@spec graduated(non_neg_integer(), [tier()]) :: non_neg_integer()
def graduated(quantity, tiers) do
{total, _floor} =
Enum.reduce_while(tiers, {0, 0}, fn tier, {total, floor} ->
if quantity <= floor do
{:halt, {total, floor}}
else
ceiling = cap(tier.up_to, quantity)
units = ceiling - floor
cost = units * tier.unit_amount + Map.get(tier, :flat_amount, 0)
{:cont, {total + cost, ceiling}}
end
end)
total
end
@spec volume(non_neg_integer(), [tier()]) :: non_neg_integer()
def volume(quantity, tiers) do
tier = tier_for(quantity, tiers)
quantity * tier.unit_amount + Map.get(tier, :flat_amount, 0)
end
@doc "The tier the quantity is in, and how many units until the next one."
@spec position(non_neg_integer(), [tier()]) :: %{tier: pos_integer(), units_to_next: pos_integer() | nil}
def position(quantity, tiers) do
index = Enum.find_index(tiers, &(&1.up_to == :inf or quantity <= &1.up_to))
tier = Enum.at(tiers, index)
%{
tier: index + 1,
units_to_next: if(tier.up_to == :inf, do: nil, else: tier.up_to - quantity + 1)
}
end
defp tier_for(quantity, tiers),
do: Enum.find(tiers, &(&1.up_to == :inf or quantity <= &1.up_to))
defp cap(:inf, quantity), do: quantity
defp cap(up_to, quantity), do: min(up_to, quantity)
end
Every number in the worked examples above becomes a test. If the module and the table ever disagree, the suite says so before a customer does:
defmodule MyApp.Billing.TiersTest do
use ExUnit.Case, async: true
alias MyApp.Billing.Tiers
@tiers [
%{up_to: 1_000, unit_amount: 0},
%{up_to: 10_000, unit_amount: 2},
%{up_to: :inf, unit_amount: 1}
]
test "graduated prices each unit by its own tier" do
assert Tiers.graduated(0, @tiers) == 0
assert Tiers.graduated(1_000, @tiers) == 0
assert Tiers.graduated(5_000, @tiers) == 8_000
assert Tiers.graduated(25_000, @tiers) == 33_000
end
test "volume prices every unit at the tier the total reaches" do
assert Tiers.volume(800, @tiers) == 0
assert Tiers.volume(5_000, @tiers) == 10_000
assert Tiers.volume(25_000, @tiers) == 25_000
end
test "volume has a cliff at each boundary" do
assert Tiers.volume(10_000, @tiers) == 20_000
assert Tiers.volume(10_001, @tiers) == 10_001
end
test "graduated never decreases as usage grows" do
totals = Enum.map(0..30_000//250, &Tiers.graduated(&1, @tiers))
assert totals == Enum.sort(totals)
end
test "position reports the tier and the distance to the next one" do
assert Tiers.position(9_500, @tiers) == %{tier: 2, units_to_next: 501}
assert Tiers.position(50_000, @tiers) == %{tier: 3, units_to_next: nil}
end
end
The monotonic property test is worth keeping even if you never use volume pricing: it fails immediately if someone edits the table and the tiers fall out of order, which would otherwise produce negative unit counts and a bill that shrinks as usage grows.
If your unit prices go below a cent (AI tokens often do), Stripe accepts unit_amount_decimal. Store the amounts as integer micro-dollars or use Decimal in this module rather than floats, and round once, at the end.
One tier table, two consumers
The tier table should live in exactly one place in your code, so the Stripe price and the in-app estimate cannot drift. Put it in config:
# config/config.exs
config :my_app, :api_call_pricing,
mode: :graduated,
tiers: [
%{up_to: 1_000, unit_amount: 0},
%{up_to: 10_000, unit_amount: 2},
%{up_to: :inf, unit_amount: 1}
]
Creating the tiered metered price in Stripe
Usage-based prices in Stripe are attached to a Billing Meter, which sums the events you send for each customer. Create the meter once (event name api_calls, sum aggregation, customer key stripe_customer_id, value key value), then create a tiered recurring price that points at it. A one-off Mix task keeps this reproducible across test mode and live mode:
defmodule Mix.Tasks.Billing.CreateTieredPrice do
use Mix.Task
@shortdoc "Creates the tiered metered price for API calls in Stripe"
def run([product_id, meter_id]) do
Mix.Task.run("app.config")
Application.ensure_all_started(:req)
pricing = Application.fetch_env!(:my_app, :api_call_pricing)
tier_params =
pricing[:tiers]
|> Enum.with_index()
|> Enum.flat_map(fn {tier, i} ->
[
{"tiers[#{i}][up_to]", to_string(tier.up_to)},
{"tiers[#{i}][unit_amount]", to_string(tier.unit_amount)}
]
end)
params =
[
{"product", product_id},
{"currency", "usd"},
{"lookup_key", "api_calls_tiered_v1"},
{"billing_scheme", "tiered"},
{"tiers_mode", to_string(pricing[:mode])},
{"recurring[interval]", "month"},
{"recurring[usage_type]", "metered"},
{"recurring[meter]", meter_id}
] ++ tier_params
%{status: 200, body: body} =
Req.post!("https://api.stripe.com/v1/prices",
auth: {:bearer, System.fetch_env!("STRIPE_SECRET_KEY")},
form: params
)
Mix.shell().info("Created #{body["id"]} (#{body["tiers_mode"]})")
end
end
to_string(:inf) produces "inf", which is exactly what Stripe expects for the last tier’s up_to. Run it against your test-mode key first:
mix billing.create_tiered_price prod_123 mtr_456
Two Stripe rules worth knowing before you ship this. First, tiers must be in ascending order and the last one must be inf. Second, a price’s amounts and tier mode cannot be edited after creation. Changing the tiers means creating a new price (note the _v1 lookup key) and moving subscriptions to it, which is the same problem as raising prices, covered in grandfathered pricing in Phoenix.
Metering the usage with Aurora Meter
The tiers only matter if the count is right. Aurora Meter is a free, MIT-licensed Elixir library that counts usage on an ETS hot path, enforces plan limits and persists deltas to Postgres. Declare the feature on the plan that carries the tiered price:
defmodule MyApp.Plans do
use AuroraMeter.Plans
plan :free do
price 0
limit :api_calls, 1_000, :hard
end
plan :scale do
price 4_900
metered :api_calls, included: 1_000, unit_price: 2
feature :api_access, true
end
end
metered means the customer is never blocked at 1,000; usage past the allowance is overage. Then count each call where it happens:
def call(conn, _opts) do
org = conn.assigns.current_org
AuroraMeter.track(org, :api_calls)
conn
end
track/2 is an atomic ETS increment, so it is safe on every request. Be honest with yourself about one detail: the plan DSL describes a single overage rate, and that rate drives the core’s built-in estimate fields. With more than one paid tier, the plan’s unit_price is a simplification (use the first paid tier’s rate), and the real arithmetic belongs in MyApp.Billing.Tiers and in Stripe. That split is deliberate: the plan defines the dashboard estimate, Stripe defines the actual charge.
Reporting usage to the tiered price
Getting the counter onto the invoice is the part Aurora Meter Pro handles. Its usage reporter reads the persisted counters, computes delta = counter - last_reported per billing window, and sends those deltas to the Billing Meter with an idempotency identifier per window, so a retried job does not bill the same calls twice. Point it at the tiered price:
config :aurora_meter,
provider: AuroraMeter.Pro.Stripe,
period_source: AuroraMeter.Pro.Period
config :aurora_meter_pro,
stripe_prices: %{scale: "price_scale_flat"},
stripe_metered_prices: %{scale: ["price_api_calls_tiered"]},
stripe_meters: %{api_calls: "api_calls"}
Because the meter sums deltas over the billing period, Stripe sees the period total at invoice time, and applies whichever tier mode the price uses. The reporter does not need to know whether the tiers are graduated or volume, and switching modes later is a Stripe price change, not a code change. Pro also aligns Aurora Meter’s periods to the Stripe subscription period, so the number in your app and the number on the invoice cover the same days.
A live cost estimate in LiveView
Customers on tiered pricing want to see two things: what they owe so far, and how close they are to the next, cheaper tier. Aurora Meter broadcasts usage changes over PubSub, so the estimate updates as calls come in:
defmodule MyAppWeb.BillingLive do
use MyAppWeb, :live_view
alias MyApp.Billing.Tiers
@impl true
def mount(_params, _session, socket) do
org = socket.assigns.current_org
if connected?(socket), do: AuroraMeter.LiveView.subscribe(org)
{:ok,
socket
|> assign(pricing: Application.fetch_env!(:my_app, :api_call_pricing))
|> assign(quota: AuroraMeter.quota(org, :api_calls))
|> assign_estimate()}
end
@impl true
def handle_info({:aurora_meter, :usage, _payload} = message, socket) do
socket = AuroraMeter.LiveView.assign_quota(message, socket, :quota, :api_calls)
{:noreply, assign_estimate(socket)}
end
defp assign_estimate(socket) do
%{pricing: pricing, quota: quota} = socket.assigns
used = quota.used
cents =
case pricing[:mode] do
:graduated -> Tiers.graduated(used, pricing[:tiers])
:volume -> Tiers.volume(used, pricing[:tiers])
end
assign(socket, used: used, cents: cents, position: Tiers.position(used, pricing[:tiers]))
end
end
<div class="space-y-2">
<p><%= @used %> API calls this period</p>
<p class="text-2xl font-semibold">
Usage so far: $<%= :erlang.float_to_binary(@cents / 100, decimals: 2) %>
</p>
<p :if={@position.units_to_next}>
Tier <%= @position.tier %>. <%= @position.units_to_next %> more calls and
every further call gets cheaper.
</p>
</div>
Label it “usage so far” or “estimate”, not “your bill”. Taxes, credits, proration and discounts are applied by Stripe, and the estimate does not know about them. The real-time usage dashboard post covers the rest of the page: history charts, per-feature meters and alerts.
Edge cases to decide before launch
- Mid-period plan changes. If a customer moves from a flat plan to the tiered one halfway through a month, decide whether the tiers apply to the whole month’s usage or only to usage after the switch. Stripe’s default is to start a new billing period on some changes and not others, so test it with a test clock rather than reasoning about it.
- Annual plans. Tiers are applied per billing period of the metered price. If you sell annual plans with monthly limits, keep the metered price monthly so the tiers reset each month. See annual plans with monthly usage limits.
- Refunds and corrections. Correcting usage after the fact changes which tier a customer landed in. A correction that moves them back below a boundary changes the price of every unit under volume pricing, so prefer graduated if you expect to issue corrections often.
- Alerts at tier boundaries. “You are 500 calls from a cheaper rate” is a useful email, and so is “you have used your free allowance”. Quota alerts in Phoenix shows how to send each once per period.
-
Verify a real invoice. A successful API call to create the price proves nothing about the invoice. Run one subscription through a Stripe test clock, push usage across two tier boundaries, advance the clock and read the invoice line items against your
Tierstests.
Summary
Tiered usage pricing in Elixir comes down to three decisions and one discipline:
- Pick graduated by default. It keeps the included allowance, never drops when usage rises, and is easy to explain. Use volume only when you are deliberately pricing commitment.
- Keep one tier table in config and use it for both the Stripe price and the in-app estimate.
- Let Stripe apply the tiers to a summed Billing Meter, and send it idempotent deltas so retries never double-bill.
- Test the arithmetic with the exact numbers you would put in your pricing page, and verify one real test-clock invoice before launch.
The free Aurora Meter core (MIT, on GitHub) gives you the counting, plan limits and live LiveView updates today. When you want the usage reported to Stripe Billing Meters, subscription-aligned periods and reconciliation without writing the reporter yourself, Aurora Meter Pro is licensed per app from $99 a month, with a 14-day free trial (one trial per customer). And if you would rather start from a complete metered-API product, the Aurora API Starter template ships API keys, metering and billing pages on the core already.