---
title: Grandfathered Pricing Done Right
date: '2026-11-08'
description: In Mailingest a plan's price is a published version that never changes. Customers keep theirs; moving them is a migration Stripe runs at renewal.
author: Pablo Fernandez
tags:
  - Billing
  - Stripe
  - Postgres
  - Pricing
  - Rust
source: 'https://www.pablofr.com/blog/keeping-the-price-a-customer-bought'
---
The first time you change a price, you find out what your price was. If it was a number in a config file, every customer now pays the new one, including the ones who signed up last week because of the old one. If it was a row you edited, last month's invoice can no longer be explained, because the row that priced it says something else today.

[Mailingest](/blog/giving-an-inbox-to-each-agent), my mail platform, got plans with versions on October 30. The request that started them was one sentence: staff should be able to edit plans, quotas and allowances from the admin panel, and there should be versions for grandfathering. Those two halves pull against each other. An editable price and a price a customer can count on are the same column, unless what staff edit isn't the price customers pay. This is how the two were kept apart, and what Stripe ended up doing at the till.

## A plan is a name, a version is a price

The split is two tables. A plan (`billing_plans`) is the name somebody buys: Personal, Pro, Business, or a private plan for one partner. It has a slug that never changes, because the API, discount codes and Stripe's lookup keys all say it. It carries no money.

Everything that costs, includes or allows lives on a version (`billing_plan_versions`): the monthly and yearly fee, the emails and storage included, the price per 1,000 emails over that, storage blocks, how many mailboxes are included and what an extra one costs, the features, the refund rules. A version is a draft while staff edit it, published once it's sold, and retired when it stops being sold.

```
  ┌───────────────┐  publish   ┌───────────────┐  retire   ┌───────────────┐
  │ draft         │ ─────────▶ │ published     │ ────────▶ │ retired       │
  │ staff edit it │            │ terms frozen  │           │ not for sale  │
  │ one per plan  │            │ sold to new   │           │ kept by those │
  │ can be thrown │            │ customers     │           │ who have it   │
  └───────────────┘            └───────────────┘           └───────────────┘
```

*A version is edited only as a draft; once published its terms are frozen, and retiring it stops sales without touching anyone who has it.*

The plan points at its current version, the one new customers get. Each organisation points at the version it bought (`organization_billing.plan_version_id`). Publishing version 2 moves the plan's pointer and nobody else's. That is the whole of grandfathering: it isn't a feature added on top, it's what happens when you do nothing.

The prices on the [public pricing page](https://www.mailingest.com/en/pricing) today are all version 1: 9, 20 and 90 euros a month for Personal, Pro and Business, VAT included, with the yearly price set at ten months. The page has no figures in its code. It reads the current public versions from the API, so publishing a new version changes the page and nothing else.

## The database holds the published terms

Grandfathering only means something if version 1 still says what it said when the customer bought it. So the rule isn't left to the console. A trigger refuses any change to a published version except its retirement:

```sql:migrations/603_billing.sql {16-18}
CREATE FUNCTION billing_plan_versions_immutable() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
    IF TG_OP = 'DELETE' THEN
        IF OLD.status <> 'draft' THEN
            RAISE EXCEPTION 'plan version % is published and cannot be deleted', OLD.id
                USING ERRCODE = 'check_violation';
        END IF;
        RETURN OLD;
    END IF;
    IF NOT (NEW.status = OLD.status
            OR (OLD.status = 'draft' AND NEW.status = 'published')
            OR (OLD.status = 'published' AND NEW.status = 'retired')) THEN
        -- ... raise: a version only moves forward
    END IF;
    IF OLD.status <> 'draft'
       AND (to_jsonb(NEW) - ARRAY['status', 'retired_at', 'updated_at'])
           IS DISTINCT FROM (to_jsonb(OLD) - ARRAY['status', 'retired_at', 'updated_at']) THEN
        RAISE EXCEPTION 'plan version % is published: its terms never change', OLD.id
            USING ERRCODE = 'check_violation';
    END IF;
    RETURN NEW;
END;
$$;
```

The highlighted comparison is the part I'd copy. It turns the whole row into JSON, removes the three columns that are allowed to move, and compares what's left. A column added next year is frozen the day it's added, with nobody having to remember it. When I wrote about [invoices Postgres refuses to change](/blog/immutable-invoices-in-postgres), the guard there listed the frozen columns one by one, and I said that listing the few that may change would fail safe instead. This is that design, written from the start.

A test in `crates/db/tests/plans.rs` goes around the repository on purpose: a raw `UPDATE` of the monthly amount, a raw `DELETE`, and an attempt to set a published version back to draft. All three fail.

## Prices in Stripe are versioned too

Stripe has the same problem from the other side. A [Price](https://docs.stripe.com/api/prices/object) object's amount [can't be changed](https://docs.stripe.com/products-prices/manage-prices) either, so each Mailingest version gets its own set of prices on one product per plan. They're found by lookup key, and the key carries the version:

```rust:crates/core/src/plans.rs
fn key_prefix(&self) -> String {
    format!("{}_v{}", self.slug, self.version)
}
```

So Pro's first version sells as `pro_v1_monthly` and `pro_v1_yearly`, with `pro_v1_emails`, `pro_v1_storage`, `pro_v1_storage_blocks` and `pro_v1_mailboxes` for usage and extras. Since a published version never changes, a lookup key names one price forever, and the catalog job that creates them can run again at every deploy without creating a second. It also works in reverse: when a subscription changes in Stripe, the sync reads which version it's on from its price's lookup key and pins the organisation to it.

## Moving people is a decision

Sometimes the old version does have to go: a price rise, an allowance that turned out to cost more than it earns. In Mailingest that's a cohort migration, and nothing starts one but a member of staff.

The preview says how many organisations move, by interval, what each paid before and after, the difference in revenue a month, the date each one switches, a sample of 50 and the text of the notice. The default switch is each organisation's first renewal after the notice, with nothing prorated; the other option is a fixed date for everyone. The notice period defaults to 30 days, and decision D10 in the plans doc makes 30 days the minimum whenever the new version is worse for the customer in anything at all. A customer who gets that notice can leave with the unused part of the period refunded.

The migration doesn't flip a column on renewal day. It hands the change to a [subscription schedule](https://docs.stripe.com/billing/subscriptions/subscription-schedules) in Stripe, built from the live subscription:

```rust:services/api/src/billing/migrations.rs {4,13}
let mut form = Form::new()
    .set("end_behavior", "release")
    .set("phases[0][start_date]", start)
    .set("phases[0][end_date]", switch)
    .set("phases[0][proration_behavior]", "none");
form = sync::phase_items(form, 0, &sync::current_items(&sub));
// ...
let next = sync::items_of(state, to, interval, due.account.organization_id).await?;
form = sync::phase_items(form, 1, &next)
    .set("phases[1][duration][interval]", interval.as_str())
    .set("phases[1][duration][interval_count]", 1)
    .set(
        "phases[1][proration_behavior]",
        if at_renewal || due.effective == "renewal" {
            "none"
        } else {
            "create_prorations"
        },
    )
```

Phase 0 is what the customer has now and ends at the switch. Phase 1 is the new version's fee and usage prices for one period, and then the schedule releases the subscription to carry on as normal. If the update fails, the code releases the half-made schedule so the subscription stays as it was. Stripe makes the change at the exact second, the webhook arrives, and the sync reads the new lookup key. A job every five minutes tells the customers, creates the schedules, and marks each organisation as scheduled, switched, skipped or failed. Anyone who changes plan on their own before the date is skipped.

The doc records one of these run end to end in Stripe's test mode, with test clocks and a made-up version 2: before the date the subscription was still on version 1, and the renewal invoice afterwards charged version 2's fee plus its extra mailboxes.

## Which version priced last month

One more gap showed up later the same day. Usage over the allowance is reported to Stripe through the month, and 48 hours after each period ends a close compares what was measured with what was reported and bills anything that got lost. The close used to read the version the organisation has now. With a migration at renewal, that's the wrong one: the month that just ended would be re-priced at version 2's rates.

The fix (decision D15, the evening of October 30) was to make the database keep the history itself:

```sql:migrations/615_billing_version_history.sql
CREATE FUNCTION record_billing_version() RETURNS trigger AS $$
BEGIN
    IF TG_OP = 'UPDATE' AND OLD.plan_version_id IS NOT DISTINCT FROM NEW.plan_version_id THEN
        RETURN NULL;
    END IF;
    -- Two changes in one transaction: the last one is what held from then.
    INSERT INTO billing_organization_versions (organization_id, plan_version_id, effective_from)
    VALUES (NEW.organization_id, NEW.plan_version_id, NOW())
    ON CONFLICT (organization_id, effective_from)
       DO UPDATE SET plan_version_id = EXCLUDED.plan_version_id;
    RETURN NULL;
END;
$$ LANGUAGE plpgsql;
```

It fires on every write to `plan_version_id`, whoever makes it: Stripe's sync, staff, a cohort migration or a discount code. No code path has to remember to log. The close then asks for the version in force at the last second of the period, prices with it, and stores it on the close row.

```
   October (on v1)                       November (on v2)
  ├─────────────────────────────────────┼───────────────────────────────────▶
                                        │           │
                                renewal: schedule   close of October,
                                switches to v2      48 h later
                                                    │
                                                    ▼
                                  history: v1 until the renewal, v2 after
                                  version at October's last second = v1
```

*A migration at renewal changes the version at the boundary; the close two days later still prices the old month with the version it had at its end.*

A change in the middle of a month works the other way, and on purpose: a downgrade "now" or a migration on a fixed date prices the whole month with the new version, which is what the usage reports had been doing since the change, so the close adds nothing on top. A test in `billing::report` checks that the two agree.

## Where the rule was bent

The trigger stops the app and any stray `UPDATE`. It doesn't stop a migration, which runs as the table's owner, and twice a migration has switched it off to edit version 1 in place. On November 5, security codes stopped being a feature of their own (sealing replaced them) and `642_correo_verificable.sql` removed the name from every version's feature list. On November 6, AI moved to a prepaid balance with a monthly allowance by plan, and `667_ai_balance.sql` added the column and filled it for version 1:

```sql:migrations/667_ai_balance.sql
ALTER TABLE billing_plan_versions ADD COLUMN included_ai_cents BIGINT CHECK (included_ai_cents >= 0);
ALTER TABLE billing_plan_versions DISABLE TRIGGER billing_plan_versions_immutable;
UPDATE billing_plan_versions v SET included_ai_cents = x.cents
  FROM billing_plans p, (VALUES ('personal', 300::bigint), ('pro', 600), ('business', 2500)) AS x(slug, cents)
 WHERE p.id = v.plan_id AND p.slug = x.slug;
ALTER TABLE billing_plan_versions ENABLE TRIGGER billing_plan_versions_immutable;
```

Neither edit takes anything away from a customer: one drops a feature name that sealing, already in the same plans, now covers, the other gives every plan 3, 6 or 25 euros of AI a month. Doing it properly would have meant a version 2 of every plan and a migration to move everyone onto it. Still, it's version 1's terms changing after publication, which is the thing the design exists to prevent, and it's only visible because both migrations write `DISABLE TRIGGER` where a reviewer can see it. The guard is a rule for the application. For the person writing migrations it's a convention, and both of those edits are on record.

## Stripe sells, Mailingest serves

The last piece is who takes the money. Every Checkout goes through [Stripe Managed Payments](https://docs.stripe.com/payments/managed-payments), which makes Stripe the merchant of record: Stripe, as Link, is the seller on the receipt, calculates and remits the VAT, issues the invoices, and handles fraud, disputes and support for each charge. The customer sees "sold through Link" in the Checkout and `LINK.COM*` on their card statement.

```
  Mailingest                          Stripe (Link)
  ┌──────────────────────────────┐    ┌──────────────────────────────┐
  │ plans and versions           │    │ seller of record             │
  │ prices by lookup key         │    │ VAT calculated and paid      │
  │ allowances and usage         │    │ invoices, receipts, refunds  │
  │ migrations and schedules     │    │ fraud, disputes, support     │
  │ consent before the Checkout  │    │ the Checkout page itself     │
  └──────────────────────────────┘    └──────────────────────────────┘
```

*With Managed Payments, the sale and its tax belong to Stripe; Mailingest keeps the catalog, the versions and the service.*

In code that's one parameter, and a list of parameters that must not be sent:

```rust:services/api/src/billing/sync.rs {3}
let mut form = Form::new()
    .set("mode", "subscription")
    .set("managed_payments[enabled]", "true")
    .set("customer", customer)
    .set("client_reference_id", &org)
    .set("line_items[0][price]", price)
    .set("line_items[0][quantity]", 1)
    .set("subscription_data[metadata][organization_id]", &org)
    .set("subscription_data[billing_mode][type]", "flexible")
    // ... locale, return URLs, expiry
    // The consumer's consent that the service starts at once (D9), given
    // in the web before coming here (Checkout takes no text of ours with
    // Managed Payments).
    .set("metadata[immediate_start_consent]", "true")
```

A test next to it holds the second half: `automatic_tax`, `tax_id_collection`, `customer_update`, `invoice_creation` and the rest of what Stripe takes over as seller never appear in the form. One of them cost a feature. The customer's consent that the service starts at once, inside the 14-day withdrawal period, used to sit on Stripe's pay button as `custom_text`. Managed Payments refuses that ("You cannot use custom_text with Managed Payments"), so the consent moved to a required checkbox in Mailingest's own page before the redirect, and travels as metadata.

The Checkout only creates the fee. Stripe's Checkout can't create a subscription with mixed intervals, and a yearly plan still bills its usage monthly, so the sync adds the metered prices and the extras afterwards. The billing doc lists everything Mailingest uses, checked on October 30 with Managed Payments subscriptions paid in test mode: metered usage billed at renewal, prorated plan changes, subscription schedules, credit notes, customer balance. The same day there stopped being a free trial or a free plan at all. A new organisation is read-only until it buys one, so every account that sends mail has a version, and every version was bought through that Checkout or assigned by staff.

All of this is on `main`, and the pricing page serves it. What the page still sells is version 1 of every plan: as far as the docs record, the migration path has only run in Stripe's test mode.

Put together, the trade is this. Staff can change any number on any plan whenever they like, and none of those changes reaches a customer by accident. A new price is a new version; reaching an existing customer with it takes a decision, a notice, and a schedule Stripe carries out at their renewal. The cost is a second table, a trigger, a history table and a lookup key with a `v1` in it. In return, "what does this customer pay, and why?" has an answer that was true the day they bought it and is still true now.
