DEV Community

Daniel Pertu
Daniel Pertu

Posted on

One abandoned-checkout email, seven reasons not to send it, and a Redis key that fails closed

Somebody opens CogniPrep's checkout, gets as far as the card field, and closes the tab. An hour later Stripe sends checkout.session.expired, and we send one email.

The email is the boring part. Everything around deciding whether to send it is not.

It is a reminder, and the module says so first

The file opens by defining itself by what it is not:

 * - A plain reminder of what they were buying and a link back to it. No
 *   discount code, no countdown, nothing that pretends the offer is ending.
 * - Sent only to a known account with email notifications on, and only when
 *   they have not bought the product (or anything else) since starting that
 *   checkout. The account-wide unsubscribe applies, as on every other email.
 * - At most one per user per 14 days, whatever they abandon.
Enter fullscreen mode Exit fullscreen mode

Writing the constraints at the top of the module is cheap and it settles arguments later. The temptation with this email is always the same: add 10% off, add "your cart expires tonight". Both are easy, both convert, and both are lies in our case, because the price does not change and nothing expires.

Why an hour, and why Stripe tells us at all

A Checkout Session gets an explicit expires_at:

export const CHECKOUT_SESSION_TTL_SECONDS = 60 * 60;

export function checkoutSessionExpiresAt(nowMs: number, cap?: number | null): number {
  const own = Math.floor(nowMs / 1000) + CHECKOUT_SESSION_TTL_SECONDS;
  return cap ? Math.min(own, cap) : own;
}
Enter fullscreen mode Exit fullscreen mode

The hour is not about the email. A session can hold a reserved discount code, and the reservation has its own lifetime, so the session is made to expire before the reservation would lapse on its own. The cap argument is for a session holding something that has to end sooner, and Math.min means the shorter of the two always wins.

The useful consequence is that abandonment becomes an event. There is no cron scanning for stale sessions and no "created more than an hour ago and not paid" query. Stripe already knows and says so once.

Three things happen on that event, and none may fail

case 'checkout.session.expired': {
  const expiredSession = event.data.object;
  await releaseNurtureCodeByCheckoutSession(expiredSession.id);
  await captureCheckoutExpired(expiredSession);
  await handleAbandonedCheckout(expiredSession);
  break;
}
Enter fullscreen mode Exit fullscreen mode

A reserved discount code is handed back, the funnel drop-off is captured (the client cannot observe its own expiry, so this is the only place that step exists), and the reminder is considered. All three are documented as never throwing, and for the third the module explains why:

 * `handleAbandonedCheckout` never throws. It runs inside the Stripe webhook,
 * where a throw would release the event marker and make Stripe redeliver the
 * expiry, repeating the nurture-code release and the analytics capture.
Enter fullscreen mode Exit fullscreen mode

This is the thing I would get wrong if I were writing it quickly. The webhook de-duplicates by inserting a marker row keyed on the Stripe event id before the switch runs, and the route's own comment explains the rest: "on a handler failure we release the marker (delete it) before returning 500 so Stripe's retry re-processes the event rather than being skipped as an already-seen duplicate". That is exactly right for a failed entitlement grant. It is wrong here, because the retry re-runs two siblings that already succeeded, and one of them is an analytics capture, so the funnel would count one abandonment twice. The failure mode of a thrown error is not a missing email. It is a double-counted step somewhere else.

So the whole body sits in one try, and the catch logs. An email we failed to send is a lost email. That is the smaller loss and it is chosen deliberately.

Seven ways to decide not to send

The decision is a pure function that returns a reason string, or null to send:

if (!buyer) return 'no such user';
if (!buyer.email_notifications_enabled) return 'email notifications off';
if (buyer.first_purchase_at && buyer.first_purchase_at >= sessionCreatedAt) {
  return 'bought something since';
}
Enter fullscreen mode Exit fullscreen mode

then one case per product: already owns the provider, already owns part of the bundle, already Premium, already owns the Assessment Centre, bought Interview Access since.

Returning the reason rather than a boolean is worth the extra type. It goes straight into the log line, so "why did this person not get the email" is answerable from one grep instead of a re-run.

Two of those cases carry real decisions.

"Bought since" is read from what they own, not from history. For the one-off unlocks, owning the thing and having bought it are the same statement, and reading ownership needs no extra query or new column. Interview Access can be bought more than once, so it is the only product that gets a second query, for a purchase row created after the session.

The bundle counts as bought when either half is owned. The comment is the clearest sentence in the file:

 * The bundle counts as bought when either half is owned: they have since made
 * a choice between the options, and a reminder about the other half would be
 * selling, not reminding.
Enter fullscreen mode Exit fullscreen mode

Someone who opened the bundle checkout and then bought one half has decided. Emailing them about the other half is an upsell wearing a reminder's clothes.

The dedupe is one Redis key, and it fails closed

No new table, no column, no job:

const key = abandonedEmailKey(purchase.userId);
const claimed = await redis.set(key, session.id, { nx: true, ex: ABANDONED_EMAIL_COOLDOWN_SECONDS });
if (claimed === null) return; // reminded within 14 days
Enter fullscreen mode Exit fullscreen mode

SET NX with a 14-day TTL. The key is per user, not per product, so someone who opens and closes four different checkouts in an afternoon gets one email rather than four. The value stored is the session id, which makes the key self-explaining when you look at it in a console.

The branch above it is the one I like:

if (!redis) {
  logDebug('[abandoned-checkout] Redis not configured, not sending without the dedupe');
  return;
}
Enter fullscreen mode Exit fullscreen mode

Without Redis, nothing is sent. The module states the trade: "a duplicate here is worse than a missing reminder". That is the opposite of how the inbound-email path in the same codebase handles a Redis outage, which fails open, because dropping a customer's support email is worse than handling it twice. Same mechanism, opposite default, both written down.

If the send fails, the claim is handed back:

const error = await sendRawEmail(buildAbandonedCheckoutEmail(purchase, buyer!)).then(
  (result) => result.error,
  (thrown: unknown) => thrown
);
if (error) {
  await redis.del(key).catch(() => undefined);
  logError('[abandoned-checkout] Send failed', error);
  return;
}
Enter fullscreen mode Exit fullscreen mode

The two-argument .then() flattens "the API returned an error field" and "the call threw" into one value, so there is a single error path instead of a try inside a try. Claim, send, release on failure, in that order, which is the same shape the lifecycle email cron uses.

The one bit of copy that is not marketing

Each product's email carries an includes list and, optionally, one sentence about what it does not include:

  • on a provider unlock: "Scores and feedback reports are not included. They are a separate purchase."
  • on Premium: "It does not unlock any games. Those are bought per provider."

Those exist because buyers mix the two up, and because the entitlements genuinely are orthogonal: the plan tier gates scores and feedback, provider unlocks gate play, and neither implies the other. An email that reminded someone to finish buying Premium while letting them believe it unlocks the games would convert better and generate a refund request.

The button goes to the offer rather than the dashboard. A provider unlock lands on /dashboard/games?unlock=<provider>, which opens the unlock dialog on arrival. Premium lands on the feedback page, with its own reason given inline: a game's start screen has nothing to buy.

The email also carries List-Unsubscribe and List-Unsubscribe-Post: List-Unsubscribe=One-Click, so the one-click unsubscribe in Gmail works without opening the message.

20 tests cover the decision function and the copy, which is possible because the only impure parts of the module are two queries, one Redis call and one send.

See it

The products the email describes, and the separation it is careful about, are both public.

Open the pricing page. The provider unlock and the scores purchase are separate cards for the reason the email's "not included" sentence spells out. Nothing on that page offers a discount for hesitating, which is the same decision as the email's.

If you want to trigger the path itself: sign in, start a checkout from that page, and close the tab without paying. Nothing arrives immediately, because the trigger is the session's own expiry, and that is an hour away. One email arrives after it, and a second abandoned checkout in the next fortnight produces nothing at all.

The products the copy is built from are listed on their own pages too: the interview practice page and the assessment centre page sell the two the email has hand-written includes lists for.

Top comments (0)