We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
From the blog
Rollover Credits in Phoenix: Carry Unused Usage Into the Next Billing Period
By Liam Killingback ·
Rollover Credits in Phoenix: Carry Unused Usage Into the Next Billing Period
Every usage-based product eventually gets the same support email. “I paid for 5,000 credits in March and used 800. Do I really lose the other 4,200?” If the answer is yes, a quiet month feels like being robbed. If the answer is “they all carry over forever”, you have just created a liability that grows every month and a customer who never needs to upgrade.
Rollover credits are the middle answer: unused allowance carries into the next billing period, up to a cap. It is a small pricing feature with a surprising number of ways to get wrong in code. This guide covers the policy choices, a hand-rolled Ecto version so you can see where the bugs live, and then the same thing in Aurora Meter, where capped rollover is one line in a plan.
If you are new to the credit ledger itself, read pay-as-you-go billing with prepaid credits first. This post assumes you know what a grant and a debit are.
Three rollover policies, and why the capped one wins
No rollover. The allowance resets each period. Simple to build and easy to explain, but it punishes uneven usage. Customers with seasonal or bursty workloads (a tax tool, a batch pipeline, anything agency-shaped) churn or downgrade after their first quiet month.
Unlimited rollover. Everything unused accumulates. Customers love it. Your accountant does not, because unused prepaid credit is something you owe, and it compounds. It also removes the upgrade pressure: a customer who banked 40,000 credits over a slow winter has no reason to move up a tier in spring.
Capped rollover. Carry over at most a fixed amount (or one period’s worth), and expire it at the end of the next period. A quiet month is forgiven, a quiet year is not. The liability has a hard ceiling per customer, and it is easy to say on a pricing page: “Unused credits roll over for one month, up to 1,000.”
Most products that offer rollover land on the capped version. The rest of this post builds that.
Why a resetting quota cannot do this
The obvious first attempt is to take your monthly limit and make the reset smarter. In Aurora Meter a hard limit looks like this:
plan :studio do
price 4_900
limit :ai_generations, 5_000, :hard
end
A limit counts events inside a period. When the period turns over, the count starts again at zero and the ceiling is 5,000 again. There is nowhere in that model to put “plus 800 left over from last month”, and bolting one on means the limit is no longer a property of the plan. It becomes a per-customer, per-period number with its own history.
That is the tell. The moment an allowance can be carried, expired, topped up or refunded, it has stopped being a quota and become a balance. Balances belong in a ledger.
The hand-rolled version, and where it breaks
Here is a reasonable first implementation: one row per customer per period, written when the period starts.
defmodule MyApp.Billing.Allowance do
use Ecto.Schema
schema "allowances" do
field :org_id, :id
field :period_key, :string # "2026-11"
field :granted, :integer # this period's plan allowance
field :carried, :integer # rolled over from the previous period
field :used, :integer, default: 0
timestamps()
end
end
With a unique index on (org_id, period_key), the period turnover job is:
defmodule MyApp.Billing.Rollover do
import Ecto.Query
alias MyApp.Billing.Allowance
alias MyApp.Repo
@allowance 5_000
@rollover_cap 1_000
def open_period(org_id, period_key, previous_key) do
Repo.transaction(fn ->
previous =
Repo.one(
from a in Allowance,
where: a.org_id == ^org_id and a.period_key == ^previous_key,
lock: "FOR UPDATE"
)
carried =
case previous do
nil ->
0
a ->
# last period's carry is spent first, so only usage beyond it
# came out of last period's own grant
used_from_grant = max(a.used - a.carried, 0)
unused_grant = max(a.granted - used_from_grant, 0)
min(unused_grant, @rollover_cap)
end
Repo.insert!(
%Allowance{org_id: org_id, period_key: period_key, granted: @allowance, carried: carried},
on_conflict: :nothing,
conflict_target: [:org_id, :period_key]
)
end)
end
end
It is forty lines and it mostly works. Look at what it had to get right, and what it still gets wrong.
Accumulation. The carried calculation spends last month’s carried amount first (a.used - a.carried) and only rolls over what is left of last month’s own grant. Write it as granted + carried - used instead, which is the natural first draft, and rollover compounds: two idle months leave 2,000 carried, then 3,000, and the cap never bites because it is applied to each step separately. This is the single most common rollover bug.
Double grants. The job will run twice. A deploy restarts it mid-run, two nodes both fire the cron, an operator re-runs it by hand. The unique index plus on_conflict: :nothing is what makes the second run harmless. Without both, a customer gets two allowances.
The cap is read from code. @rollover_cap is whatever the module says today. Change it from 1,000 to 500 and deploy on the 30th, and customers who were promised 1,000 last month get 500. The cap that applies to a period should be the one that was in force when that period was granted.
Missed periods. If the job is down for a few days across a boundary, or a customer is inactive for three months, the “previous” row does not exist and the chain is broken.
Spending is not shown at all. Every request has to increment used atomically, refuse when granted + carried - used reaches zero, and cope with retries. And the day you add paid top-ups, you need a rule for which money is spent first.
Each of these is fixable. Together they are a ledger, and you are now writing one.
Capped rollover in Aurora Meter
Aurora Meter’s free core has a credit ledger made of lots: each grant is its own row with an amount, a category and an optional expiry. A plan can carry a recurring allowance that arrives every period, and rollover is an option on it:
defmodule MyApp.Plans do
use AuroraMeter.Plans
plan :studio do
price 4_900
counter :ai_generations
recurring_credits :monthly_allowance,
amount: 5_000_000,
rollover: 1_000_000
end
end
Amounts in the ledger are integer millionths of a dollar, so 5_000_000 is $5.00 of included usage and 1_000_000 caps the carry at $1.00. Working in money, not in “credits”, is deliberate: it lets one allowance cover several features at different prices. If an AI generation costs you a tenth of a cent, the $5 allowance is 5,000 generations.
Note that :ai_generations is a counter, not a limit. It is measured for the dashboard and never blocks anything. The balance is what stops a customer, which is the whole point of moving from a quota to a ledger.
By default a recurring allowance is granted as promotional credit that expires at the period end. That default is what makes rollover meaningful: without an expiry, nothing would ever be “unused at the end of the period”.
What the rollover option actually promises
From the lots and recurring allowances guide, the rules are:
- It carries at most the cap of the previous period’s unused allowance into the next one.
- It does not accumulate. With a $1 cap, two idle periods leave the third holding its own allowance plus $1, never plus $2. This is the bug from the hand-rolled version, closed.
- The cap comes from the previous period’s stored policy, not from your compiled plan. Editing the number changes future periods and does not retroactively change what somebody already carried.
- Nonsense is refused at compile time. A rollover on an allowance that does not expire at the period end is a compile error, because there would be nothing to roll.
Granting each period, exactly once
One function issues whatever is due:
AuroraMeter.Credits.Recurrences.run(limit: 500)
# {:ok, %{counts: %{examined: 40, granted: 12, duplicate: 28}}}
It is safe to run from every node as often as you like. A period gets one grant, enforced inside the balance row’s lock by two independent guards: a unique row per tenant and period, and a unique reference on the ledger transaction. That is the on_conflict: :nothing trick from earlier, done twice because it is money.
A tenant who is three periods behind gets those three in order, each granted and expired in the same transaction, then the live one. A brand new tenant gets the current period only. There is no back pay and no pro rating, which is worth saying on your pricing page so nobody expects a half allowance for joining mid-month.
If you use Oban, you do not call it yourself. The optional worker runs hourly:
config :my_app, Oban,
plugins: [{Oban.Plugins.Cron, crontab: AuroraMeter.Oban.cron_entries()}]
That schedule includes AuroraMeter.Oban.RecurringGrants for the grants and AuroraMeter.Oban.CreditExpiry for expiring what was not carried.
Spending the allowance
Spending is the ordinary ledger API. When the cost is known up front:
def generate(org, prompt, request_id) do
case AuroraMeter.Credits.debit(org, 1_000, "gen:#{request_id}") do
{:ok, _txn} ->
AuroraMeter.track(org, :ai_generations)
MyApp.AI.generate(prompt)
{:error, :insufficient_credits} ->
{:error, :out_of_credits}
{:error, :duplicate_reference} ->
{:error, :already_processed}
end
end
The third argument is a reference, and it is the idempotency key. A retried request with the same id is not charged twice, which matters more with rollover than without: a double charge now eats into next month as well. Idempotent usage tracking covers choosing those keys.
When the cost is only known afterwards (token counts, pages parsed), hold an estimate and settle the real figure:
{:ok, _} = AuroraMeter.Credits.hold(org, 30_000, "doc:#{doc.id}")
# ...do the work, learn the true cost...
{:ok, _} = AuroraMeter.Credits.settle("doc:#{doc.id}", 32_100)
Rollover and paid top-ups in the same wallet
Sooner or later a customer on the $49 plan runs out on the 20th and wants to buy more without upgrading. Now the wallet holds two kinds of money: the plan allowance (free with the subscription, expires) and a top-up (paid for, should not vanish).
AuroraMeter.Credits.grant(org, 10_000_000, reference: "stripe:pi_3abc")
A plain grant like this is a paid lot with no expiry. The ledger then spends in a fixed order: promotional before paid, earliest expiry first, oldest grant first. For rollover that order is exactly what you would choose by hand. The expiring allowance is used up before the customer’s own money is touched, so cash they paid is still there after the period turns.
The order is not configurable, on purpose. A configurable spend order is a configurable answer to “what did you charge me for”, and support needs that question to have one answer. When someone does ask, this returns the lots that paid for a specific request:
AuroraMeter.Credits.Lots.allocations(org, reference: "gen:abc123")
Expiry is equally narrow. Expiring a lot moves what is left of that one lot into its expired bucket. It does not touch the next lot, money reserved by an open hold, or anything the customer paid for.
Showing it to the customer
Rollover only reduces churn if customers can see it. A usage page should answer three questions: what do I have, how much of it expires, and when. The balance gives the totals:
AuroraMeter.Credits.balance(org)
# %{
# balance: 16_200_000, held: 0, available: 16_200_000,
# spendable: 16_200_000,
# promotional: 6_200_000, promotional_spendable: 6_200_000,
# debt: 0, expired: 0, currency: "USD", ...
# }
Here promotional is the plan allowance including what rolled over, and the difference between balance and promotional is paid credit that does not expire. In a LiveView:
def mount(_params, _session, socket) do
org = socket.assigns.current_org
balance = AuroraMeter.Credits.balance(org)
{:ok,
assign(socket,
expiring: AuroraMeter.Credits.Money.format(balance.promotional),
kept: AuroraMeter.Credits.Money.format(balance.balance - balance.promotional),
lots: AuroraMeter.Credits.Lots.list(org)
)}
end
Lots.list/1 returns the open lots in spend order, so the first row is the money that will be used next. Render that list with each lot’s expiry and you have the “use it or lose it” line that makes people come back before the period ends. Pair it with quota alerts at 80% and 100% for the opposite case.
The Stripe side stays boring
Rollover does not need anything clever in Stripe. The subscription is a flat recurring price ($49 a month). The allowance, the carry and the expiry all live in your ledger, and Stripe never hears about them. Top-ups are one-off payments that become paid grants, keyed on the PaymentIntent id.
What you do need is for the plan and the billing period in your app to follow the Stripe subscription, so the allowance stops when a customer cancels and moves when they change plan. You can write those webhook handlers yourself. Aurora Meter Pro does it for you: it syncs subscriptions from Stripe with out-of-order webhook protection, sells top-ups through Checkout, and reports metered usage to Stripe Billing Meters if you also charge overage.
Policies to decide before you ship
How big is the cap? One period’s allowance is generous. Twenty percent of it is the common conservative choice. Whatever you pick, it is the maximum liability per customer, so multiply by your customer count and check you are comfortable.
Does rollover survive a downgrade? The simplest honest rule is that the carry is computed from the period that just ended, on the plan that period was granted under, and the new plan’s allowance is added on top.
What about annual plans? Customers who pay yearly usually still get a monthly allowance, with rollover between months. Annual plans with monthly usage limits covers running a monthly cadence inside a yearly subscription.
What happens on cancel? Allowance credit should end with the subscription. Paid top-ups are a separate decision, and in many places a legal one. Keep them as separate lots so you can answer either way.
Say it plainly. “Up to 1,000 unused credits roll over for one month” is a sentence customers understand. “Credits may be eligible for carry-forward” is a support ticket.
Testing rollover
Rollover bugs show up at period boundaries, which is the worst place to find them in production. The cases worth a test each:
- A period with unused allowance below the cap carries all of it.
- A period with unused allowance above the cap carries exactly the cap.
- Two idle periods in a row carry the cap once, not twice.
- Running the recurring grant twice for the same period grants once.
- A paid top-up is untouched when the allowance expires.
- Spending drains the expiring allowance before the top-up.
Testing usage-based billing in ExUnit shows how to drive periods and expiry from a test without waiting for a real month to pass.
Or skip the plumbing
Everything in the Aurora Meter half of this post, the lots, the recurring allowance, capped rollover, expiry and the spend order, is in the free MIT core. Read the core docs or the source on GitHub.
When you want the Stripe side handled as well, Aurora Meter Pro adds subscription sync, Checkout top-ups and usage reporting. It is licensed per app from $99 a month, with a 14-day free trial that each customer can claim once.
Summary
- Capped rollover forgives a quiet period without building an unbounded liability or removing the reason to upgrade.
- A quota cannot roll over. Once an allowance can be carried or expired it is a balance, and it belongs in a ledger.
- The classic bug is accumulation: rolling over last month’s carry as well as last month’s grant. Carry only the unused part of the previous period’s own allowance, capped.
- Grant once per period with a database-level guard, because the job will run twice.
- Store the cap with the period, so changing your plan does not rewrite what customers were promised.
- Spend expiring credit first, and keep paid top-ups in their own lots so expiry never touches them.
-
In Aurora Meter that is
recurring_credits :monthly_allowance, amount: ..., rollover: ...and a scheduledRecurrences.run/1.