My account

Monetization and pricing

A product engineer must know how the product makes money, because pricing lives in the code. Pick a value metric, keep plans and features apart with entitlements, treat the billing provider as the source of truth and handle its webhooks safely, count usage you charge for exactly once, and watch MRR, churn and conversion. Change prices with care, because a price test touches trust, not only numbers.

Not reviewedWritten with AI helpReading time: 15 minOnline shop exampleTypeScript

Author: bezzad

Contents

The problem: “just add a Pro plan”

Our shop wants a membership called Shop Plus: free shipping and early access to sales, for a monthly price. A first version went live in one week. One month later the team has these reports:

  1. Some members lost free shipping even though they paid. Their card renewal was a few minutes late.
  2. Some people got Plus for free. They canceled, but the app never heard about it.
  3. Marketing wants a yearly plan and a “Plus Lite” plan. The code has if (user.plan === 'plus') in 40 places.

None of these are hard problems alone. They happen because money was added as a quick flag, and not designed as a part of the product.

Pricing models in one table

Model How the customer pays Good for Watch out
One-time Once, keeps it Simple tools, digital goods No steady income.
Subscription Every month or year Ongoing value, like Shop Plus Churn. People must keep seeing the value.
Usage-based Per unit used (orders, API calls, AI tokens) Value that grows with use Bills are hard to predict. You must meter exactly.
Freemium Free plan, paid upgrade Products that spread by use The free plan costs money to run.
Tiers Good, better, best plans Different kinds of customers Too many plans confuse people.

Most real products mix these: a subscription with tiers, plus usage-based extras, for example “Plus includes 100 AI questions a month, then $1 per 100”.

The value metric is the unit you charge for. A good value metric grows when the customer gets more value: “orders shipped” for a seller tool is better than “number of logins”. An interviewer may ask: “What would you charge for, and why?” Answer with the value metric.

Entitlements: plans are not features

The 40 if (plan === 'plus') checks are the real bug. A plan is a price package. The code should ask about what the user is allowed to do, not which package they bought.

Billing providerOne table in our codeFeaturesPlanplus_monthlyStatusactiveEntitlementsfree_shippingearly_salesai_questionsCheckoutSales pageAI helpcan(account, e)A new plan changes only the middle table.
The billing provider knows the plan. Our code maps a plan to entitlements once. Features only ask about entitlements.
type Entitlement = 'free_shipping' | 'early_sales' | 'ai_questions';

// The only place that knows which plan gives what.
const PLAN_ENTITLEMENTS: Record<string, Entitlement[]> = {
  free: [],
  plus_lite: ['early_sales'],
  plus_monthly: ['free_shipping', 'early_sales', 'ai_questions'],
  plus_yearly: ['free_shipping', 'early_sales', 'ai_questions'],
};

export function can(account: Account, e: Entitlement): boolean {
  const active = ['trialing', 'active', 'past_due'];
  if (!active.includes(account.subscriptionStatus)) return false;
  return PLAN_ENTITLEMENTS[account.planId]?.includes(e) ?? false;
}

// In the checkout code:
const shipping = can(account, 'free_shipping') ? 0 : rate.price;
  1. Adding a yearly plan is now one line in a table, not 40 code changes.
  2. Feature code is easy to test: give an account with an entitlement, check the result.
  3. Sales can give one customer a special deal by adding an entitlement, without a fake plan.
  4. Many teams store this table in the database or in the feature flag tool, so it can change without a deploy.

Subscriptions: the provider is the source of truth

Use a billing provider (for example Stripe, Paddle or the app stores). Never store card numbers yourself. The provider owns the real state of the subscription, and it tells you about changes with webhooks.

trial ends without a cardpayscard failsretries faila retry workstrialingactivepast_duecanceledaccessaccessaccess (grace)no access
A subscription moves between states. Past due is not canceled: give a short grace period while the provider retries the card.

Rules for webhooks:

  1. Check the signature. Anyone can send a request to your webhook URL. Only accept requests signed by the provider.
  2. Handle each event once. Providers send the same event again if you are slow or fail. Save the event id and skip ids you have seen.
  3. Do not trust the order. “Updated” can come before “created”. When in doubt, fetch the current subscription from the provider’s API and save that.
  4. Answer fast. Save the event, answer 200, and do slow work in a background job.
  5. Have a backup. A daily job compares your saved subscriptions with the provider, in case a webhook was lost.
export async function onBillingWebhook(req: Request) {
  // Throws if the signature is wrong.
  const event = billing.verify(await req.text(), req.headers);
  const isNew = await db.processedEvents.insertIfMissing(event.id);
  if (!isNew) return new Response('already done', { status: 200 });

  await jobs.enqueue('sync-subscription', {
    subscriptionId: event.data.subscriptionId,
  });
  return new Response('ok', { status: 200 });
}

// The job reads the truth from the provider, so order does not matter.
async function syncSubscription(id: string) {
  const sub = await billing.subscriptions.get(id);
  await db.accounts.update(sub.customerId, {
    planId: sub.planId,
    subscriptionStatus: sub.status,
    currentPeriodEnd: sub.currentPeriodEnd,
  });
}

This fixes the first two bugs: “past due” still gives access while the card is retried, and a cancel event (even a late or repeated one) always reaches the database.

Usage-based billing: count once, count exactly

If Plus members pay for AI questions above the limit, every question is money.

  1. Write a usage record with a unique key (for example the question id) in the same transaction as the work. Retries then do not count twice.
  2. Send usage to the provider in batches from a job, with the same key, so the provider can also remove duplicates.
  3. Show the user their usage before the bill comes. Surprise bills create refunds and angry support tickets.
  4. Set a limit or an alert. A bug or a bad actor can create a huge bill in one night.

Numbers a product engineer should know

Number What it means Simple formula
MRR Monthly recurring revenue Sum of all active subscriptions per month (a yearly plan counts as price / 12).
Churn Share of customers who leave Customers lost this month / customers at the start of the month.
Conversion Share of people who start paying New paying customers / people who saw the offer or started a trial.
ARPU Average revenue per user Revenue / active users.
LTV Revenue from one customer over their whole time Roughly ARPU / monthly churn (a rough guess, not a fact).

Track these as events, like any other product metric: trial started, subscription started, payment failed, canceled, and the reason. Then you can answer “why did churn go up in March?”

Changing prices with care

  1. Price tests are not like button tests. Two people who see two prices for the same thing may feel cheated. Many teams test on new customers only, test different packages instead of different prices, or test in different markets. Check local law too.
  2. Grandfathering: when the price goes up, many products keep the old price for current customers for some time, and tell them early.
  3. Measure the right thing. A higher price can lower conversion but raise revenue. Look at revenue per visitor and at churn after some months, not only at sign-ups this week.

Common mistakes

Mistake Result Better way
if (plan === 'plus') everywhere Every new plan touches many files. Map plans to entitlements in one place.
Webhooks without a signature check Anyone can give themselves a paid plan. Verify the signature on every request.
Handling the same event twice Double credits, double emails. Save event ids and skip repeats.
Removing access the moment a payment fails Paying customers lose features for a late card. Keep access in “past due” for a short grace period.
Counting usage outside the transaction Retries charge twice, or not at all. Write usage with a unique key together with the work.
Testing prices without a plan Angry customers, unclear results. Test packages or new customers, and measure revenue and churn.

Summary in 6 lines

  1. Know the pricing model and the value metric: what you charge for should grow with the customer’s value.
  2. Plans are price packages. Map them to entitlements once, and let features ask only about entitlements.
  3. The billing provider owns the subscription. Verify webhooks, handle each event once, and read the current state from the provider.
  4. Past due is not canceled. Give a grace period while the card is retried.
  5. Usage you charge for must be counted exactly once, shown to the user, and limited.
  6. Track MRR, churn and conversion as events, and change prices with care for trust.

Done reading this lesson?Mark it as finished so it shows in your lessons list and report card.