We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
From the blog
Storage Billing in Phoenix: Meter GB-Months Instead of Counting Events
By Liam Killingback ·
Storage Billing in Phoenix: Meter GB-Months Instead of Counting Events
Most usage metering advice assumes an event: a request, a generation, a message sent. You count each one and add them up. Storage does not work that way. A customer who uploads 40 GB on the 1st and deletes it on the 2nd has not used “40 GB this month”, and a customer who has held 40 GB all month has done nothing at all in the last 30 days that you could count.
Storage billing in Phoenix needs a different shape: a level that you sample over time, a limit that applies to the level right now, and a bill that reflects how much was stored for how long. This post builds all three: tracking stored bytes transactionally, enforcing a plan’s storage cap at upload time without a race, sampling GB-days with Oban, and getting the result onto a Stripe invoice. The metering examples use Aurora Meter, the free MIT metering library for Phoenix, and each step says what it does so you can hand-roll it.
Flows and levels
There are two kinds of usage, and mixing them up is the root of most storage billing bugs.
A flow is something that happens: API calls, tokens, emails. The usage for a period is the sum of the events in it, and a new period starts from zero.
A level is something that is: stored bytes, active seats, provisioned databases. It does not reset at the start of a month, it can go down as well as up, and its value at any one moment says nothing about the month as a whole.
A counter is the right tool for a flow. To bill a level, you convert it into a flow by sampling it: once a day, record how much is stored. The sum of those samples over a billing period is measured in GB-days, and it is an ordinary counter that resets each period and only goes up.
Here is the arithmetic. A customer stores 30 GB for the first 10 days of a 30-day month, then 50 GB for the remaining 20:
30 GB x 10 days = 300 GB-days
50 GB x 20 days = 1,000 GB-days
total = 1,300 GB-days
average = 1,300 / 30 = 43.3 GB-months
That 43.3 figure is what cloud providers call GB-months, and it is the fair answer: the customer pays for the time-weighted average, not the peak (50) and not whatever happened to be there on invoice day.
So storage needs two numbers with two different jobs:
| Number | What it is | Where it lives | Used for |
|---|---|---|---|
| Stored bytes | The level, right now | Your own table | Enforcing the cap, showing “12.4 of 50 GB” |
| GB-days | The sampled flow | A metering counter | Billing, usage history |
Keep the level in your own table
The current level is your application’s data, and it has to be exact. Do not compute it with SUM(size) on every upload, and do not keep it in a cache that can drift. Keep a running total on the organisation and change it in the same transaction that creates or deletes a file.
defmodule MyApp.Repo.Migrations.AddStorageToOrgs do
use Ecto.Migration
def change do
alter table(:orgs) do
add :storage_bytes, :bigint, null: false, default: 0
add :storage_carry_bytes, :bigint, null: false, default: 0
add :storage_sampled_on, :date
end
create constraint(:orgs, :storage_bytes_not_negative, check: "storage_bytes >= 0")
end
end
storage_bytes is the level. The other two columns belong to the sampler and are explained below. The check constraint is cheap insurance: a double delete that would take the total below zero fails loudly instead of handing someone free storage.
Enforce the storage cap without a race
A plan’s storage allowance is a property of the plan, so declare it next to the other plan values. In Aurora Meter that is a feature with a value:
defmodule MyApp.Plans do
use AuroraMeter.Plans
plan :free do
price 0
feature :storage_gb, 1
end
plan :team do
price 4_900
feature :storage_gb, 50
metered :storage_gb_days, included: 1_550, unit_price: 1
end
end
feature :storage_gb, 50 is the cap on the level. metered :storage_gb_days is the billing counter, and it comes back later.
The obvious check (“read the total, compare, then insert”) is wrong under concurrency. Two uploads that each fit can both pass the check and together exceed the cap. The fix is to make the check and the increment one statement, so Postgres decides:
defmodule MyApp.Storage do
import Ecto.Query
alias Ecto.Multi
alias MyApp.Accounts.Org
alias MyApp.Repo
alias MyApp.Storage.StoredFile
@gb 1_073_741_824
def cap_bytes(org), do: AuroraMeter.feature_value(org, :storage_gb, 1) * @gb
def used_bytes(org), do: Repo.one!(from o in Org, where: o.id == ^org.id, select: o.storage_bytes)
def create_file(org, attrs) do
size = Map.fetch!(attrs, :size)
cap = cap_bytes(org)
Multi.new()
|> Multi.run(:reserve, fn repo, _changes ->
query =
from o in Org,
where: o.id == ^org.id and o.storage_bytes + ^size <= ^cap
case repo.update_all(query, inc: [storage_bytes: size]) do
{1, _} -> {:ok, size}
{0, _} -> {:error, :storage_limit_exceeded}
end
end)
|> Multi.insert(:file, StoredFile.changeset(%StoredFile{org_id: org.id}, attrs))
|> Repo.transaction()
end
def delete_file(%StoredFile{} = file) do
Multi.new()
|> Multi.delete(:file, file)
|> Multi.update_all(
:release,
from(o in Org, where: o.id == ^file.org_id),
inc: [storage_bytes: -file.size]
)
|> Repo.transaction()
end
end
The update_all only matches a row if the new total fits. The row lock it takes makes concurrent uploads queue behind each other, so the second one sees the first one’s bytes. If the insert fails, the whole transaction rolls back and the reservation goes with it.
AuroraMeter.feature_value/3 reads the plan from an ETS cache, so asking for the cap costs no database query.
Check before the bytes arrive
Refusing a 2 GB upload after the customer has waited for it to finish is correct and unkind. With LiveView uploads you know the size before anything is sent, so check up front and keep create_file/2 as the authority:
def handle_event("validate", _params, socket) do
org = socket.assigns.current_org
pending = Enum.sum(for entry <- socket.assigns.uploads.files.entries, do: entry.client_size)
remaining = MyApp.Storage.cap_bytes(org) - MyApp.Storage.used_bytes(org)
socket =
if pending > remaining do
put_flash(socket, :error, "These files need more storage than your plan has left.")
else
clear_flash(socket)
end
{:noreply, socket}
end
client_size is reported by the browser, so treat it as a hint. The object’s real size, read from S3 or the filesystem once the upload completes, is what goes into create_file/2. If uploads go straight to object storage with presigned URLs, create the file record (and take the reservation) when you sign the URL, and delete it if the upload never completes.
Sample the level into GB-days
Now the billing half. Once a day, for each organisation, add the current level to a counter. Three details make the difference between a sampler that is roughly right and one you can put on an invoice.
Do not round each sample. A customer holding 300 MB rounds down to 0 GB every single day and is never billed, while one holding 1.6 GB is rounded to 2 and overpays by 25%. Carry the remainder forward instead: add today’s bytes to yesterday’s leftover, bill the whole gigabytes, keep the rest.
Do not double count. A retried job must not add a second sample for the same day.
Do not skip days. If the scheduler was down on Tuesday, Wednesday’s run should account for both days.
All three are handled by recording, on the org row, the last day sampled and the carried bytes, and updating them in the same transaction as the decision to bill:
defmodule MyApp.Workers.SampleStorage do
use Oban.Worker, queue: :metering, max_attempts: 5
import Ecto.Query
alias MyApp.Accounts.Org
alias MyApp.Repo
@gb 1_073_741_824
@impl Oban.Worker
def perform(%Oban.Job{args: %{"org_id" => org_id}}) do
today = Date.utc_today()
{:ok, gb_days} =
Repo.transaction(fn ->
org = Repo.one!(from o in Org, where: o.id == ^org_id, lock: "FOR UPDATE")
days = days_owed(org.storage_sampled_on, today)
total = org.storage_bytes * days + org.storage_carry_bytes
org
|> Ecto.Changeset.change(
storage_sampled_on: today,
storage_carry_bytes: rem(total, @gb)
)
|> Repo.update!()
div(total, @gb)
end)
if gb_days > 0, do: AuroraMeter.track(org_id, :storage_gb_days, gb_days)
:ok
end
defp days_owed(nil, _today), do: 1
defp days_owed(last, today), do: max(Date.diff(today, last), 0)
end
Run it for the second time on the same day and days_owed/2 is zero, the carry is unchanged and nothing is tracked. Run it after a missed day and it bills two days at the current level, which is an approximation (the level may have changed in between) but a far better one than billing nothing.
There is one honest gap. The database commit and the track/3 call are not one atomic step, so a crash between them loses that day’s sample for that organisation. The error is in the customer’s favour and limited to a day. If you need better than that, write the sample to an outbox table inside the transaction and track from there, as described in idempotent usage tracking in Elixir.
A daily cron job fans out one sampling job per organisation:
# config/config.exs
config :my_app, Oban,
plugins: [
{Oban.Plugins.Cron, crontab: [{"5 0 * * *", MyApp.Workers.EnqueueStorageSamples}]}
]
defmodule MyApp.Workers.EnqueueStorageSamples do
use Oban.Worker, queue: :metering
import Ecto.Query
@impl Oban.Worker
def perform(_job) do
from(o in MyApp.Accounts.Org, where: o.storage_bytes > 0 or o.storage_carry_bytes > 0, select: o.id)
|> MyApp.Repo.all()
|> Enum.map(&MyApp.Workers.SampleStorage.new(%{org_id: &1}))
|> Oban.insert_all()
:ok
end
end
How often to sample
Daily sampling is the pragmatic default, and it has a known weakness: a customer can upload 500 GB at 00:10 and delete it at 23:50 without ever being sampled. If your product is closer to a backup service than a document tool, sample hourly and meter GB-hours. The code is the same with a smaller unit. Going finer than hourly rarely pays for itself. For exact time-weighting you would record every change in level with a timestamp and integrate, which is what the large cloud providers do with byte-hours, and it is a lot of machinery for a difference most customers never notice.
Samples are taken in UTC, and the free core’s billing periods are UTC calendar months, so a sample taken at 00:05 UTC on the 1st lands in the new period.
The allowance, in the right unit
Back to the plan line:
metered :storage_gb_days, included: 1_550, unit_price: 1
included and unit_price have to be in the sampled unit. The Team plan includes 50 GB, months have up to 31 days, so the allowance is 50 x 31 = 1,550 GB-days. Sizing it for the longest month means a customer sitting exactly at 50 GB is never charged overage, in any month. The alternative (50 x 30) charges them for 50 GB-days every January, which is a support ticket waiting to be written.
unit_price is an integer number of cents, so 1 means one cent per GB-day past the allowance, or about 30 cents per GB-month. If your price per GB-month is lower than that, a cent per GB-day is too coarse. Metering in a finer unit only makes that worse, so keep the counter as it is and set the real price in Stripe, where a metered price accepts fractions of a cent.
Notice what the metered counter does not do: it never blocks. The hard stop for storage is the cap on the level in create_file/2. If you want customers to be able to exceed 50 GB and pay for it, raise or remove that cap for the plan and let the GB-days overage carry the charge. Decide which of the two you are selling and say so on the pricing page. Overage billing in Phoenix covers that choice, including abuse ceilings.
Show customers both numbers
Customers think in the level (“how full am I?”), and invoices are in GB-days. Show both, and label them.
def mount(_params, _session, socket) do
org = socket.assigns.current_org
if connected?(socket), do: AuroraMeter.LiveView.subscribe(org)
{:ok,
assign(socket,
used_bytes: MyApp.Storage.used_bytes(org),
cap_bytes: MyApp.Storage.cap_bytes(org),
billing: AuroraMeter.quota(org, :storage_gb_days),
history: AuroraMeter.history(org, :storage_gb_days, days: 30)
)}
end
AuroraMeter.quota/2 returns the period’s GB-days, the included amount and the overage so far. AuroraMeter.history/3 returns one row per day, and because each day’s value is that day’s sample, charting it gives you a storage-over-time graph for free. Divide the period’s GB-days by the days elapsed and you can show “average this month: 43.3 GB”, which is the number the invoice will be based on.
Bill it through Stripe
On the Stripe side, storage is an ordinary metered price on a Billing Meter with a sum aggregation. Every GB-day you report adds to the period total, and a graduated price gives the first 1,550 units at zero and the rest at your per-unit rate. Nothing in Stripe needs to know the number came from sampling a level.
What you do need is for the usage that reaches Stripe to be the same usage your app shows, reported once, in the right billing period. Aurora Meter Pro reports persisted counters to Stripe Billing Meters with stable identifiers, aligns periods to the Stripe subscription instead of the calendar month, and reconciles the two sides. One consequence of subscription-aligned periods is worth planning for: a period that runs from the 14th to the 14th still has 28 to 31 days in it, so the “size the allowance for 31 days” rule holds.
Before you publish a storage price, run a full cycle in a Stripe sandbox with a test clock: upload, sample for a simulated month, advance the clock and read the invoice. It is the only way to be sure the tiers, the unit and the allowance agree.
Test the arithmetic
The sampler is pure enough to test without waiting a day. The cases worth pinning are the carry, the retry and the gap:
defmodule MyApp.Workers.SampleStorageTest do
use MyApp.DataCase, async: false
use Oban.Testing, repo: MyApp.Repo
alias MyApp.Workers.SampleStorage
@gb 1_073_741_824
test "sub-gigabyte storage is carried until it adds up" do
org = insert(:org, storage_bytes: div(@gb, 2))
AuroraMeter.subscribe(org.id, :team)
:ok = perform_job(SampleStorage, %{org_id: org.id})
assert AuroraMeter.usage(org.id, :storage_gb_days) == 0
backdate_sample(org, 1)
:ok = perform_job(SampleStorage, %{org_id: org.id})
assert AuroraMeter.usage(org.id, :storage_gb_days) == 1
end
test "a retry on the same day adds nothing" do
org = insert(:org, storage_bytes: 3 * @gb)
AuroraMeter.subscribe(org.id, :team)
:ok = perform_job(SampleStorage, %{org_id: org.id})
:ok = perform_job(SampleStorage, %{org_id: org.id})
assert AuroraMeter.usage(org.id, :storage_gb_days) == 3
end
test "a missed day is caught up" do
org = insert(:org, storage_bytes: 2 * @gb, storage_sampled_on: Date.add(Date.utc_today(), -3))
AuroraMeter.subscribe(org.id, :team)
:ok = perform_job(SampleStorage, %{org_id: org.id})
assert AuroraMeter.usage(org.id, :storage_gb_days) == 6
end
end
backdate_sample/2 is a one-line helper that moves storage_sampled_on back a day. Add a concurrency test for create_file/2 as well: start two uploads that each fit and together do not, on separate database connections, and assert that exactly one succeeds. More patterns for this kind of test are in testing usage-based billing in Elixir.
What to build, and what to install
Everything above except the Stripe reporting runs on the free core: the plan values, the cached feature_value/3 lookup, the GB-days counter, the daily history and the LiveView subscription. It is MIT, on GitHub, and the core docs cover setup. The stored-bytes column and the sampler are your code, because the level is your data.
When the GB-days should turn into a charge, Aurora Meter Pro adds the Stripe usage reporter, subscription-aligned periods, Checkout and webhook sync, quota alerts and reconciliation. It is licensed per app from $99 a month, with a 14-day free trial (one trial per customer), which is enough time to run the sandbox cycle above end to end.
Summary
Storage billing in Phoenix works once you stop treating storage as an event. Keep the current level as an exact running total in your own table, changed in the same transaction as the file. Enforce the plan’s cap with a single conditional update so concurrent uploads cannot both squeeze through. Convert the level into a flow by sampling it daily into a GB-days counter, carrying the remainder, refusing to double count and catching up missed days. Size the included allowance for a 31-day month, show customers both the level and the time-weighted average, and let Stripe sum the samples into an invoice.