How to Calculate Churn Rate from Stripe

Stripe API · Updated 16 November 2026

TL;DR

Stripe does not return a churn field. List subscriptions with status active, trialing, past_due, paused, unpaid, and canceled, then list subscription events. Customer churn is the starting customers who have no qualifying subscription at periodEnd, divided by the starting count. Gross MRR churn adds contraction to canceled MRR before that division. Net MRR churn subtracts expansion. The default book counts status active after the trial has ended. past_due and paused stay out unless you opt in. cancel_at_period_end stays in until ended_at.

The churn rate glossary is the definition. This page is the Stripe procedure. Monthly prices come from the same normalizer as how to calculate MRR from the Stripe API. A single subscriptions export can be normalized in the browser with the Stripe MRR CSV calculator. That page does not call the API, does not upload the file, and does not return a churn rate. The SaaS metrics dashboard template is $59 once. Its overview does not compute churn. The live demo uses sample data.

License
$59 once
Refund
7-day no-questions refund
Stack
Next.js 16, shadcn/ui, Recharts, Postgres, Drizzle, Clerk, optional Stripe

Customer churn, gross MRR churn, and net MRR churn

Churn rate on the glossary page is the starting-base formula. This guide uses that denominator and shows the Stripe objects that fill it. Monthly recurring revenue here is each subscription item normalized to one month. A one-time charge is outside both rates. Cash collected this month is outside both rates.

RateNumerator over starting base
Customer (logo) churnStarting customers with no qualifying subscription at periodEnd / starting customers
Gross MRR churn(Churned MRR + contraction MRR) / starting MRR
Net MRR churn(Churned MRR + contraction MRR - expansion MRR) / starting MRR
Net revenue retention(Starting MRR − churned MRR − contraction MRR + expansion MRR) / starting MRR

Churned MRR is the starting MRR of customers who are gone at the end. Contraction is the decrease for customers who stay. Expansion is the increase for customers who were already in the starting book, including a second subscription added for that same customer. New MRR and reactivation MRR are reported beside the rates and left out of the numerator and the denominator. A negative net MRR churn means expansion was larger than the losses. Net revenue retention above 100% is that same case. How to calculate net revenue retention from Stripe is GRR and NRR on this book, including the cohort form. How to calculate customer lifetime value from Stripe divides ARPU by this customer churn fraction. Churn of zero makes that quotient undefined.

The window is half-open on the right for events: created at or after periodStart and before periodEnd. The ending book is the state at periodEnd. A subscription whose ended_at equals periodEnd is churned in this window and absent from the next window's start.

  1. Choose the window and which churn rate you are reporting
  2. List subscriptions for each status you might count
  3. List subscription events inside the 30-day retention window
  4. Mark who was active at the start and at the end
  5. Split churned, contraction, expansion, new, and reactivation MRR
  6. Compare the result with Billing analytics and a CSV export

Why Stripe Billing analytics can disagree

Stripe's Billing analytics page documents the Dashboard rules. The figures in this section are Stripe's own examples from that page, checked 16 November 2026. They are illustrations of the formula, and they are separate from the hypothetical book further down.

  • Dashboard MRR is the monthly-normalized value of active and past_due subscriptions. Taxes, free plans, and metered products are excluded. A legacy trial that uses trial_endexcludes the whole subscription. Stripe's example is 100 subscribers at 100 USD per month plus 50 subscribers at 600 USD per year: (100 × 100) + (50 × (600 / 12)) = 12,500 USD. This function leaves past_due out unless you pass includePastDue: true.
  • Active subscribers on that page are customers with positive MRR in active or past_due. One customer with several subscriptions counts once. A 100% coupon can drop the customer out of that count when discounts are subtracted. This function still counts a $0 active subscription as a logo.
  • Subscriber churn rate is churned subscribers in the past 30 days divided by active subscribers from 30 days ago plus new subscribers in those 30 days. Stripe's example is 1,000 at the start, 100 new, and 100 churned: 100 / 1,100. This function divides by the starting customers only. New customers stay out of the denominator.
  • Churned revenue on the Dashboard is a sum, churned MRR plus contraction MRR. Stripe's example cancels a 120 USD yearly plan (10 USD of MRR) and downgrades 50 USD to 25 USD, for 35 USD of churned revenue. Gross MRR churn on this page is that kind of sum divided by starting MRR.
  • Configure metrics can count a cancellation when it is scheduled, or when the billing period ends, and can start the active-subscriber clock at subscription start or at the first successful payment. Changes take 24–48 hours. This function waits for ended_at.
  • Discount settings can subtract recurring discounts, one-time discounts, or both. Stripe says permanent recurring discounts are always subtracted. This code uses the MRR guide's rule: duration: once does not change MRR. Forever coupons apply. Repeating coupons apply while end is null or still in the future.
  • MRR growth can include an FX adjustment when Stripe converts currencies. Some explore filters are unavailable when the account bills in more than one currency. This function returns one book per currency and does not convert.
  • Prebuilt report date columns use UTC. Billing analytics charts use the account time zone, so a month boundary can move. Pass UTC periodStart and periodEnd into this function and use the same instants everywhere you compare.
  • Canceling a subscription can refund a prorated amount or the last payment. That refund changes cash. The function reads subscription items, and it does not read Refund or Charge objects.

1. List every status you might count

stripe.subscriptions.list takes one status at a time. Omitting it returns subscriptions that have not been canceled. That set still includes incomplete, unpaid, paused, trialing, and past_due. status=canceledreturns canceled subscriptions, including those on deleted customers. You need that list. A customer who left is no longer in the default list, so a snapshot of today's active rows has no memory of them.

There is no ended_at filter on the list call. The function pages each status with limit: 100 and autoPagingToArray, then keeps a subscription when start_date and ended_at put it inside the window. The safety cap is 100,000 records per status. That cap is local. Stripe's limit parameter stops at 100.

Expand data.discounts.source.coupon on the subscription list. Stripe allows four expand levels, so an item coupon needs a second call to subscriptionItems.list with data.discounts.source.coupon. An unexpanded coupon id does not change MRR. The MRR API guide is the full coupon, quantity, and interval write-up. This page calls that normalizer and does not restate the interval table.

2. List subscription events

events.list goes back up to 30 days. The snippet requests customer.subscription.created, customer.subscription.updated, customer.subscription.deleted, customer.subscription.paused, and customer.subscription.resumed in one types array. Pass either type or types. The API rejects both.

customer.subscription.deleted is sent when the subscription ends, including when a cancel_at_period_end subscription reaches the period end. Setting the flag sends customer.subscription.updated. customer.subscription.paused fires when status becomes paused. Pausing payment collection does not send it, because invoices continue and the status stays put.

An updated event can include previous_attributes.items. Stripe's event object sends the whole items array when any item changed. The function treats the earliest such array at or after a timestamp as the price book before that change. That is how a downgrade inside the month still has a starting MRR. The Subscription object itself only keeps the latest items.

customer.subscription.updated also fires on renewals and on other field edits. Those events are in the audit list. They change MRR only when previous_attributes includes items. If items changed and the previous array has no price, the report increments itemChangesUnreconstructed and keeps the current items. Read that counter before you trust contraction and expansion.

The live call fetches events from the later of periodStartand 30 days ago, through now, so a window that ended last week can still rewind today's items. When periodStart is strictly older than 30 days, eventsLookbackIncomplete is true. ended_at still marks the cancellation. The old price does not. Store a snapshot, or store the events, when the month has to remain auditable.

3. Who counts at the start and at the end

subscriptionActiveAt is the policy. At timestamp T a subscription counts when start_date is at or before T and ended_at is null or later than T, and the status rules below pass.

  • active counts. trialing, or a trial_end still in the future, does not, unless you pass includeTrialing: true. Even then the MRR contribution stays 0 until the trial timestamp has passed. The recurring price is the post-trial price.
  • past_due is out unless includePastDue is true. The current status is the only past_due signal on the object. A subscription that was past_due on the 1st and active today is treated as active at both boundaries. Events older than 30 days cannot rebuild that gap.
  • paused is out unless includePaused is true. pause_collection is a different field. Status stays active, invoices continue, and the subscription stays in the book.
  • unpaid, incomplete, and incomplete_expired are out. Stripe's analytics page treats unpaid as no longer in MRR.
  • cancel_at_period_end: true with a null ended_at still counts. The report lists those rows as scheduledToCancelAtPeriodEnd. They are in the ending book.

A customer is one logo when any of their subscriptions qualify. Customer ids come from subscription.customer. Deleted customers still have an id on the canceled subscription, and that id is the logo.

4. Churn, contraction, expansion, new, and reactivation

Each qualifying subscription is passed to normalizeStripeSubscriptionMrr with status forced to active so a canceled row can still produce the MRR it had before ended_at. The normalizer's own status filter would otherwise drop it. Yearly prices divide by 12 times interval_count. Weekly prices use 52/12. Daily prices use 365/12. Metered and tiered prices are skipped and counted in skippedItems.

For each customer inside one currency:

  • Present at the start, absent at the end: add their starting MRR to churned MRR and count a churned logo.
  • Present at both boundaries, ending MRR lower: add the decrease to contraction. The logo stays.
  • Present at both boundaries, ending MRR higher: add the increase to expansion. A second subscription for the same customer is expansion, because the customer was already in the base.
  • Absent at the start, present at the end, with an earlier subscription whose ended_at is at or before periodStart: reactivation MRR.
  • Absent at the start and present at the end, with no earlier ended subscription: new MRR.

Gross, net, and net revenue retention then use the formulas in the first section. Currencies are separate books. A customer with one subscription in dollars and another in yen is counted in each book and listed in customersInMultipleCurrencies. Each amount stays in its own currency. Two currencies on a single subscription follow the MRR normalizer: the first priced currency is the book, and later items in another currency are skipped.

Endpoint comparison is the period rate. A customer who cancels on the 10th and resubscribes on the 20th is in both snapshots, so the logo rate does not move. The created and deleted events for that pair are in eventsInWindow. Read them when you need the path, not only the endpoints. A subscription that starts and ends inside the window, with no other live subscription, is startedAndEndedInPeriod. It is in neither snapshot, so it is outside the rate.

TypeScript

Install stripe. Copy lib/tools/stripe-mrr.ts with its MIT notice, and copy lib/guides/calculate-stripe-mrr.ts for createStripeClient. The file below is lib/guides/calculate-stripe-churn.ts. Pass the secret key only on the server.

lib/guides/calculate-stripe-churn.ts
/**
 * Customer (logo) churn and MRR churn from Stripe subscriptions.
 *
 * Stripe does not return a churn field. This file compares each customer's
 * normalized MRR at `periodStart` with their normalized MRR at `periodEnd`.
 * Monthly normalization is `normalizeStripeSubscriptionMrr` in
 * `lib/tools/stripe-mrr.ts` (MIT). Copy that file with this one. The Stripe
 * client factory lives in `lib/guides/calculate-stripe-mrr.ts`.
 *
 * Run the Stripe calls on the server. `STRIPE_SECRET_KEY` is a secret key.
 *
 * The Events API lists events going back up to 30 days
 * (https://docs.stripe.com/api/events/list). `ended_at`, `start_date`, and
 * `trial_end` still describe older cancellations. Item changes older than
 * that window are not on the Subscription object.
 */
import Stripe from "stripe"

import { createStripeClient } from "./calculate-stripe-mrr"
import {
  minorUnitFactor,
  normalizeStripeSubscriptionMrr,
  roundMajorCurrency,
  type StripeDiscountLike,
  type StripeSubscriptionItemLike,
} from "../tools/stripe-mrr"

export { createStripeClient }

/** Stripe documents `events.list` as going back up to 30 days. This cutoff is 30 * 24 hours. */
export const STRIPE_EVENT_RETENTION_SECONDS = 30 * 24 * 60 * 60

/**
 * Statuses this report lists. `incomplete` and `incomplete_expired` never
 * became a paying subscription. `status=all` includes them. `status=canceled`
 * is required because the default list omits canceled subscriptions.
 */
export const CHURN_LIST_STATUSES = ["active", "trialing", "past_due", "paused", "unpaid", "canceled"] as const

export const CHURN_EVENT_TYPES = [
  "customer.subscription.created",
  "customer.subscription.updated",
  "customer.subscription.deleted",
  "customer.subscription.paused",
  "customer.subscription.resumed",
] as const

/** Safety cap passed to `autoPagingToArray`. Stripe's list `limit` max is 100. This cap is local. */
const AUTO_PAGE_LIMIT = 100_000

/**
 * Expand on `subscriptions.list`. Four levels is the API maximum, so an item
 * coupon (`data.items.data.discounts.source.coupon`) is loaded later from
 * `subscriptionItems.list`. The net revenue retention guide uses this same list.
 */
export const SUBSCRIPTION_LIST_EXPAND = ["data.discounts.source.coupon", "data.items.data.discounts"] as const

export interface ChurnPolicy {
  /** Count `past_due` subscriptions as active. Default false. Stripe Billing MRR includes them. */
  includePastDue?: boolean
  /** Count `status: "paused"` subscriptions as active. Default false. `pause_collection` is not this status. */
  includePaused?: boolean
  /**
   * Count a customer who is still inside `trial_end` (or whose current status
   * is `trialing`). Default false. MRR stays 0 until the trial timestamp has
   * passed, because the recurring price is not in effect yet.
   */
  includeTrialing?: boolean
  /** Divisor for a three-decimal currency (BHD, JOD, KWD, OMR, TND). Pass 1000. */
  minorUnitFactor?: number
}

export interface ChurnWindowOptions extends ChurnPolicy {
  periodStart: Date
  periodEnd: Date
  /**
   * Clock for the 30-day event flag. `calculateChurnFromStripe` sets this to
   * the current time. Omit it when the events were stored by you.
   */
  now?: Date
}

export interface ChurnEventInput {
  id: string
  type: string
  /** Unix seconds. */
  created: number
  subscriptionId: string | null
  /**
   * True when `previous_attributes` included `items`. Stripe sends the whole
   * items array on `*.updated` when any item changed.
   */
  itemsChanged: boolean
  previousItems?: StripeSubscriptionItemLike[] | null
}

export interface ChurnSubscriptionInput {
  id: string
  customerId: string
  status: string
  /** Unix seconds. Subscription `start_date`. */
  startDate: number
  /** Unix seconds. Subscription `ended_at`. Null when the subscription has not ended. */
  endedAt: number | null
  /** Unix seconds. Subscription `trial_end`. */
  trialEnd: number | null
  cancelAtPeriodEnd: boolean
  /** Latest items on the Subscription. Ending MRR uses these unless a later event rewinds them. */
  items: StripeSubscriptionItemLike[]
  discounts?: Array<string | StripeDiscountLike> | null
}

export interface CurrencyChurnReport {
  currency: string
  startingCustomers: number
  endingCustomers: number
  churnedCustomers: number
  customerChurnRate: number | null
  /** Major units, rounded like the MRR normalizer. */
  startingMrr: number
  endingMrr: number
  churnedMrr: number
  contractionMrr: number
  expansionMrr: number
  newMrr: number
  reactivationMrr: number
  /** (churned MRR + contraction MRR) / starting MRR. Null when starting MRR is 0. */
  grossMrrChurnRate: number | null
  /** (churned MRR + contraction MRR - expansion MRR) / starting MRR. */
  netMrrChurnRate: number | null
  /** (starting MRR - churned MRR - contraction MRR + expansion MRR) / starting MRR. New and reactivation are excluded. */
  netRevenueRetention: number | null
}

export interface ChurnReport {
  periodStart: string
  periodEnd: string
  byCurrency: CurrencyChurnReport[]
  logos: {
    startingCustomers: number
    endingCustomers: number
    churnedCustomers: number
    customerChurnRate: number | null
    newCustomers: number
    reactivationCustomers: number
  }
  /** Subscriptions that were active at the start and not at the end. A customer with two subscriptions can lose one and stay a logo. */
  subscriptionsEndedDuringWindow: number
  subscriptionsActiveAtStart: number
  subscriptionsActiveAtEnd: number
  /** Still active at `periodEnd` with `cancel_at_period_end`. They are in the ending book. */
  scheduledToCancelAtPeriodEnd: number
  /** Customers with no qualifying subscription at either boundary who started and ended one inside the window. */
  startedAndEndedInPeriod: number
  /** Customers with qualifying MRR in more than one currency. Each currency is its own book. Amounts are not converted. */
  customersInMultipleCurrencies: number
  pastDueExcluded: number
  pausedExcluded: number
  /** True when `periodStart` is strictly older than 30 days before `now`. */
  eventsLookbackIncomplete: boolean
  /** `customer.subscription.updated` events whose item snapshot could not be read. */
  itemChangesUnreconstructed: number
  /** Events whose `created` is inside [periodStart, periodEnd). */
  eventsInWindow: number
  skippedItems: number
  unexpandedDiscounts: number
}

interface Quote {
  mrr: number
  currency: string | null
  skippedItems: number
  unexpandedDiscounts: number
}

interface CurrencyBucket {
  startMrr: number
  endMrr: number
  seenStart: boolean
  seenEnd: boolean
}

interface CustomerBook {
  currencies: Map<string, CurrencyBucket>
  activeStart: boolean
  activeEnd: boolean
  hadEndedBeforeStart: boolean
  startedAndEnded: boolean
}

export function subscriptionActiveAt(
  subscription: {
    status?: string | null
    startDate: number
    endedAt?: number | null
    trialEnd?: number | null
  },
  at: number,
  options: ChurnPolicy = {},
): boolean {
  if (!Number.isFinite(subscription.startDate) || subscription.startDate > at) return false
  if (subscription.endedAt != null && subscription.endedAt <= at) return false

  const status = subscription.status ?? ""
  if (status === "canceled" && subscription.endedAt == null) return false
  if (status === "incomplete" || status === "incomplete_expired" || status === "unpaid") return false
  if (status === "paused" && !options.includePaused) return false
  if (status === "past_due" && !options.includePastDue) return false

  const inTrial = status === "trialing" || (subscription.trialEnd != null && subscription.trialEnd > at)
  if (inTrial && !options.includeTrialing) return false

  return status === "active" || status === "trialing" || status === "past_due" || status === "paused" || status === "canceled"
}

function inTrialAt(subscription: ChurnSubscriptionInput, at: number): boolean {
  if (subscription.status === "trialing") return true
  return subscription.trialEnd != null && subscription.trialEnd > at
}

function usableItems(items: StripeSubscriptionItemLike[] | null | undefined): items is StripeSubscriptionItemLike[] {
  if (!items?.length) return false
  return items.some((item) => {
    const amount = item.price?.unit_amount
    const decimal = item.price?.unit_amount_decimal
    return (typeof amount === "number" && Number.isFinite(amount)) || (typeof decimal === "string" && decimal.trim() !== "")
  })
}

/**
 * Items as of `at`, before any event timestamped at or after `at`.
 * The earliest `itemsChanged` event at or after `at` carries the previous items.
 */
export function itemsAsOf(
  subscription: ChurnSubscriptionInput,
  events: readonly ChurnEventInput[],
  at: number,
): { items: StripeSubscriptionItemLike[]; unreconstructed: boolean } {
  const itemEvents = events
    .filter((event) => event.subscriptionId === subscription.id && event.created >= at && event.itemsChanged)
    .sort((left, right) => left.created - right.created)
  const first = itemEvents[0]
  if (!first) return { items: subscription.items, unreconstructed: false }
  if (!usableItems(first.previousItems)) return { items: subscription.items, unreconstructed: true }
  return { items: first.previousItems, unreconstructed: false }
}

function quoteItems(
  subscription: ChurnSubscriptionInput,
  items: StripeSubscriptionItemLike[],
  at: number,
  options: ChurnPolicy,
): Quote {
  const normalized = normalizeStripeSubscriptionMrr(
    [
      {
        status: "active",
        discounts: subscription.discounts ?? [],
        items: { data: items },
      },
    ],
    {
      now: new Date(at * 1000),
      minorUnitFactor: options.minorUnitFactor,
    },
  )
  return {
    mrr: normalized.mrr,
    currency: normalized.currency,
    skippedItems: normalized.skippedItems,
    unexpandedDiscounts: normalized.unexpandedDiscounts,
  }
}

function ratio(part: number, whole: number): number | null {
  if (!(whole > 0)) return null
  return part / whole
}

function roundForCurrency(amount: number, currency: string, options: ChurnPolicy): number {
  const factor = options.minorUnitFactor && options.minorUnitFactor > 0 ? options.minorUnitFactor : minorUnitFactor(currency)
  return roundMajorCurrency(amount, factor)
}

function emptyReport(periodStart: Date, periodEnd: Date, eventsLookbackIncomplete: boolean, eventsInWindow: number): ChurnReport {
  return {
    periodStart: periodStart.toISOString(),
    periodEnd: periodEnd.toISOString(),
    byCurrency: [],
    logos: {
      startingCustomers: 0,
      endingCustomers: 0,
      churnedCustomers: 0,
      customerChurnRate: null,
      newCustomers: 0,
      reactivationCustomers: 0,
    },
    subscriptionsEndedDuringWindow: 0,
    subscriptionsActiveAtStart: 0,
    subscriptionsActiveAtEnd: 0,
    scheduledToCancelAtPeriodEnd: 0,
    startedAndEndedInPeriod: 0,
    customersInMultipleCurrencies: 0,
    pastDueExcluded: 0,
    pausedExcluded: 0,
    eventsLookbackIncomplete,
    itemChangesUnreconstructed: 0,
    eventsInWindow,
    skippedItems: 0,
    unexpandedDiscounts: 0,
  }
}

export function calculateChurnFromListedSubscriptions(
  subscriptions: readonly ChurnSubscriptionInput[],
  events: readonly ChurnEventInput[] = [],
  options: ChurnWindowOptions,
): ChurnReport {
  const periodStart = Math.floor(options.periodStart.getTime() / 1000)
  const periodEnd = Math.floor(options.periodEnd.getTime() / 1000)
  if (!Number.isFinite(periodStart) || !Number.isFinite(periodEnd) || periodEnd <= periodStart) {
    throw new Error("periodEnd must be after periodStart")
  }

  const nowUnix = options.now ? Math.floor(options.now.getTime() / 1000) : null
  const eventsLookbackIncomplete =
    nowUnix != null && periodStart < nowUnix - STRIPE_EVENT_RETENTION_SECONDS
  const eventsInWindow = events.filter((event) => event.created >= periodStart && event.created < periodEnd).length
  const report = emptyReport(options.periodStart, options.periodEnd, eventsLookbackIncomplete, eventsInWindow)

  const customers = new Map<string, CustomerBook>()
  const customerOf = (id: string): CustomerBook => {
    const existing = customers.get(id)
    if (existing) return existing
    const created: CustomerBook = {
      currencies: new Map(),
      activeStart: false,
      activeEnd: false,
      hadEndedBeforeStart: false,
      startedAndEnded: false,
    }
    customers.set(id, created)
    return created
  }

  const bucketOf = (customer: CustomerBook, currency: string): CurrencyBucket => {
    const existing = customer.currencies.get(currency)
    if (existing) return existing
    const created: CurrencyBucket = { startMrr: 0, endMrr: 0, seenStart: false, seenEnd: false }
    customer.currencies.set(currency, created)
    return created
  }

  for (const subscription of subscriptions) {
    const activeStart = subscriptionActiveAt(subscription, periodStart, options)
    const activeEnd = subscriptionActiveAt(subscription, periodEnd, options)
    const customer = customerOf(subscription.customerId || `subscription:${subscription.id}`)
    if (activeStart) {
      customer.activeStart = true
      report.subscriptionsActiveAtStart += 1
    }
    if (activeEnd) {
      customer.activeEnd = true
      report.subscriptionsActiveAtEnd += 1
      if (subscription.cancelAtPeriodEnd) report.scheduledToCancelAtPeriodEnd += 1
    }
    if (activeStart && !activeEnd) report.subscriptionsEndedDuringWindow += 1
    if (subscription.endedAt != null && subscription.endedAt <= periodStart) customer.hadEndedBeforeStart = true
    if (
      subscription.startDate >= periodStart &&
      subscription.startDate < periodEnd &&
      subscription.endedAt != null &&
      subscription.endedAt >= periodStart &&
      subscription.endedAt < periodEnd
    ) {
      customer.startedAndEnded = true
    }

    const overlaps =
      subscription.startDate < periodEnd && (subscription.endedAt == null || subscription.endedAt > periodStart)
    if (overlaps && subscription.status === "past_due" && !options.includePastDue) report.pastDueExcluded += 1
    if (overlaps && subscription.status === "paused" && !options.includePaused) report.pausedExcluded += 1

    const startItems = itemsAsOf(subscription, events, periodStart)
    const endItems = itemsAsOf(subscription, events, periodEnd)
    if (startItems.unreconstructed || endItems.unreconstructed) report.itemChangesUnreconstructed += 1

    const apply = (at: number, items: StripeSubscriptionItemLike[], side: "start" | "end") => {
      if (inTrialAt(subscription, at)) return
      const quote = quoteItems(subscription, items, at, options)
      report.skippedItems += quote.skippedItems
      report.unexpandedDiscounts += quote.unexpandedDiscounts
      if (!quote.currency) return
      const bucket = bucketOf(customer, quote.currency)
      if (side === "start") {
        bucket.seenStart = true
        bucket.startMrr += quote.mrr
      } else {
        bucket.seenEnd = true
        bucket.endMrr += quote.mrr
      }
    }

    if (activeStart) apply(periodStart, startItems.items, "start")
    if (activeEnd) apply(periodEnd, endItems.items, "end")
  }

  type CurrencyTotals = {
    currency: string
    startingCustomers: number
    endingCustomers: number
    churnedCustomers: number
    startingMrr: number
    endingMrr: number
    churnedMrr: number
    contractionMrr: number
    expansionMrr: number
    newMrr: number
    reactivationMrr: number
  }
  const totals = new Map<string, CurrencyTotals>()
  const totalsOf = (currency: string): CurrencyTotals => {
    const existing = totals.get(currency)
    if (existing) return existing
    const created: CurrencyTotals = {
      currency,
      startingCustomers: 0,
      endingCustomers: 0,
      churnedCustomers: 0,
      startingMrr: 0,
      endingMrr: 0,
      churnedMrr: 0,
      contractionMrr: 0,
      expansionMrr: 0,
      newMrr: 0,
      reactivationMrr: 0,
    }
    totals.set(currency, created)
    return created
  }

  for (const customer of customers.values()) {
    if (customer.activeStart) report.logos.startingCustomers += 1
    if (customer.activeEnd) report.logos.endingCustomers += 1
    const reactivated = !customer.activeStart && customer.activeEnd && customer.hadEndedBeforeStart
    if (customer.activeStart && !customer.activeEnd) report.logos.churnedCustomers += 1
    else if (reactivated) report.logos.reactivationCustomers += 1
    else if (!customer.activeStart && customer.activeEnd) report.logos.newCustomers += 1
    if (!customer.activeStart && !customer.activeEnd && customer.startedAndEnded) report.startedAndEndedInPeriod += 1
    if (customer.currencies.size > 1) report.customersInMultipleCurrencies += 1

    for (const [currency, bucket] of customer.currencies) {
      const startMrr = roundForCurrency(bucket.startMrr, currency, options)
      const endMrr = roundForCurrency(bucket.endMrr, currency, options)
      const row = totalsOf(currency)
      if (bucket.seenStart) row.startingCustomers += 1
      if (bucket.seenEnd) row.endingCustomers += 1
      row.startingMrr += startMrr
      row.endingMrr += endMrr
      if (bucket.seenStart && !bucket.seenEnd) {
        row.churnedCustomers += 1
        row.churnedMrr += startMrr
      } else if (bucket.seenStart && bucket.seenEnd) {
        const delta = roundForCurrency(endMrr - startMrr, currency, options)
        if (delta < 0) row.contractionMrr += roundForCurrency(-delta, currency, options)
        else if (delta > 0) row.expansionMrr += delta
      } else if (!bucket.seenStart && bucket.seenEnd) {
        if (reactivated) row.reactivationMrr += endMrr
        else row.newMrr += endMrr
      }
    }
  }

  report.logos.customerChurnRate = ratio(report.logos.churnedCustomers, report.logos.startingCustomers)
  report.byCurrency = [...totals.values()]
    .map((row) => {
      const startingMrr = roundForCurrency(row.startingMrr, row.currency, options)
      const endingMrr = roundForCurrency(row.endingMrr, row.currency, options)
      const churnedMrr = roundForCurrency(row.churnedMrr, row.currency, options)
      const contractionMrr = roundForCurrency(row.contractionMrr, row.currency, options)
      const expansionMrr = roundForCurrency(row.expansionMrr, row.currency, options)
      const newMrr = roundForCurrency(row.newMrr, row.currency, options)
      const reactivationMrr = roundForCurrency(row.reactivationMrr, row.currency, options)
      return {
        currency: row.currency,
        startingCustomers: row.startingCustomers,
        endingCustomers: row.endingCustomers,
        churnedCustomers: row.churnedCustomers,
        customerChurnRate: ratio(row.churnedCustomers, row.startingCustomers),
        startingMrr,
        endingMrr,
        churnedMrr,
        contractionMrr,
        expansionMrr,
        newMrr,
        reactivationMrr,
        grossMrrChurnRate: ratio(churnedMrr + contractionMrr, startingMrr),
        netMrrChurnRate: ratio(churnedMrr + contractionMrr - expansionMrr, startingMrr),
        netRevenueRetention: ratio(startingMrr - churnedMrr - contractionMrr + expansionMrr, startingMrr),
      }
    })
    .sort((left, right) => left.currency.localeCompare(right.currency))

  return report
}

type RawItem = {
  quantity?: number | null
  discounts?: Array<string | Stripe.Discount> | null
  price?: Stripe.Price | null
}

function toDiscounts(
  discounts: Array<string | Stripe.Discount> | null | undefined,
): Array<string | StripeDiscountLike> {
  if (!discounts?.length) return []
  return discounts.map((discount) => {
    if (typeof discount === "string") return discount
    const coupon = discount.source?.coupon
    if (!coupon || typeof coupon === "string") return discount.id
    return {
      end: discount.end,
      source: {
        coupon: {
          percent_off: coupon.percent_off,
          amount_off: coupon.amount_off,
          currency: coupon.currency,
          duration: coupon.duration,
        },
      },
    }
  })
}

function toItem(item: RawItem): StripeSubscriptionItemLike | null {
  const price = item.price
  if (!price) return null
  return {
    quantity: item.quantity ?? null,
    discounts: toDiscounts(item.discounts),
    price: {
      unit_amount: price.unit_amount,
      unit_amount_decimal: price.unit_amount_decimal,
      currency: price.currency,
      billing_scheme: price.billing_scheme,
      recurring: price.recurring
        ? {
            interval: price.recurring.interval,
            interval_count: price.recurring.interval_count,
            usage_type: price.recurring.usage_type,
          }
        : null,
    },
  }
}

function itemCouponsAreIds(items: Stripe.SubscriptionItem[]): boolean {
  return items.some((item) =>
    item.discounts.some((discount) => typeof discount !== "string" && typeof discount.source.coupon === "string"),
  )
}

async function loadItems(stripe: Stripe, subscription: Stripe.Subscription, pageLimit: number): Promise<StripeSubscriptionItemLike[]> {
  let items = subscription.items.data
  if (subscription.items.has_more || itemCouponsAreIds(items)) {
    items = await stripe.subscriptionItems
      .list({
        subscription: subscription.id,
        limit: 100,
        expand: ["data.price", "data.discounts.source.coupon"],
      })
      .autoPagingToArray({ limit: pageLimit })
  }
  return items.map((item) => toItem(item)).filter((item): item is StripeSubscriptionItemLike => item !== null)
}

export async function toChurnSubscriptionInput(
  stripe: Stripe,
  subscription: Stripe.Subscription,
  pageLimit: number,
): Promise<ChurnSubscriptionInput> {
  return {
    id: subscription.id,
    customerId: customerIdFrom(subscription.customer, subscription.id),
    status: subscription.status,
    startDate: subscription.start_date,
    endedAt: subscription.ended_at,
    trialEnd: subscription.trial_end,
    cancelAtPeriodEnd: subscription.cancel_at_period_end,
    discounts: toDiscounts(subscription.discounts),
    items: await loadItems(stripe, subscription, pageLimit),
  }
}

export function toChurnEventInput(event: Stripe.Event): ChurnEventInput | null {
  const subscription = eventSubscription(event)
  if (!subscription) return null
  const previous = previousItemsFromEvent(event)
  return {
    id: event.id,
    type: event.type,
    created: event.created,
    subscriptionId: subscription.id,
    itemsChanged: previous.itemsChanged,
    previousItems: previous.previousItems,
  }
}

function customerIdFrom(customer: Stripe.Subscription["customer"], subscriptionId: string): string {
  if (typeof customer === "string" && customer) return customer
  if (customer && typeof customer === "object" && "id" in customer && customer.id) return customer.id
  return `subscription:${subscriptionId}`
}

function previousItemsFromEvent(event: Stripe.Event): { itemsChanged: boolean; previousItems: StripeSubscriptionItemLike[] | null } {
  const previous = event.data.previous_attributes as { items?: { data?: RawItem[] } } | undefined
  if (!previous || !("items" in previous)) return { itemsChanged: false, previousItems: null }
  const mapped = (previous.items?.data ?? []).map((item) => toItem(item)).filter((item): item is StripeSubscriptionItemLike => item !== null)
  return { itemsChanged: true, previousItems: usableItems(mapped) ? mapped : null }
}

function eventSubscription(event: Stripe.Event): Stripe.Subscription | null {
  const object = event.data.object as { object?: string }
  if (object.object !== "subscription") return null
  return event.data.object as Stripe.Subscription
}

export interface CalculateStripeChurnOptions extends ChurnWindowOptions {
  /** Override the auto-pagination cap. */
  pageLimit?: number
}

export async function calculateChurnFromStripe(
  stripe: Stripe,
  options: CalculateStripeChurnOptions,
): Promise<ChurnReport> {
  const pageLimit = options.pageLimit ?? AUTO_PAGE_LIMIT
  const now = options.now ?? new Date()
  const periodStart = Math.floor(options.periodStart.getTime() / 1000)
  const nowUnix = Math.floor(now.getTime() / 1000)
  const retentionFloor = nowUnix - STRIPE_EVENT_RETENTION_SECONDS
  const eventGte = Math.max(periodStart, retentionFloor)

  if (periodStart < retentionFloor) {
    console.warn(
      `[Data Lighthouse] Stripe events are listed going back up to 30 days. Churn window start ${options.periodStart.toISOString()} is older than that, so item changes before the retained events are not reconstructed.`,
    )
  }

  const statusPages = await Promise.all(
    CHURN_LIST_STATUSES.map(async (status) => {
      const subscriptions = await stripe.subscriptions
        .list({
          status,
          limit: 100,
          expand: [...SUBSCRIPTION_LIST_EXPAND],
        })
        .autoPagingToArray({ limit: pageLimit })
      if (subscriptions.length >= pageLimit) {
        console.warn(`[Data Lighthouse] Stripe auto-pagination stopped at ${pageLimit} ${status} subscriptions.`)
      }
      return subscriptions
    }),
  )

  const seen = new Set<string>()
  const listed: ChurnSubscriptionInput[] = []
  for (const subscription of statusPages.flat()) {
    if (seen.has(subscription.id)) continue
    seen.add(subscription.id)
    listed.push(await toChurnSubscriptionInput(stripe, subscription, pageLimit))
  }

  const events = await stripe.events
    .list({
      types: [...CHURN_EVENT_TYPES],
      created: { gte: eventGte, lt: nowUnix + 1 },
      limit: 100,
    })
    .autoPagingToArray({ limit: pageLimit })
  if (events.length >= pageLimit) {
    console.warn(`[Data Lighthouse] Stripe auto-pagination stopped at ${pageLimit} subscription events.`)
  }

  const mappedEvents: ChurnEventInput[] = []
  for (const event of events) {
    const mapped = toChurnEventInput(event)
    if (mapped) mappedEvents.push(mapped)
  }

  return calculateChurnFromListedSubscriptions(listed, mappedEvents, { ...options, now })
}

calculateChurnFromStripe(stripe, options) lists the six statuses, lists the subscription events, and calls calculateChurnFromListedSubscriptions. The listed-subscription function is the same math for objects you already have in tests. byCurrency holds the rates. logos counts a customer once across currencies.

Route handler and server action

Both call the same function for the trailing 30 days, which fits inside the Events API retention when you run it now. A calendar month that started more than 30 days ago still has ended_at for cancellations. Set eventsLookbackIncomplete as a warning on item changes, and keep a snapshot if that month has to stay exact.

app/api/stripe-churn/route.ts
import { NextResponse } from "next/server"
import { createStripeClient } from "@/lib/guides/calculate-stripe-mrr"
import { calculateChurnFromStripe } from "@/lib/guides/calculate-stripe-churn"

export async function GET() {
  const key = process.env.STRIPE_SECRET_KEY
  if (!key) {
    return NextResponse.json({ error: "Missing STRIPE_SECRET_KEY" }, { status: 500 })
  }

  const periodEnd = new Date()
  const periodStart = new Date(periodEnd.getTime() - 30 * 24 * 60 * 60 * 1000)
  const report = await calculateChurnFromStripe(createStripeClient(key), {
    periodStart,
    periodEnd,
  })

  return NextResponse.json(report)
}
app/stripe-churn/actions.ts
"use server"

import { createStripeClient } from "@/lib/guides/calculate-stripe-mrr"
import { calculateChurnFromStripe } from "@/lib/guides/calculate-stripe-churn"

export async function churnForTrailing30Days() {
  const key = process.env.STRIPE_SECRET_KEY
  if (!key) throw new Error("Missing STRIPE_SECRET_KEY")

  const periodEnd = new Date()
  const periodStart = new Date(periodEnd.getTime() - 30 * 24 * 60 * 60 * 1000)
  return calculateChurnFromStripe(createStripeClient(key), { periodStart, periodEnd })
}

CSV path, without the API

In the Dashboard, open Billing, then Subscriptions, and export the CSV. Stripe's public docs do not publish a fixed header row for that export. The Stripe MRR CSV calculator maps columns in the browser, calls the same monthly normalizer once per currency, and does not upload the file. Active rows are included. Trialing and past_due are optional switches on that page.

One export is one snapshot. Save the file on the first day of the period and export again at periodEnd. Normalize each file. Customer churn still needs a customer id on both files so you can see who disappeared. Gross MRR churn from the two totals alone mixes new MRR into the ending number. Subtract new logos before you call the remainder contraction, or use the API report, which splits the lines. The CSV page does not compute that split.

Edge-case checklist

  1. Stopping after the first page. The default page size is 10. Canceled subscriptions live on their own status list.
  2. Using today's active list as the starting book. People who already canceled are missing, so churn looks like zero.
  3. Counting cancel_at_period_end on the day the customer clicks. ended_at is the exit.
  4. Treating a paused collection the same as status: paused. Collection pauses stay active.
  5. Including a trial that never converts. trial_end in the future is outside the default book.
  6. Calling a downgrade a lost logo. The customer remains. The dollars are contraction.
  7. Putting a second subscription for an existing customer into new MRR. The customer was in the base, so the increase is expansion.
  8. Adding new MRR to the denominator. This page keeps the starting base. Dashboard subscriber churn adds new subscribers.
  9. Dividing a yearly cancellation by the full yearly price. $120 a year is $10 of MRR.
  10. Adding USD and JPY, or dividing a zero-decimal currency by 100. The report keeps one book per currency.
  11. Subtracting a refund from MRR. Refunds are cash. The price on the subscription did not change.
  12. Trusting item history from the current Subscription object. Previous quantities live on the updated event, and events older than 30 days are gone.
  13. Ignoring itemChangesUnreconstructed. The current price was used for both boundaries, so contraction can be missing.
  14. Letting a subscription that starts and ends inside the window into the rate. It is in neither snapshot.
  15. Reading past_due from history. The object only has the current status.

Hypothetical January book

Every figure below is hypothetical. It is labelled example data for January 2026, from 2026-01-01T00:00:00.000Z to 2026-02-01T00:00:00.000Z. It is a made-up book passed through calculateChurnFromListedSubscriptions. It is separate from the public demo, from any customer account, and from Stripe's documentation examples above.

SubscriptionWhat the row isMRR at 1 JanMRR at 1 Feb
Keep$100 every month. No subscription event in January.$100.00$100.00
Annual$120 every year. Normalized MRR is $10. The yearly price is not added whole.$10.00$10.00
Downgrade2 × $20 at 1 January. A 12 January updated event records the previous quantity. The subscription ends January at 1 × $20.$40.00$20.00
Upgrade$30 at 1 January. An 18 January updated event records the previous price. The subscription ends January at $50.$30.00$50.00
Cancel$20 every month. ended_at is 15 January. Status is canceled. The deleted event has no previous items.$20.00$0.00

Together, the five subscriptions are 5 starting customers and $200.00 of starting MRR. 1 customer cancels, so customer churn is 20%. Churned MRR is $20.00. Contraction is $20.00. Expansion is $20.00. Gross MRR churn is 20%. Net MRR churn is 10%. Net revenue retention is 90%. Ending MRR of this book is $180.00, which is the starting $200.00 minus churned and contraction plus expansion. New MRR and reactivation MRR are $0.00 and $0.00. The 20% logo rate and the 20% gross MRR rate describe the same month and different questions. One logo left. The downgrade moved dollars without removing a logo, and the upgrade put those dollars back.

The same function on one extra labelled case at a time:

  • Two subscriptions, one customer, $10 and $10. One ends on 20 January. Logo churn is 0%. Subscriptions that ended: 1. Contraction is $10.00.
  • A trial with trial_end on 15 January converts to $25. Starting customers are 0. New MRR is $25.00.
  • A subscription created on 8 January at $15. New customers: 1. New MRR is $15.00. It is outside the churn denominator.
  • A subscription that ended on 1 December 2025, then a new $12 subscription on 8 January. Reactivation customers: 1. Reactivation MRR is $12.00. New MRR stays $0.00.
  • A subscription that starts on 10 January and ends on 20 January. startedAndEndedInPeriod is 1. Customer churn is undefined because the starting base is empty.
  • cancel_at_period_end with no ended_at. Customer churn is 0%. Scheduled cancellations still in the ending book: 1. MRR stays $10.00.
  • A past_due subscription at $70. Excluded rows: 1. Starting customers: 0. With includePastDue: true, starting MRR is $70.00.
  • Status paused at $40. Excluded rows: 1. Starting customers: 0.
  • A $30 price with a forever 100% coupon. The logo stays, starting customers 1, starting MRR $0.00. Gross MRR churn is undefined because the starting MRR is zero.
  • An updated event that says items changed and sends no previous price. itemChangesUnreconstructed is 1. Both boundaries use the current $20.00, so a downgrade that lacked a snapshot is invisible.
  • The same five USD subscriptions plus ¥1,500 a month. The USD book is still $200.00 of starting MRR and 20% customer churn. The yen book is ¥1,500 on its own. Logos across both currencies are 6. The yen amount is not added to the dollars.

Put the report next to the dashboard

The SaaS metrics dashboard template is $59 once. You host the Next.js app and set STRIPE_SECRET_KEY there. That key and the signed-in revenue route are on the Next.js Stripe analytics dashboard. The overview normalizes active subscriptions to MRR and shows ARR as that MRR times 12. It does not compute churn, so the report from this page is the piece you add if you want the rate beside revenue and visitors. The live demo renders the overview with sample data and does not call Stripe.

Whether to build the ingestion, pay a hosted metrics product, or start from the template is a separate decision, covered in build vs buy a SaaS metrics dashboard. The price on the template page is $59. The MRR API guide is the snapshot this churn math subtracts from. A single live list does not keep the starting book. How to sync Stripe data for a SaaS metrics dashboard is the backfill, the webhook, and the reconciliation that store those two snapshots.

Sources

Stripe churn questions

Short answers on logo churn, MRR churn, and the Dashboard.

How do you calculate churn rate from Stripe?

Stripe does not return a churn field. List subscriptions, including canceled ones, and subscription events. Count customers with a qualifying subscription at the start of the window and none at the end, and divide by the starting customers. For MRR churn, normalize each subscription to one month, then divide churned MRR plus contraction by starting MRR. Subtract expansion only when you are reporting net MRR churn.

What is the difference between Stripe customer churn and MRR churn?

Customer churn counts logos. A customer with two subscriptions who cancels one is still a customer, so customer churn does not move and the lost dollars are contraction. Gross MRR churn divides canceled MRR plus contraction by starting MRR. Net MRR churn also subtracts expansion. Net revenue retention on this page is the starting book after those three movements, divided by starting MRR. New MRR is a separate line.

Why does the Stripe Dashboard churn rate differ from my calculation?

Billing analytics is configurable. Its MRR includes active and past_due subscriptions and excludes legacy trials. Subscriber churn divides churned subscribers by the subscribers from 30 days ago plus new subscribers in the period. This page divides by the starting customers only and leaves past_due out unless you opt in. Charts use the account time zone, while prebuilt report dates use UTC. Multi-currency accounts can include an FX adjustment. This function does not convert currencies.

Does cancel_at_period_end count as Stripe churn immediately?

Not in this function. Stripe keeps the subscription active until the period ends, then sends customer.subscription.deleted and sets ended_at. The subscription stays in the starting and ending book until that timestamp. Billing analytics can be configured to count the cancellation when it is scheduled instead. A refund issued at cancellation is cash. This function does not read Refund or Charge objects.

How do trials, paused subscriptions, and annual plans affect Stripe churn?

A subscription with trial_end still in the future is outside the default book, so a trial that cancels before it converts is not customer churn. status paused is outside the default book. pause_collection does not change status, and invoices still generate, so those subscriptions stay. A yearly price is divided by 12, and by interval_count, before it enters MRR. Canceling a $120 yearly plan removes $10 of MRR, which is the same divisor Stripe uses in its Billing analytics example.

Can I calculate Stripe churn without code?

Export the subscriptions CSV at the start of the period and again at the end. The Stripe MRR CSV calculator at https://datalighthouse.dev/tools/stripe-mrr-csv-calculator normalizes one file in the browser and does not upload it. It returns MRR per currency, not a churn rate. Compare the two totals with the formulas on this page. Data Lighthouse is a self-hosted Next.js template. The overview does not compute churn. The license is $59 once. The buyer page is https://datalighthouse.dev/saas-metrics-dashboard-template and the sample dashboard is https://datalighthouse.dev/demo. The demo uses sample data and does not call Stripe.