From the blog

Stripe Proration in Phoenix: Upgrade and Downgrade Plans Mid-Cycle Without Breaking Usage Limits

By Liam Killingback ·

Stripe Proration in Phoenix: Upgrade and Downgrade Plans Mid-Cycle Without Breaking Usage Limits

Stripe proration in Phoenix looks like a one-parameter problem. A customer clicks Upgrade on the 14th, you update the subscription, Stripe works out the difference, done. Then the questions arrive. They used 480 of their 500 generations before upgrading: do they now have 520 left of 1,000, or a fresh 1,000? Someone downgrades while already over the smaller plan’s limit: are they locked out until the 1st? Someone upgrades, burns through the bigger allowance in an afternoon, and downgrades again before the invoice.

Proration only answers the money question. A plan change in a usage-based product moves three things at once:

  1. Money: what Stripe charges or credits for the partial period.
  2. Entitlement: which plan your app thinks the customer is on, and from when.
  3. Usage: what happens to the counter and the limit for the period already in progress.

Get them out of step and you either give product away or lock out a paying customer. This post covers all three: what Stripe actually does, the policy that keeps the three in line, a hand-rolled implementation in Elixir, and how Aurora Meter handles it.

What Stripe proration actually does

When you change the price on a subscription item mid-period, Stripe can generate two invoice line items: a credit for the unused time on the old price and a charge for the remaining time on the new one.

A worked example. A customer is on a $20 monthly plan and upgrades to $50 exactly halfway through a 30-day period:

Line Amount
Unused time on the $20 plan (15 of 30 days) -$10.00
Remaining time on the $50 plan (15 of 30 days) +$25.00
Net proration +$15.00

Stripe prorates to the second, so real numbers are rarely this round. What happens to that $15 depends on proration_behavior:

Value What happens
create_prorations The two lines are created as pending invoice items and ride on the next invoice. The customer pays $65 at renewal ($50 plus $15).
always_invoice The lines are created and invoiced now. The customer pays $15 today and $50 at renewal.
none No lines. The price changes, and the next invoice is simply $50.

Three things that surprise people:

  • The billing date does not move when both prices share an interval. Switching monthly to yearly (or the reverse) is different: that starts a new period at the switch.
  • A downgrade produces a credit, not a refund. The negative net sits on the customer’s balance and reduces future invoices. Money goes back to the card only if you refund it yourself.
  • Lines accumulate. Upgrade then downgrade inside one period and the next invoice has four proration lines. The total is right. The invoice is hard to read, and that is the one your customer forwards to support.

The policy that keeps money, plan and usage aligned

Before any code, pick the rules. This is the set most usage-based products converge on, and the reason for each:

Change When it takes effect Proration Usage counter
Upgrade Immediately Charge the difference now (always_invoice) Keeps counting; the new, larger limit applies
Downgrade End of the current period None Resets naturally with the new period
Cancel End of the current period None Plan falls back to free at the boundary

Upgrades are immediate because the customer wants the bigger limit right now, usually because they just hit the smaller one. Charging the difference now, not at renewal, closes the abuse path: with deferred prorations, someone can upgrade, use the large allowance, and downgrade before paying anything extra.

Downgrades wait for the period end because every alternative is worse. An immediate downgrade means computing a credit for time the customer already had full access to, and it creates the over-the-limit problem: a customer at 800 of 1,000 who drops to a 500 plan is suddenly 300 over and locked out of something they paid for. Deferring means they keep what they bought until the period they bought it for ends, and the new period starts with a zero counter under the smaller limit. No credit, no lockout, no four-line invoice.

The counter is never reset by an upgrade. If it were, the cheapest way to get more usage would be to upgrade and downgrade on a loop. Usage for the period is a fact. The plan change moves the ceiling above it, so 480 used of 500 becomes 480 used of 1,000.

There is a fourth, stricter option for upgrades: prorate the allowance as well as the price, so half a period on the larger plan grants half the extra units. It is fair on paper and confusing in practice. Customers understand “you are on Pro now, your limit is 1,000”. They do not understand “your limit this month is 750”. Unless your unit costs are high enough to demand it, keep the full new limit.

The hand-rolled version in Elixir

Preview the charge before you make it

Never show a number you computed yourself. Ask Stripe what it will charge, using the same proration timestamp you will send with the real update so the two match:

defmodule MyApp.Billing.Stripe do
  @base "https://api.stripe.com/v1"

  def preview_change(subscription, new_price_id, proration_date) do
    Req.post(@base <> "/invoices/create_preview",
      auth: {:bearer, secret_key()},
      form: [
        {"subscription", subscription.stripe_id},
        {"subscription_details[items][0][id]", subscription.stripe_item_id},
        {"subscription_details[items][0][price]", new_price_id},
        {"subscription_details[proration_behavior]", "always_invoice"},
        {"subscription_details[proration_date]", proration_date}
      ]
    )
  end

  defp secret_key, do: Application.fetch_env!(:my_app, :stripe_secret_key)
end

proration_date is a Unix timestamp. Take it once when the confirmation screen loads, keep it in the LiveView’s assigns, and send the same value with the update. Otherwise the amount on the button and the amount on the invoice differ by a few cents and somebody notices. (Older Stripe API versions expose the same preview as the upcoming invoice endpoint. Check which one your pinned API version supports.)

Upgrade: change the price, charge now

def upgrade(subscription, new_price_id, proration_date, ref) do
  Req.post(@base <> "/subscriptions/#{subscription.stripe_id}",
    auth: {:bearer, secret_key()},
    headers: [{"idempotency-key", "plan-change:" <> ref}],
    form: [
      {"items[0][id]", subscription.stripe_item_id},
      {"items[0][price]", new_price_id},
      {"proration_behavior", "always_invoice"},
      {"proration_date", proration_date},
      {"payment_behavior", "pending_if_incomplete"}
    ]
  )
end

Two lines carry the weight:

  • The idempotency key. ref is a value you generate per change request (store it on a plan_changes row with a unique index). A double click, a LiveView reconnect or a retried job then produces one Stripe update, not two.
  • payment_behavior: "pending_if_incomplete". With it, the price change is applied only if the proration invoice is paid. If the card is declined, the subscription stays on the old price and you have nothing to unwind. Stripe restricts which fields can be combined with pending updates, so check its documentation against your exact call.

Notice what this function does not do: it does not update the plan in your database. That happens in the webhook.

The webhook is the only writer

Stripe sends customer.subscription.updated when the change lands. Make that handler the single place a plan is ever written:

def handle_event(%{"type" => "customer.subscription.updated", "data" => %{"object" => sub}}) do
  price_id = get_in(sub, ["items", "data", Access.at(0), "price", "id"])
  plan = MyApp.Plans.for_price!(price_id)

  MyApp.Accounts.set_plan(sub["metadata"]["tenant_key"], plan,
    status: sub["status"],
    period_start: sub["current_period_start"],
    period_end: sub["current_period_end"]
  )
end

If the controller wrote the plan optimistically and the webhook wrote it again, you would have two writers that can disagree, and a declined card would leave a customer on a plan they never paid for. One writer, driven by Stripe’s state, cannot drift. It also means changes made in the Stripe Customer Portal flow through the same path with no extra code.

Stripe retries events and does not guarantee their order, so an old snapshot can arrive after a newer one. Either compare the event’s created time with what you stored, or fetch the current subscription inside the handler and write that.

Downgrade: schedule it, do not do it

A downgrade is a row and a job, not an API call:

def schedule_downgrade(org, new_plan, ref) do
  %PlanChange{}
  |> PlanChange.changeset(%{
    org_id: org.id,
    target_plan: to_string(new_plan),
    effective_at: org.subscription.current_period_end,
    ref: ref,
    state: "pending"
  })
  |> Repo.insert(on_conflict: :nothing, conflict_target: :ref)
end

An Oban cron job picks up rows whose effective_at has passed and sends the Stripe update with proration_behavior: "none". Because it runs at the boundary, there is no partial period to prorate. The UI shows “Your plan changes to Starter on 1 December”, with a Cancel button that deletes the pending row.

The job must handle three cases before sending anything: the customer cancelled in the meantime (drop the change), the customer upgraded in the meantime (drop the change), or Stripe already shows the target price because a previous run crashed after the update (mark it done, send nothing). Stripe’s Subscription Schedules can hold the future phase for you instead, at the cost of a second object to keep in sync.

What happens to usage: the part proration ignores

With the policy above, the usage rules fall out simply, as long as your counter is keyed by tenant, feature and period, and your limit is read from the current plan at check time:

  • Upgrade mid-period. The counter is untouched. The next check reads the new plan’s limit. A customer blocked at 500 of 500 is unblocked the moment the webhook lands, with 500 remaining of 1,000.
  • Downgrade at the boundary. The new period has a new counter starting at zero, so “over the new limit” cannot happen.
  • Downgrade forced mid-period (a failed payment that ends in cancellation, for example). The customer may now be over the free plan’s limit. That is correct: new work is refused, nothing already done is taken away, and the dashboard should say why.

The trap is storing the limit next to the counter (“500 allowed this month”) when the period opens. Then an upgrade has to find and rewrite that row, and forgetting to is the classic “I upgraded and I am still blocked” ticket.

Metered overage needs more care

If the plan bills overage (1,000 included, then a unit price), a mid-period change raises a real billing question: is this month’s overage measured against the old included amount, the new one, or a blend? Stripe prices metered usage on the subscription’s own cycle, and moving the metered price mid-period changes what the already-reported usage is billed against.

The safe rule: for plans with metered prices, report outstanding usage first, then change the plan, and prefer making the change at the period boundary. Our post on overage billing in Phoenix covers the allowance arithmetic in detail.

Plan changes with Aurora Meter

Aurora Meter (free, MIT) keys counters by tenant, feature and period and resolves the limit from the tenant’s plan on every check, through an ETS cache that a subscription write evicts on every node. So the usage rules above are the default behaviour, not something you build. See the core docs for setup.

defmodule MyApp.Plans do
  use AuroraMeter.Plans

  plan :starter do
    price 2_000
    limit :ai_generations, 500, :hard
  end

  plan :pro do
    price 5_000
    limit :ai_generations, 1_000, :hard
    feature :api_access, true
  end
end

An upgrade keeps the counter and lifts the ceiling

AuroraMeter.quota(org, :ai_generations)
# => %{kind: :hard, used: 480, limit: 500, remaining: 20, ...}

AuroraMeter.subscribe(org, :pro)

AuroraMeter.quota(org, :ai_generations)
# => %{kind: :hard, used: 480, limit: 1_000, remaining: 520, ...}

No counter migration and no cache to bust. A LiveView showing <.usage_meter quota={@quota} /> redraws with the new denominator on the next usage message.

A downgrade is a scheduled transition

The core has the “row and a job” from the hand-rolled section built in. First show the customer exactly what changes, with a pure read that writes nothing:

{:ok, preview} = AuroraMeter.Subscriptions.preview_transition(org, :starter)

preview.changes
# each change carries a :direction (:increase, :decrease, :added, :removed)
preview.effective_at
# the end of this tenant's current period

Then schedule it:

{:ok, _transition} =
  AuroraMeter.Subscriptions.schedule_transition(org, :starter,
    ref: "downgrade:#{org.id}:#{request_id}"
  )

With no :effective_at, the boundary is the end of the tenant’s own period. The :ref is an idempotency key, so a double submit returns the same transition. Until it applies, check/2 and quota/2 keep answering from the current plan. “Actually, keep me on Pro” is one call:

AuroraMeter.Subscriptions.cancel_transition(org, "downgrade:#{org.id}:#{request_id}")

Due transitions are applied by AuroraMeter.Subscriptions.apply_due_transitions/1, which you run from any scheduler and which is safe to run on every node at once. One caution from the docs: the price in a preview is the plan’s declared list price. The core computes no proration, so never present it as “you will be charged”.

With Stripe in the loop: Aurora Meter Pro

When a plan change has to move a Stripe price, the entitlement must not change until Stripe agrees. Aurora Meter Pro schedules the change with provider confirmation:

{:ok, transition} =
  AuroraMeter.Pro.Transitions.schedule(org, {:starter, "1"}, ref: "downgrade-8412")

The transition stays pending and visible until Stripe’s own state shows the new price. A scheduled worker (AuroraMeter.Pro.Transitions.Applier) retrieves the subscription, sends nothing if Stripe already shows the target, otherwise sends the update with a stable idempotency key, then confirms only after reading the new price back. That is the crash-safe sequence from the hand-rolled section, already written and tested.

Three behaviours worth knowing before you rely on it:

  • Proration is Stripe’s arithmetic, passed through. Pro computes none. The :proration_behavior setting (:none, :create_prorations or :always_invoice) is handed to Stripe untouched and defaults to :none, which is the “changes take effect cleanly at the next period” behaviour. Turn on the others deliberately, knowing the lines accumulate.
  • A refusal is never applied locally. If Stripe rejects the change, the transition stays pending and a reconciliation item is opened for a human. Granting a plan Stripe is not billing for is the one outcome it refuses to produce.
  • Cancellation wins. If the customer has asked to cancel at the period end, a transition scheduled at or after that moment is cancelled with it.

Subscription webhooks are handled by mounting one plug, including the out-of-order case: Pro refreshes the current subscription from Stripe instead of trusting an old snapshot. With the Pro period source, usage periods follow the customer’s own billing cycle, so “end of period” means their renewal date and not the end of the calendar month.

Pro is licensed per app from $99 a month, with a 14-day free trial that each customer can claim once. Details are on the pricing page.

Testing plan changes

Three tests catch most regressions, and none needs Stripe:

test "an upgrade keeps usage and raises the limit" do
  org = org_fixture(plan: :starter)
  AuroraMeter.track(org, :ai_generations, 480)

  AuroraMeter.subscribe(org, :pro)

  quota = AuroraMeter.quota(org, :ai_generations)
  assert quota.used == 480
  assert quota.limit == 1_000
end

test "a scheduled downgrade changes nothing until it applies" do
  org = org_fixture(plan: :pro)

  {:ok, _} =
    AuroraMeter.Subscriptions.schedule_transition(org, :starter, ref: "t-1")

  assert AuroraMeter.plan(org).id == :pro
end

test "scheduling twice with one ref creates one transition" do
  org = org_fixture(plan: :pro)

  {:ok, first} = AuroraMeter.Subscriptions.schedule_transition(org, :starter, ref: "t-2")
  {:ok, second} = AuroraMeter.Subscriptions.schedule_transition(org, :starter, ref: "t-2")

  assert first.id == second.id
end

Add a fourth for the boundary itself with a frozen clock. Our guide to testing usage-based billing in ExUnit shows how to move time without sleeping.

Edge cases to decide up front

  • Upgrading during a trial. There is no paid time to prorate. Decide whether upgrading ends the trial or only changes what the trial converts to.
  • Upgrading while past_due. The proration invoice will probably fail too. Send them to update their card first.
  • Seats. A quantity change is the same mechanism with the same choices. Most products prorate added seats immediately and remove seats at renewal.
  • Monthly to annual. The interval change starts a new period, so the usage window moves with it. Decide whether the customer gets a fresh allowance at that point.
  • Version pinning. If the customer is on a grandfathered price, a downgrade and later upgrade usually lands them on today’s price. Say so on the confirmation screen. See grandfathered pricing in Phoenix.

Summary

  • Stripe proration settles money only. A plan change also moves the entitlement and the usage ceiling, and all three must agree.
  • Upgrade now, charge the difference now (always_invoice), and apply the plan only when Stripe confirms payment.
  • Downgrade at the period end with no proration. It avoids credits, unreadable invoices and customers stranded over a smaller limit.
  • Never reset usage on a plan change. Key the counter by period and read the limit from the current plan at check time.
  • Make the webhook the only code that writes a plan, give every change an idempotency reference, and preview with the same proration_date you charge with.
  • In Aurora Meter, an upgrade is subscribe/2, a downgrade is schedule_transition/3, and Pro holds the entitlement until Stripe shows the new price.