DEV Community

Daniel Pertu
Daniel Pertu

Posted on

Our discount label is a percentage, because the phone cannot know which currency the bill is in

Munchable has a subscription, priced per country in fixed amounts you can see on the pricing section of the homepage. It also has a reward: if you add a product the catalogue does not have yet, you get credit against your next bill.

The whole feature sounds like a Stripe one-liner. It took a status machine, and the first thing it taught me was that the reward cannot be expressed in money.

The label is a percentage, and that was not a design preference

My first version of the label said "20p off next month", because that is what the credit was worth. Then I wrote down what the app would need to know to print that sentence truthfully:

/**
 * A reward is a percent-off coupon on the next bill, and the percentage is the
 * one figure that is exactly right for everybody: Stripe takes that share off
 * whatever the bill is, in whatever currency the subscription is in. A money
 * figure would have to guess the currency from the phone, and a subscriber's
 * bill is in the currency they subscribed in, which the phone does not know.
 */
export function rewardOffLabel(percent: number, freeMonth: boolean): string {
  if (freeMonth) return 'Next month free!';
  if (percent <= 0) return 'No discount yet this month';
  return `${percent}% off next month`;
}
Enter fullscreen mode Exit fullscreen mode

Three facts collide here. Prices are set per currency as whole amounts, not converted at a rate. A subscription is billed in the currency it was created in, forever. And a phone knows its own region, which is not the same thing: people travel, move, change their store region, and sign up on one device and read the app on another.

So "20p" is a sentence the client cannot say without guessing, and a guess about somebody's bill is the worst kind of guess. "4% off next month" is exactly true in every currency and needs no lookup at all. There is still a pence figure in the API response for display on the web, where the price actually is known, and the phone ignores it.

Percentages have two more properties I did not plan for and now would not give up. They survive a price change: a credit minted last month is still the same share of this month's bill. And they are correct about tax:

 * A percent discount comes off the subtotal so tax is computed on what
 * remains: 100% off is £0 in every country. A customer-balance credit would
 * leave EU customers paying the VAT and is undocumented under
 * merchant-of-record.
Enter fullscreen mode Exit fullscreen mode

That is the kind of thing you find out at the end, after you have built the other version. A balance credit feels equivalent to a discount and is not, because tax is calculated before it is applied. If your product is sold through a merchant of record and your "free month" has to actually be free, use a percent_off coupon.

The coupons themselves are deterministic, which keeps the whole thing stateless:

/** Deterministic coupon id for a whole-number percent, 1..100. */
export function rewardCouponId(percent: number): string {
  return `${REWARD_COUPON_PREFIX}${percent}pct`;
}
Enter fullscreen mode Exit fullscreen mode

At most 100 coupons can ever exist, each created on first use, each named for exactly what it does. No coupon table, no ids to store, nothing to clean up.

The hard part is that the two halves happen in different months

Credit is earned in one calendar month and comes off a bill in the next, which means the thing that creates the reward and the thing that spends it are different processes running weeks apart. Two actors can touch a reward row:

  • a monthly job, which settles the previous month and puts coupons on live subscriptions
  • the checkout flow, when somebody who banked rewards while unsubscribed finally subscribes, and the banked credit should attach to the session

They must never both act on the same row, because the failure mode is a double discount on a real invoice.

The row has five statuses and an explicit transition table:

export type RewardStatus = 'earned' | 'applying' | 'applied' | 'no_subscription' | 'failed';

/** Allowed transitions. 'applied' is terminal. */
export const REWARD_TRANSITIONS: Readonly<Record<RewardStatus, readonly RewardStatus[]>> = {
  earned: ['applying', 'no_subscription'],
  no_subscription: ['applying', 'earned'],
  failed: ['applying', 'no_subscription'],
  applying: ['applied', 'earned', 'failed', 'no_subscription'],
  applied: [],
};
Enter fullscreen mode Exit fullscreen mode

no_subscription is not an error state, it is a parking space: you earned this, there is nothing to discount yet, we are keeping it. The app says so in those words ("Saved until you subscribe"). applied is terminal and nothing leaves it.

The mutex is one UPDATE

No advisory locks, no queue, no leader election. Claiming a row is a single statement:

/** Single-actor claim: only the caller that gets the row back proceeds. */
async function claim(id: string, allowed: readonly RewardStatus[]): Promise<boolean> {
  const rows = await db
    .update(contributionRewards)
    .set({ status: 'applying', updatedAt: new Date() })
    .where(and(eq(contributionRewards.id, id), inArray(contributionRewards.status, [...allowed])))
    .returning({ id: contributionRewards.id });
  return rows.length > 0;
}
Enter fullscreen mode Exit fullscreen mode

The status is both the data and the lock. Whoever flips it to applying gets the row back and proceeds to call Stripe; the other caller gets zero rows and moves on. The set of statuses a claim is allowed to start from is a named constant shared by both actors, so neither one can quietly widen it.

The obvious hole is a process that claims a row and then dies mid call, leaving it applying forever. That is handled by time, not by a heartbeat: an applying row older than fifteen minutes is treated as abandoned and adopted by the next run. Fifteen minutes is longer than any Stripe call can live, which is the only property the number needs.

Idempotency, and the discount that must not stack

Each Stripe call is keyed on the reward row, and the subscription gets tagged with the row id:

// Idempotency: the subscription update is keyed on the reward ROW
// (`reward:<rowId>`) and tags the subscription's metadata with that row id, so
// a retry after a timeout can find its own work (reconcile) instead of adding
// a second discount.
Enter fullscreen mode Exit fullscreen mode

This is the pattern I would carry to any billing integration. An idempotency key stops a retry of the same request from duplicating work, but it does not help a process that timed out, lost its context, and now needs to know whether its own earlier attempt landed. Writing the row id into the remote object's metadata turns "did I already do this?" into a read instead of a guess.

Rewards also refuse to stack multiplicatively. If a reward coupon is already pending on the subscription, the row does not try to be clever: it goes back to earned and waits for next month. Two coupons would compound (10% then 10% is 19%, not 20%), which is not what anybody was promised.

Failures are classified, not just caught

Stripe errors are sorted into "worth trying again next month" and "never going to work":

const TRANSIENT_ERROR_PREFIXES = [
  'api_connection_error',
  'api_error',
  'rate_limit_error',
  'timeout',
];
Enter fullscreen mode Exit fullscreen mode

The row stores a human readable <class>/<code>: message, and the retry predicate reads the prefix of that stored string. Re-parsing a string you formatted yourself is slightly grubby, and I kept it, because the alternative is a second column nobody reads and this way a human opening the row sees the actual reason. A vanished subscription (resource_missing) is not a failure at all: it becomes no_subscription, which is the truth.

Banked credit, oldest first

Somebody can contribute for months without ever subscribing. Those rewards pile up with nothing to discount, and when they do subscribe, as much as possible is attached to the checkout session:

for (const row of sorted) {
  if (percent >= MAX_PERCENT) break;
  if (percent + row.percent > MAX_PERCENT && picked.length > 0) break;
  picked.push(row);
  percent = Math.min(MAX_PERCENT, percent + row.percent);
}
Enter fullscreen mode Exit fullscreen mode

Oldest period first, stopping before a row that would push the total over 100%, so that row keeps its full value for the following month instead of having part of it quietly discarded. A bill cannot be more than free, and nobody should lose credit to arithmetic.

There is no limit on how many months can be banked, and there is a comment in the file explaining why there is no constant for that either:

 * There is no ceiling on how many months can be banked, and no constant for
 * one: an unread `MAX_BANKED_PERIODS = null` read like a policy that was
 * enforced somewhere.
Enter fullscreen mode Exit fullscreen mode

A constant that is not enforced is worse than no constant. Somebody will find it in six months and believe it.

The one bit of polish

The app shows a progress bar toward the free month. It animates from empty on every arrival, even when the value has not changed, and that is deliberate:

// Contributing a product is the one thing here the user chose to do, so
// watching the progress actually move is the reward, and a width that is just
// already there on arrival gives that away for nothing.
Enter fullscreen mode Exit fullscreen mode

Everything else in this post is about not paying somebody twice. That line is the only part the contributor actually sees.

If you want to see where this surfaces: the price it discounts is on the homepage, in your own currency, and the terms spell out what the credit is and is not (a discount on a bill, never a cash value, never paid out). The licenses page covers the other half, which is what happens to a product somebody adds.

Top comments (0)