How to Calculate Customer Lifetime Value (LTV) from Stripe

Stripe API · Updated 22 November 2026

TL;DR

Stripe does not return customer lifetime value. Divide normalized monthly recurring revenue by paying customers, then divide that ARPU by the customer churn fraction for the same period. Churn of zero makes the result undefined.

The LTV glossary is the definition. ARPU and the churn guide are the two inputs. Monthly prices come from how to calculate MRR from the Stripe API. Net revenue retention reads the same starting book as a retention rate, not as a lifetime. Cohort cash comes from paid invoices. The SaaS metrics calculator divides numbers you type. The Stripe MRR CSV calculator normalizes one export in the browser and does not upload it. Neither tool lists invoices.

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

How do you calculate customer lifetime value from Stripe?

Stripe has no LTV field. You compute it. Recurring LTV uses one currency's starting book. Cohort LTV uses invoices for customers acquired in one window. They answer different questions. Publish the name next to the number.

ModelFormula
Recurring ARPUStarting MRR / starting customers
Revenue LTVRecurring ARPU / customer churn fraction
Expected lifetime1 / customer churn fraction, in the same period as ARPU
Gross-margin LTVRevenue LTV × gross margin, with margin from 0 to 1
Revenue-churn LTVRecurring ARPU / gross MRR churn fraction
Discounted revenue LTVARPU × (1 + discount rate) / (churn + discount rate)
Cohort LTVNet paid invoices for the cohort / customers acquired in the window

Customer churn is a fraction. A rate of 4% is 0.04. Revenue LTV is undefined when that fraction is zero or missing. Gross margin is a fraction you type. Stripe does not return it. A discount rate is also yours. The series below is why the discounted formula has that shape.

Assume the customer pays ARPU at the start of each period they are still active. After k periods the survival chance is (1 minus churn) to the power k. A payment k periods away is divided by (1 + discount rate) to the power k. The first payment is today, so k starts at 0.

That sum is a geometric series. It equals ARPU times (1 + discount rate), divided by (churn + discount rate), when the denominator is positive. A discount rate of 0 collapses the sum to ARPU / churn. Churn of 0 with a positive discount rate stays finite. Both rates at 0 is undefined. This page derives that sum. It does not borrow a rate.

Net revenue retention is ending MRR of the starting customers, divided by starting MRR. It is not a lifetime. A month of NRR does not tell you how many months the logo will pay.

  1. Write the LTV formulas before you call Stripe
  2. Build ARPU and customer churn from subscriptions
  3. Stop when churn is zero, and do not mix periods
  4. Apply gross margin and CAC that you bring yourself
  5. Sum paid invoices for one acquisition cohort
  6. Paginate subscriptions, invoices, and customers

Worked example, labeled as an example

Every figure in this section is hypothetical. It is example data for January 2026, from 2026-01-01T00:00:00.000Z to 2026-02-01T00:00:00.000Z, passed through ltvFromChurnReport. It is separate from the public demo and from any customer account.

CustomerPriceState at 1 February
Ada, Bo, Cam$40 every monthStill active
Dee$40 every monthended_at on 15 January

Starting customers are 4. Starting MRR is $160.00. Recurring ARPU is $40.00. Customer churn is 25%. Expected lifetime is 4 months. Revenue LTV is $160.00. That is $40.00 divided by 0.25.

Gross margin in this example is 0.8, which you would type. It is not on the Subscription object. Gross-margin LTV is $128.00. The same function with margin 4, the percent typed in place of the fraction, returns undefined.

CAC in this example is $64.00. Stripe did not produce that number. Revenue LTV:CAC is 2.5. Gross-margin LTV:CAC is 2. Revenue payback is 1.6 months of ARPU. Contribution payback is 2 months of ARPU times 0.8. None of those ratios is a target.

The discount rate in this example is 0.01 per month. Discounted revenue LTV is $155.38. The call is discountedRevenueLtv on the same ARPU and churn. The rate is an input, not a recommendation.

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

  • Three customers at $10 and one at $100 who cancels. ARPU is $32.50. Logo churn is 25%. Revenue LTV is $130.00. Gross MRR churn is 76.92%, so revenue-churn LTV is $42.25. The lost logo paid more than the average. The two formulas diverge.
  • One $30 customer who stays. Customer churn is 0%. Revenue LTV is undefined. Discounted LTV at 0.01 per month is $3,030.00. A zero in the denominator is not a large lifetime.
  • A $120 yearly price that stays, plus a $40 monthly price that cancels. Normalized starting MRR is $50.00, not $160. ARPU is $25.00. Revenue LTV is $50.00. Treating the yearly prepayment as monthly ARPU, so the average of $120 and $40 divided by the same 0.5 churn, produces $160.00. That second figure is the mistake, computed beside the function.
  • A $40 price and a second $40 price with a forever 100% coupon. Starting customers are 2. Starting MRR is $40.00. ARPU is $20.00. Nobody left, so revenue LTV is undefined. The free logo still sits in the ARPU denominator.
  • The equal USD book plus ¥1,500 a month that stays. USD revenue LTV is still $160.00. The yen book is ¥1,500 of ARPU on its own. Yen revenue LTV is undefined because that book did not lose a customer. The yen amount is not added to the dollars.
  • An example input that is not this January book: ARPU of $40 and a churn fraction of 0.001. Revenue LTV is $40,000.00, which is 1000 months of that ARPU. Dividing $40 by 4, the percent in place of the fraction, produces $10.00. That is the percent-versus-fraction mistake, not a lifetime.

ARPU and churn from subscriptions

Recurring ARPU needs a starting snapshot. Today's active list has no memory of who left. The customer churn fraction has to use the same customers as the ARPU denominator. This page uses the starting book from how to calculate churn rate from Stripe.

  • price.unit_amountis minor units. USD divides by 100. JPY divides by 1. The MRR normalizer's minorUnitFactor is the rule.
  • A year divides by 12 times interval_count. A week multiplies by 52/12. A day multiplies by 365/12. The MRR API guide is the interval and coupon write-up. This page calls that normalizer through the churn function.
  • 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.
  • Metered and tiered prices are skipped. duration: once does not change MRR. Forever coupons apply. Repeating coupons apply while end is null or still in the future.

Logo churn and gross MRR churn are different divisors. Logo churn asks how many starting customers are gone. Gross MRR churn asks how much starting MRR was lost to cancellations and contractions. Use logo churn when the ARPU is per customer. Use gross MRR churn when you want the dollars, not the logos, to set the lifetime. Say which one you divided by.

New customers and reactivations are outside the starting book. The NRR guide leaves them out of retention for the same reason. Putting them into the ARPU denominator without putting them into the churn denominator mixes two populations.

Why does low churn send this formula to infinity?

Revenue LTV divides by the churn fraction. A smaller fraction produces a larger quotient. There is no cap inside the formula. At zero the division is undefined. revenueLtv returns null. It does not return an infinite number, and it does not substitute a large placeholder.

The model also assumes the rate you measured will continue. One quiet month is a sample of one. A cohort that has not had time to cancel will print a churn of zero and an undefined LTV. That is a short window, not a proof that nobody will ever leave.

A discount rate you supply is what keeps the zero-churn case finite. With churn at 0 the sum is ARPU times (1 + discount rate) divided by the discount rate. The January example uses 0.01 only so the arithmetic is visible. Pick a rate from your own cost of capital if you want one. This page does not supply one.

Period mix breaks the same formula without a zero. Monthly ARPU with a yearly churn fraction multiplies the lifetime by about twelve. Yearly ARPU with a monthly churn fraction divides it by about twelve. Match the period before you divide.

How do annual plans, discounts, refunds, and currencies change LTV?

Annual plans hit ARPU and invoices differently. Normalized MRR divides a yearly price by 12. amount_paid on the invoice is the prepayment, often the whole year, on paid_at. Using that prepayment as a monthly ARPU inflates revenue LTV. The labeled yearly row above is the numeric version of that mistake.

Discounts are already in both inputs when you use this code. The MRR normalizer applies percent-off and amount-off coupons that still recur. amount_paid is the cash after invoice discounts. Subtracting total_discount_amounts again removes the discount twice.

Refunds do not change price.unit_amount, so they do not change recurring ARPU. They do change cash. Subtract post_payment_credit_notes_amount from amount_paid once. Do not also subtract pre_payment_credit_notes_amount. That reduction is already out of amount_paid.

A Refund on the charge with no credit note does not move post_payment_credit_notes_amount. This function does not list Refund objects. If your account refunds that way, the cohort cash figure is high until you account for those Refunds yourself.

Each currency is its own book. Amounts are not converted. A customer in dollars and yen is counted in each book and listed on customersInMultipleCurrencies. Do not divide a zero-decimal currency by 100. The Stripe MRR CSV calculator uses the same separation for one export. It does not return LTV.

How do you calculate LTV:CAC and the payback period?

LTV:CAC divides a lifetime-value figure by acquisition cost. Payback divides that cost by the contribution you collect each period. Stripe charges, invoices, and subscriptions are revenue. They are not the ad spend or the sales cost that produced the customer. The function has no CAC argument.

RatioFormula
LTV:CACChosen LTV / CAC
Revenue paybackCAC / recurring ARPU
Contribution paybackCAC / (recurring ARPU × gross margin)

In the labeled January book, CAC of $64.00 and gross-margin LTV of $128.00 give a ratio of 2. Contribution payback is 2 months. Those sentences describe the arithmetic. They do not say the ratio is high enough, or too low, for a company.

Use the same LTV in the ratio that you use in the forecast. A revenue LTV over CAC, and a gross-margin LTV over the same CAC, are different ratios. A cohort's cash so far over CAC is a third ratio, and it is censored at the as-of date. Compare a ratio only with the same formula, window, currency, and margin.

You can type ARPU, logo churn, and see simple revenue LTV in the SaaS metrics calculator. That page does not call Stripe and does not ask for CAC.

What is cohort LTV from Stripe invoices?

Cohort LTV holds the acquisition group fixed. A member is a customer whose subscription start_date falls in the window, once per currency. Net cash is amount_paid minus post_payment_credit_notes_amount on invoices with status paid, up to the as-of timestamp. Divide by the member count. Customers who paid nothing stay in that denominator.

The rows below are hypothetical. They are not the January churn book. Acquisition is January 2026. The as-of date is 2026-03-01T00:00:00.000Z. Ada pays $30 in January and $30 in February. Bo pays $120 on 10 January for a year. Cam pays $30 and then has a post-payment credit note for the full $30. Dee starts a trial on 20 January and has no paid invoice. Eve is a Customer created in January with no subscription. Yen is ¥1,500, kept in its own book.

Cash mode, which counts the whole net amount on the paid date: USD cohort customers 4, paying customers 2, net revenue $180.00. Realized LTV is $45.00. Paying customers only would be $90.00. Customers created in the window with no subscription: 1. Eve stays out of the denominator. The open invoice is skipped.

Straight-line mode spreads each paid invoice across its service months. A month is 365/12 days, the same length the MRR normalizer uses for a daily price. By 1 March, Ada's January invoice has fully elapsed. Her 5 February invoice has not. Bo's year has barely started. Recognized USD net is $70.11. Realized LTV is $17.53. Cash mode and recognized mode are both here so the gap is visible. Pick one and label it.

The yen cohort is 1 customer and ¥1,500 of realized LTV. It is not added to the USD $45.00.

This number is censored. Invoices after the as-of date are absent. A two-month cohort will sit below a forecast that assumes the January churn rate forever. Do not replace one with the other because they landed on different dollars.

customers.list is how you see Customer objects created in the window. A Customer can exist before any subscription. Counting every Customer as a subscriber pulls realized LTV down. This function reports that count and leaves those ids out of the denominator. Say so if you choose the other denominator.

Which Stripe API calls produce the inputs?

Three lists, all paginated. subscriptions.list takes one status. The snippet requests active, trialing, past_due, paused, unpaid, and canceled. Omitting canceled subscriptions hides the customers who left, so churn looks like zero and revenue LTV comes back undefined.

The default page size is 10. The maximum limit is 100. autoPagingToArray follows starting_after until the list ends or the local cap of 100,000 records. That cap is not a Stripe maximum. Expand data.discounts.source.coupon on the subscription list. Item coupons need subscriptionItems.list, because expand stops at four levels. The churn file does that load. This file calls it.

events.list rebuilds an item change inside the window. Stripe lists events going back up to 30 days. A window that starts earlier sets eventsLookbackIncomplete. ended_at still marks a cancellation. The old price may not. Store a snapshot when the month has to stay auditable. How to sync Stripe data for a SaaS metrics dashboard is the webhook, backfill, and reconciliation write-up.

invoices.list uses status: paid and created[gte] at the cohort start. Cash from before the cohort window is not in that list. When lines.has_more is true, invoices.listLineItems loads the rest. The longest line period that lands on a whole month becomes serviceMonths. An ambiguous period stays null, and cash mode counts the net amount on the paid date.

On the current Invoice object the subscription id lives at parent.subscription_details.subscription. Cohort membership on this page uses the subscription start_date and the invoice customer, not that parent field. customers.list filters created to the cohort window.

Install stripe. Copy lib/tools/stripe-mrr.ts with its MIT notice, and copy lib/guides/calculate-stripe-churn.ts with this file. Pass the secret key only on the server. The API version in createStripeClient is 2025-10-29.clover.

lib/guides/calculate-stripe-ltv.ts
/**
 * Customer lifetime value (LTV) from Stripe subscriptions, invoices, and customers.
 *
 * Stripe does not return an LTV field, an ARPU field, or a churn field.
 * Recurring LTV uses the churn guide's starting book:
 *
 *   recurring ARPU = starting MRR / starting customers
 *   revenue LTV    = recurring ARPU / customer churn rate
 *
 * Customer churn is a fraction. Zero churn makes revenue LTV undefined.
 * Gross margin and a per-period discount rate are inputs you pass in.
 * They are not Stripe fields. CAC is not a Stripe field either, so this
 * file does not read it.
 *
 * Cohort LTV sums paid invoices for customers whose subscription
 * `start_date` falls in the cohort window, then divides by that customer
 * count. `amount_paid` is minor units after discounts. Subtract
 * `post_payment_credit_notes_amount` once. Do not also subtract
 * `pre_payment_credit_notes_amount`: `amount_paid` is already net of those.
 *
 * A refund issued without a credit note does not change
 * `post_payment_credit_notes_amount`. This function does not list Refunds.
 *
 * Run the Stripe calls on the server. `STRIPE_SECRET_KEY` is a secret key.
 * Monthly normalization is `normalizeStripeSubscriptionMrr` in
 * `lib/tools/stripe-mrr.ts`, called from `calculateChurnFromListedSubscriptions`.
 * The Events API lists events going back up to 30 days.
 */
import Stripe from "stripe"

import { minorUnitFactor, roundMajorCurrency } from "../tools/stripe-mrr"
import {
  CHURN_EVENT_TYPES,
  CHURN_LIST_STATUSES,
  STRIPE_EVENT_RETENTION_SECONDS,
  SUBSCRIPTION_LIST_EXPAND,
  calculateChurnFromListedSubscriptions,
  toChurnEventInput,
  toChurnSubscriptionInput,
  type CalculateStripeChurnOptions,
  type ChurnEventInput,
  type ChurnReport,
  type ChurnSubscriptionInput,
  type ChurnWindowOptions,
} from "./calculate-stripe-churn"
import { createStripeClient } from "./calculate-stripe-mrr"

export { createStripeClient }
export type { ChurnWindowOptions, CalculateStripeChurnOptions }

/** Same local cap as the churn list. Stripe's list `limit` max is 100. */
const AUTO_PAGE_LIMIT = 100_000

/**
 * One month in the MRR normalizer's day convention: 365/12 days.
 * Straight-line recognition uses this length. It is not a Stripe field.
 */
export const LTV_MONTH_SECONDS = (365 / 12) * 24 * 60 * 60

export interface LtvPolicy {
  /** Fraction from 0 to 1. Omit it and gross-margin LTV stays null. */
  grossMargin?: number | null
  /**
   * Discount rate per period, same period as the churn rate.
   * Omit it and discounted LTV stays null. This is not a Stripe field.
   */
  discountRatePerPeriod?: number | null
  /** Divisor for a three-decimal currency (BHD, JOD, KWD, OMR, TND). Pass 1000. */
  minorUnitFactor?: number
}

export function revenueLtv(arpu: number | null, customerChurnRate: number | null): number | null {
  if (arpu == null || customerChurnRate == null) return null
  if (!Number.isFinite(arpu) || arpu < 0) return null
  if (!Number.isFinite(customerChurnRate) || !(customerChurnRate > 0)) return null
  return arpu / customerChurnRate
}

/** Periods a constant churn rate implies: 1 / churn. Null when churn is missing or not positive. */
export function expectedLifetimePeriods(customerChurnRate: number | null): number | null {
  if (customerChurnRate == null || !Number.isFinite(customerChurnRate) || !(customerChurnRate > 0)) return null
  return 1 / customerChurnRate
}

export function grossMarginLtv(revenueLtvAmount: number | null, grossMargin: number | null): number | null {
  if (revenueLtvAmount == null || grossMargin == null) return null
  if (!Number.isFinite(revenueLtvAmount) || revenueLtvAmount < 0) return null
  if (!Number.isFinite(grossMargin) || grossMargin < 0 || grossMargin > 1) return null
  return revenueLtvAmount * grossMargin
}

/**
 * Sum of ARPU paid at the start of each period the customer is still active,
 * discounted one period at a time.
 *
 *   ARPU * (1 + discountRate) / (churn + discountRate)
 *
 * A discount rate of 0 reduces to ARPU / churn. Churn of 0 with a positive
 * discount rate stays finite. Both rates at 0 is undefined.
 */
export function discountedRevenueLtv(
  arpu: number | null,
  customerChurnRate: number | null,
  discountRate: number | null,
): number | null {
  if (arpu == null || customerChurnRate == null || discountRate == null) return null
  if (!Number.isFinite(arpu) || arpu < 0) return null
  if (!Number.isFinite(customerChurnRate) || customerChurnRate < 0) return null
  if (!Number.isFinite(discountRate) || discountRate < 0) return null
  const denominator = customerChurnRate + discountRate
  if (!(denominator > 0)) return null
  return (arpu * (1 + discountRate)) / denominator
}

/** LTV divided by CAC. Null when CAC is missing or not positive. CAC is not read from Stripe. */
export function ltvToCac(ltv: number | null, cac: number | null): number | null {
  if (ltv == null || cac == null) return null
  if (!Number.isFinite(ltv) || !Number.isFinite(cac) || !(cac > 0)) return null
  return ltv / cac
}

/**
 * Periods of contribution required to recover CAC.
 * Pass ARPU for a revenue payback. Pass ARPU * gross margin for a contribution payback.
 */
export function paybackPeriods(cac: number | null, contributionPerPeriod: number | null): number | null {
  if (cac == null || contributionPerPeriod == null) return null
  if (!Number.isFinite(cac) || cac < 0) return null
  if (!Number.isFinite(contributionPerPeriod) || !(contributionPerPeriod > 0)) return null
  return cac / contributionPerPeriod
}

export function recurringArpu(startingMrr: number, startingCustomers: number): number | null {
  if (!Number.isFinite(startingMrr) || startingMrr < 0) return null
  if (!Number.isFinite(startingCustomers) || !(startingCustomers > 0)) return null
  return startingMrr / startingCustomers
}

export interface CurrencyLtv {
  currency: string
  startingCustomers: number
  startingMrr: number
  /** Starting MRR / starting customers in this currency. Null when the book is empty. */
  recurringArpu: number | null
  /** Fraction. Null when this currency had no starting customers. */
  customerChurnRate: number | null
  grossMrrChurnRate: number | null
  /** 1 / customer churn. Null when churn is missing or zero. */
  expectedLifetimePeriods: number | null
  /** ARPU / customer churn, rounded to the currency's minor units. Null when churn is zero. */
  revenueLtv: number | null
  /** revenue LTV * gross margin. Null when margin was omitted or is outside 0 to 1. */
  grossMarginLtv: number | null
  /**
   * ARPU / gross MRR churn. A different model from logo churn.
   * Null when gross MRR churn is missing or zero.
   */
  revenueChurnLtv: number | null
  /** Null when no discount rate was passed, or when churn + discount rate is not positive. */
  discountedRevenueLtv: number | null
}

export interface FormulaLtvReport {
  periodStart: string
  periodEnd: string
  byCurrency: CurrencyLtv[]
  grossMargin: number | null
  discountRatePerPeriod: number | null
  eventsLookbackIncomplete: boolean
  customersInMultipleCurrencies: number
}

function money(amount: number | null, currency: string, factorOverride?: number): number | null {
  if (amount == null || !Number.isFinite(amount)) return null
  return roundMajorCurrency(amount, factorOverride ?? minorUnitFactor(currency))
}

export function ltvFromChurnReport(report: ChurnReport, policy: LtvPolicy = {}): FormulaLtvReport {
  const grossMargin = policy.grossMargin ?? null
  const discountRate = policy.discountRatePerPeriod ?? null
  return {
    periodStart: report.periodStart,
    periodEnd: report.periodEnd,
    grossMargin,
    discountRatePerPeriod: discountRate,
    eventsLookbackIncomplete: report.eventsLookbackIncomplete,
    customersInMultipleCurrencies: report.customersInMultipleCurrencies,
    byCurrency: report.byCurrency.map((row) => {
      const arpu = recurringArpu(row.startingMrr, row.startingCustomers)
      const logoLtv = revenueLtv(arpu, row.customerChurnRate)
      const revenueChurn = revenueLtv(arpu, row.grossMrrChurnRate)
      const discounted = discountedRevenueLtv(arpu, row.customerChurnRate, discountRate)
      const margin = grossMarginLtv(logoLtv, grossMargin)
      return {
        currency: row.currency,
        startingCustomers: row.startingCustomers,
        startingMrr: row.startingMrr,
        recurringArpu: money(arpu, row.currency, policy.minorUnitFactor),
        customerChurnRate: row.customerChurnRate,
        grossMrrChurnRate: row.grossMrrChurnRate,
        expectedLifetimePeriods: expectedLifetimePeriods(row.customerChurnRate),
        revenueLtv: money(logoLtv, row.currency, policy.minorUnitFactor),
        grossMarginLtv: money(margin, row.currency, policy.minorUnitFactor),
        revenueChurnLtv: money(revenueChurn, row.currency, policy.minorUnitFactor),
        discountedRevenueLtv: money(discounted, row.currency, policy.minorUnitFactor),
      }
    }),
  }
}

export interface LtvInvoiceInput {
  id: string
  customerId: string
  currency: string
  status: string
  /** Unix seconds from `status_transitions.paid_at`. Null when Stripe left it empty. */
  paidAt: number | null
  /** Unix seconds. Invoice `created`. Used when `paidAt` is null. */
  created: number
  /** Minor units. `amount_paid`, already after discounts and pre-payment credit notes. */
  amountPaid: number
  /** Minor units. `post_payment_credit_notes_amount`. */
  postPaymentCreditNotesAmount: number
  /**
   * Months of service, from the longest invoice line period that lands on a
   * whole month. Null means the whole net amount is cash at `paid_at`.
   */
  serviceMonths: number | null
}

export interface CohortMemberInput {
  customerId: string
  currency: string
  /** Unix seconds. Subscription `start_date` for this currency. */
  acquiredAt: number
}

export interface LtvCustomerInput {
  id: string
  /** Unix seconds. Customer `created`. */
  created: number
}

export interface CohortCurrencyLtv {
  currency: string
  cohortCustomers: number
  payingCustomers: number
  /** Major units, net of post-payment credit notes, rounded. */
  netRevenueMajor: number
  /** Net revenue / cohort customers, including customers who paid nothing. Null when the cohort is empty. */
  realizedLtv: number | null
  /** Net revenue / customers with positive net cash. Null when nobody paid. */
  realizedLtvPayingOnly: number | null
}

export interface CohortLtvReport {
  cohortStart: string
  cohortEnd: string
  asOf: string
  recognizeOverService: boolean
  byCurrency: CohortCurrencyLtv[]
  /** Customers created in the window who have no cohort subscription. They stay out of the denominator. */
  customersWithoutSubscription: number
  invoicesSkipped: number
  duplicateInvoices: number
  /** Paid invoices that had no `paid_at`, so `created` was used. */
  paidAtMissing: number
}

export interface CohortLtvOptions extends LtvPolicy {
  cohortStart: Date
  cohortEnd: Date
  asOf: Date
  /** Spread net cash across `serviceMonths` from `paid_at`. Default false: cash on the paid date. */
  recognizeOverService?: boolean
}

/** Whole months when the line period is within 0.2 months of an integer. Otherwise null. */
export function serviceMonthsFromPeriod(start: number, end: number): number | null {
  if (!Number.isFinite(start) || !Number.isFinite(end) || !(end > start)) return null
  const months = (end-start) / LTV_MONTH_SECONDS
  const rounded = Math.round(months)
  if (rounded < 1) return null
  if (Math.abs(months-rounded) > 0.2) return null
  return rounded
}

export function serviceMonthsFromPeriods(periods: readonly { start: number; end: number }[]): number | null {
  let best: number | null = null
  for (const period of periods) {
    const months = serviceMonthsFromPeriod(period.start, period.end)
    if (months != null && (best == null || months > best)) best = months
  }
  return best
}

export function netPaidMinor(invoice: Pick<LtvInvoiceInput, "amountPaid" | "postPaymentCreditNotesAmount">): number {
  if (!Number.isFinite(invoice.amountPaid) || !Number.isFinite(invoice.postPaymentCreditNotesAmount)) return 0
  return Math.max(0, invoice.amountPaid-invoice.postPaymentCreditNotesAmount)
}

/** Share of net cash recognized by `asOf`. Cash mode returns 1 once the invoice is paid. */
export function recognizedFraction(
  paidAt: number,
  asOf: number,
  serviceMonths: number | null,
  recognizeOverService: boolean,
): number {
  if (!(paidAt <= asOf)) return 0
  if (!recognizeOverService || serviceMonths == null || !(serviceMonths > 0)) return 1
  const elapsedMonths = (asOf-paidAt) / LTV_MONTH_SECONDS
  return Math.min(1, Math.max(0, elapsedMonths / serviceMonths))
}

export function cohortMembersFromSubscriptions(
  subscriptions: readonly ChurnSubscriptionInput[],
  cohortStartUnix: number,
  cohortEndUnix: number,
): CohortMemberInput[] {
  const best = new Map<string, CohortMemberInput>()
  for (const subscription of subscriptions) {
    if (subscription.startDate < cohortStartUnix || subscription.startDate >= cohortEndUnix) continue
    const currency = subscription.items.find((item) => item.price?.currency)?.price?.currency
    if (!currency || !subscription.customerId) continue
    const key = `${subscription.customerId}:${currency.toLowerCase()}`
    const existing = best.get(key)
    if (!existing || subscription.startDate < existing.acquiredAt) {
      best.set(key, {
        customerId: subscription.customerId,
        currency: currency.toLowerCase(),
        acquiredAt: subscription.startDate,
      })
    }
  }
  return [...best.values()]
}

export function countCustomersWithoutSubscription(
  customers: readonly LtvCustomerInput[],
  members: readonly CohortMemberInput[],
  cohortStartUnix: number,
  cohortEndUnix: number,
): number {
  const memberIds = new Set(members.map((member) => member.customerId))
  const seen = new Set<string>()
  let count = 0
  for (const customer of customers) {
    if (!customer.id || seen.has(customer.id)) continue
    seen.add(customer.id)
    if (customer.created < cohortStartUnix || customer.created >= cohortEndUnix) continue
    if (memberIds.has(customer.id)) continue
    count += 1
  }
  return count
}

export function cohortRealizedLtv(
  members: readonly CohortMemberInput[],
  invoices: readonly LtvInvoiceInput[],
  customers: readonly LtvCustomerInput[],
  options: CohortLtvOptions,
): CohortLtvReport {
  const cohortStart = Math.floor(options.cohortStart.getTime() / 1000)
  const cohortEnd = Math.floor(options.cohortEnd.getTime() / 1000)
  const asOf = Math.floor(options.asOf.getTime() / 1000)
  if (!Number.isFinite(cohortStart) || !Number.isFinite(cohortEnd) || cohortEnd <= cohortStart) {
    throw new Error("cohortEnd must be after cohortStart")
  }
  if (!Number.isFinite(asOf)) throw new Error("asOf must be a valid date")

  const inWindow = members.filter((member) => member.acquiredAt >= cohortStart && member.acquiredAt < cohortEnd && member.acquiredAt <= asOf)
  const byCustomer = new Map<string, CohortMemberInput[]>()
  for (const member of inWindow) {
    const list = byCustomer.get(member.customerId) ?? []
    list.push(member)
    byCustomer.set(member.customerId, list)
  }

  const nets = new Map<string, number>()
  const seenInvoices = new Set<string>()
  let invoicesSkipped = 0
  let duplicateInvoices = 0
  let paidAtMissing = 0
  const recognize = options.recognizeOverService ?? false

  for (const invoice of invoices) {
    if (!invoice.id || seenInvoices.has(invoice.id)) {
      if (invoice.id && seenInvoices.has(invoice.id)) duplicateInvoices += 1
      else invoicesSkipped += 1
      continue
    }
    seenInvoices.add(invoice.id)
    if (invoice.status !== "paid") {
      invoicesSkipped += 1
      continue
    }
    const group = byCustomer.get(invoice.customerId)
    if (!group) {
      invoicesSkipped += 1
      continue
    }
    const paidAt = invoice.paidAt ?? invoice.created
    if (invoice.paidAt == null) paidAtMissing += 1
    if (!Number.isFinite(paidAt) || paidAt > asOf) continue
    const currency = invoice.currency.toLowerCase()
    const member = group.find((row) => row.currency === currency)
    if (!member) {
      invoicesSkipped += 1
      continue
    }
    const fraction = recognizedFraction(paidAt, asOf, invoice.serviceMonths, recognize)
    const key = `${invoice.customerId}:${currency}`
    nets.set(key, (nets.get(key) ?? 0) + netPaidMinor(invoice) * fraction)
  }

  const currencies = new Map<string, { customers: number; paying: number; minor: number }>()
  for (const member of inWindow) {
    const currency = member.currency.toLowerCase()
    const row = currencies.get(currency) ?? { customers: 0, paying: 0, minor: 0 }
    row.customers += 1
    const minor = nets.get(`${member.customerId}:${currency}`) ?? 0
    row.minor += minor
    if (minor > 0) row.paying += 1
    currencies.set(currency, row)
  }

  const byCurrency: CohortCurrencyLtv[] = [...currencies.entries()]
    .map(([currency, row]) => {
      const factor = options.minorUnitFactor ?? minorUnitFactor(currency)
      const netRevenueMajor = roundMajorCurrency(row.minor / factor, factor)
      return {
        currency,
        cohortCustomers: row.customers,
        payingCustomers: row.paying,
        netRevenueMajor,
        realizedLtv: row.customers > 0 ? roundMajorCurrency(netRevenueMajor / row.customers, factor) : null,
        realizedLtvPayingOnly: row.paying > 0 ? roundMajorCurrency(netRevenueMajor / row.paying, factor) : null,
      }
    })
    .sort((left, right) => left.currency.localeCompare(right.currency))

  return {
    cohortStart: options.cohortStart.toISOString(),
    cohortEnd: options.cohortEnd.toISOString(),
    asOf: options.asOf.toISOString(),
    recognizeOverService: recognize,
    byCurrency,
    customersWithoutSubscription: countCustomersWithoutSubscription(customers, inWindow, cohortStart, cohortEnd),
    invoicesSkipped,
    duplicateInvoices,
    paidAtMissing,
  }
}

export interface LtvReport {
  formula: FormulaLtvReport
  cohort: CohortLtvReport
}

export interface ListedLtvInputs {
  subscriptions: readonly ChurnSubscriptionInput[]
  events?: readonly ChurnEventInput[]
  invoices: readonly LtvInvoiceInput[]
  customers?: readonly LtvCustomerInput[]
}

export interface CalculateStripeLtvOptions extends CalculateStripeChurnOptions, CohortLtvOptions {}

export function calculateLtvFromListedData(input: ListedLtvInputs, options: CalculateStripeLtvOptions): LtvReport {
  const churn = calculateChurnFromListedSubscriptions(input.subscriptions, input.events ?? [], options)
  const cohortStart = Math.floor(options.cohortStart.getTime() / 1000)
  const cohortEnd = Math.floor(options.cohortEnd.getTime() / 1000)
  const members = cohortMembersFromSubscriptions(input.subscriptions, cohortStart, cohortEnd)
  return {
    formula: ltvFromChurnReport(churn, options),
    cohort: cohortRealizedLtv(members, input.invoices, input.customers ?? [], options),
  }
}

function customerIdOf(customer: Stripe.Invoice["customer"] | Stripe.Customer | Stripe.DeletedCustomer | string | null): string | null {
  if (typeof customer === "string" && customer) return customer
  if (customer && typeof customer === "object" && "id" in customer && customer.id) return customer.id
  return null
}

async function serviceMonthsForInvoice(stripe: Stripe, invoice: Stripe.Invoice, pageLimit: number): Promise<number | null> {
  let lines = invoice.lines.data
  if (invoice.lines.has_more) {
    lines = await stripe.invoices.listLineItems(invoice.id, { limit: 100 }).autoPagingToArray({ limit: pageLimit })
    if (lines.length >= pageLimit) {
      console.warn(`[Data Lighthouse] Stripe auto-pagination stopped at ${pageLimit} line items for invoice ${invoice.id}.`)
    }
  }
  return serviceMonthsFromPeriods(lines.map((line) => line.period))
}

/**
 * List the churn statuses once, then subscription events, paid invoices, and
 * customers created in the cohort window.
 * `subscriptions.list` takes one status. The default list omits canceled
 * subscriptions, so a customer who left is invisible without `status=canceled`.
 * `invoices.list` here uses `status=paid` and `created[gte]=cohortStart`.
 * Cash from before the cohort window is not in that list.
 */
export async function calculateLtvFromStripe(stripe: Stripe, options: CalculateStripeLtvOptions): Promise<LtvReport> {
  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)
  const cohortStart = Math.floor(options.cohortStart.getTime() / 1000)
  const cohortEnd = Math.floor(options.cohortEnd.getTime() / 1000)

  if (periodStart < retentionFloor) {
    console.warn(
      `[Data Lighthouse] Stripe events are listed going back up to 30 days. LTV 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)
  }

  const invoicePage = await stripe.invoices
    .list({
      status: "paid",
      created: { gte: cohortStart },
      limit: 100,
    })
    .autoPagingToArray({ limit: pageLimit })
  if (invoicePage.length >= pageLimit) {
    console.warn(`[Data Lighthouse] Stripe auto-pagination stopped at ${pageLimit} paid invoices.`)
  }

  const invoices: LtvInvoiceInput[] = []
  for (const invoice of invoicePage) {
    const customerId = customerIdOf(invoice.customer)
    if (!customerId) continue
    invoices.push({
      id: invoice.id,
      customerId,
      currency: invoice.currency,
      status: invoice.status ?? "paid",
      paidAt: invoice.status_transitions.paid_at,
      created: invoice.created,
      amountPaid: invoice.amount_paid,
      postPaymentCreditNotesAmount: invoice.post_payment_credit_notes_amount,
      serviceMonths: await serviceMonthsForInvoice(stripe, invoice, pageLimit),
    })
  }

  const customerPage = await stripe.customers
    .list({
      created: { gte: cohortStart, lt: cohortEnd },
      limit: 100,
    })
    .autoPagingToArray({ limit: pageLimit })
  if (customerPage.length >= pageLimit) {
    console.warn(`[Data Lighthouse] Stripe auto-pagination stopped at ${pageLimit} customers.`)
  }

  const customers: LtvCustomerInput[] = customerPage.map((customer) => ({
    id: customer.id,
    created: customer.created,
  }))

  return calculateLtvFromListedData(
    { subscriptions: listed, events: mappedEvents, invoices, customers },
    { ...options, now },
  )
}
app/api/stripe-ltv/route.ts
import { NextResponse } from "next/server"
import { calculateLtvFromStripe, createStripeClient } from "@/lib/guides/calculate-stripe-ltv"

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)
  // grossMargin and discountRatePerPeriod are inputs you supply. Stripe does not return them.
  const report = await calculateLtvFromStripe(createStripeClient(key), {
    periodStart,
    periodEnd,
    cohortStart: periodStart,
    cohortEnd: periodEnd,
    asOf: periodEnd,
  })

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

import { calculateLtvFromStripe, createStripeClient } from "@/lib/guides/calculate-stripe-ltv"

export async function ltvForTrailing30Days() {
  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 calculateLtvFromStripe(createStripeClient(key), {
    periodStart,
    periodEnd,
    cohortStart: periodStart,
    cohortEnd: periodEnd,
    asOf: periodEnd,
  })
}

The route uses the trailing 30 days for both the churn window and the cohort window. A cohort that is only 30 days old has barely billed. Read formula.byCurrency as the forecast and cohort.byCurrency as cash so far. Pass grossMargin only when you have one. The route omits it, so gross-margin LTV stays null.

SQL over tables you store

Stripe Sigma is not the schema below. These names are tables you create when you snapshot the churn book and the paid invoices. customer_churn_rate is a fraction from the churn guide. It is not a column Stripe returns.

Revenue LTV from a stored churn row
select
  currency,
  starting_mrr / nullif(starting_customers, 0) as recurring_arpu,
  case
    when customer_churn_rate > 0
      then (starting_mrr / nullif(starting_customers, 0)) / customer_churn_rate
  end as revenue_ltv
from stripe_churn_periods;

The cohort query left joins cash onto the acquired customers. A missing invoice row contributes zero and stays in the count. An inner join would drop that customer and raise realized LTV.

Realized cohort LTV from stored invoices
with cohort as (
  select customer_id, currency
  from stripe_cohort_customers
  where acquired_at >= timestamptz '2026-01-01 00:00:00+00'
    and acquired_at < timestamptz '2026-02-01 00:00:00+00'
),
cash as (
  select
    customer_id,
    currency,
    sum(amount_paid_major-post_payment_credit_notes_major) as net_revenue
  from stripe_invoices
  where status = 'paid'
    and paid_at <= timestamptz '2026-03-01 00:00:00+00'
  group by customer_id, currency
)
select
  cohort.currency,
  count(*) as cohort_customers,
  count(*) filter (where coalesce(cash.net_revenue, 0) > 0) as paying_customers,
  sum(coalesce(cash.net_revenue, 0)) as net_revenue,
  sum(coalesce(cash.net_revenue, 0)) / nullif(count(*), 0) as realized_ltv
from cohort
left join cash
  on cash.customer_id = cohort.customer_id
 and cash.currency = cohort.currency
group by cohort.currency;

Do not sum amount_paid into the MRR column. That mix is the annual prepayment mistake. How the rows get into Postgres is the sync guide.

Common mistakes

  1. Dividing by 4 when the churn rate is 0.04. The labeled call produces $10.00 from a $40 ARPU.
  2. Treating churn of zero as a very large LTV. The function returns null. A spreadsheet may print a divide-by-zero error.
  3. Reading one quiet month as a permanent rate. The formula assumes the fraction continues.
  4. Pairing a monthly ARPU with a yearly churn fraction, or the reverse.
  5. Using a yearly invoice as monthly ARPU. The labeled yearly row shows $160.00 against a normalized $50.00.
  6. Subtracting a discount that amount_paid already excludes.
  7. Subtracting pre_payment_credit_notes_amount as well as post-payment credit notes.
  8. Ignoring a Refund that never became a credit note. This function will not see it.
  9. Adding USD and JPY, or dividing JPY by 100.
  10. Using ending customers as the ARPU denominator while churn still uses the starting count.
  11. Calling a Stripe charge the CAC. Acquisition cost lives outside Stripe.
  12. Passing 80 as gross margin. The allowed range is 0 to 1, and 4 returns undefined.
  13. Dropping customers who paid nothing from the cohort denominator without saying so. The January cohort's paying-only figure is $90.00 against $45.00 for every acquired subscriber.
  14. Replacing the forecast with a 30-day cohort's cash. The route's two windows are the same length on purpose, and they still measure different things.
  15. Reading the template's revenue card as LTV. That card is succeeded charges for 7, 14, or 30 days, and it does not subtract refunds.

What Data Lighthouse shows

Calculating LTV is the top of the funnel. Keeping the starting snapshot, or the invoice history, is the next decision. Build vs buy a SaaS metrics dashboard compares a hosted metrics product, a from-scratch pipeline, and a template. The hour ranges on that page are labeled as estimates.

Get the template for $59

The SaaS metrics dashboard template is $59 once. You host the Next.js app. The overview shows revenue, MRR, and ARR. It does not compute LTV, ARPU, or churn. The Next.js Stripe analytics dashboard is the same license, focused on the revenue route. Pricing lists what is included. The live demo renders the overview with sample data and does not call Stripe.

The SaaS metrics calculator runs MRR, ARPU, logo churn, and simple revenue LTV in the browser from plans you type. The Stripe MRR CSV calculator normalizes one subscriptions export and does not return a churn rate or an LTV. Two exports, one at each boundary, are the CSV path to the churn fraction. Invoices are still an API list.

Sources

Stripe's API reference for subscriptions, invoices, invoice line items, customers, events, credit notes, and pagination. The zero-decimal currency list is Stripe's currencies guide. The geometric series in the first section is derived on this page. The hypothetical books were produced by the functions in this repository. No benchmark is cited, because this page does not use one.

Customer lifetime value questions

Short answers on Stripe LTV, ARPU, cohorts, and LTV:CAC.

How do you calculate customer lifetime value (LTV) from Stripe?

Stripe does not return an LTV field. List subscriptions, including canceled ones, and normalize each qualifying item to one month. Recurring ARPU is starting MRR divided by starting customers in that currency. Revenue LTV is that ARPU divided by the customer churn fraction for the same window. Churn of zero makes the quotient undefined. A second number, cohort LTV, sums amount_paid on paid invoices minus post_payment_credit_notes_amount for customers acquired in one month, then divides by that customer count.

How do you calculate ARPU from Stripe?

Stripe does not return ARPU. Recurring ARPU on this page is normalized starting MRR divided by the customers who had qualifying MRR at the start of the window, in one currency. Cash ARPU is different: sum amount_paid on paid invoices in the window, subtract post-payment credit notes, and divide by the customer definition you publish. A yearly price is divided by 12 before it enters MRR. The invoice still shows the full prepayment in amount_paid.

Why does a low churn rate make LTV look infinite?

Revenue LTV divides ARPU by the churn fraction. As that fraction gets smaller, the quotient grows without a cap. At zero the division is undefined. This code returns null in that case. It does not return an infinite number. The model also assumes the same churn rate continues forever. A discount rate you choose, in the same period as the churn rate, keeps a zero-churn book finite: ARPU times (1 + discount rate) divided by the discount rate. Stripe does not supply the discount rate.

How do annual plans, discounts, refunds, and extra currencies change Stripe LTV?

A $120 yearly price is $10 of MRR, so it enters recurring ARPU as $10. The paid invoice is still $120 on paid_at. Using that $120 as a monthly ARPU inflates LTV. Forever coupons reduce normalized MRR. A coupon with duration once does not. amount_paid is already after discounts, so do not subtract the discount again. Subtract post_payment_credit_notes_amount for a credit-note refund. A refund with no credit note is not on that field. USD and JPY stay in separate books. A zero-decimal currency is not divided by 100.

What is LTV:CAC, and how do you get the payback period?

LTV:CAC divides a lifetime-value figure by acquisition cost. Payback is that cost divided by contribution per period. Contribution can be ARPU, or ARPU times a gross margin you supply. Stripe does not store ad spend or sales cost, so the ratio needs a number from outside Stripe. A worked example on this page uses a hypothetical CAC and labels it as an example. The page does not publish a target ratio.

How is cohort LTV different from ARPU divided by churn?

ARPU divided by churn is a forecast from one period's logo churn. It assumes that rate continues. Cohort LTV is cash already collected from customers acquired in one window, divided by how many of them you count, measured up to an as-of date. Early months are censored: later invoices have not been paid yet. A 30-day cohort will not match the forecast. Dropping customers who paid nothing raises the average. Say which denominator you used.

Does the Data Lighthouse template calculate LTV?

No. The overview does not compute LTV, ARPU, or churn. It shows revenue for 7, 14, or 30 days from succeeded charges, without subtracting refunds, plus MRR from active subscriptions and ARR as that MRR times 12. The SaaS metrics calculator at https://datalighthouse.dev/tools/saas-metrics-calculator can divide an ARPU you type by a logo churn you type. The Stripe MRR CSV calculator at https://datalighthouse.dev/tools/stripe-mrr-csv-calculator normalizes one subscriptions export in the browser and does not upload it. Neither one lists invoices. The template is $59 once. The buyer page is https://datalighthouse.dev/saas-metrics-dashboard-template. Pricing is https://datalighthouse.dev/pricing. The live demo at https://datalighthouse.dev/demo uses sample data and does not call Stripe.