Skip to content

A/B testing with feature flags: when a flag is enough and when you need a stats engine

How to run A/B tests with feature flags: assignment, exposure logging, sample size, peeking, sample ratio mismatch and CUPED, with working code and a sourced table of which flag tools include experiment analysis.

10 min read

Short answer: A feature flag can split users into variants, but an A/B test also needs exposure logging, a sample size decided in advance and a statistical analysis. Use a plain flag rollout when you only need to ship safely. Use a tool with a stats engine, or your own analysis, when you need to know whether the change moved a metric.

What does a feature flag do in an A/B test?

It does the assignment. A flag with two or more variants and a percentage split puts each user in one variant, and consistent hashing keeps them there on every visit (see percentage rollouts and consistent hashing).

An experiment needs three more things the flag alone doesn't give you:

Piece What it is Who usually provides it
Assignment Which variant each user gets, stable over time The flag
Exposure logging A record that this user actually saw this variant, and when The flag SDK, a hook or your analytics
Metric events What users did afterwards: purchases, sign-ups, errors Your analytics or the experiment tool
Analysis Whether the difference between variants is larger than chance A stats engine, a notebook or a warehouse query

A rollout from 10% to 100% uses only the first row. That's enough to ship safely and roll back, but it can't tell you whether the change helped: people who see a new feature in week two aren't comparable with people who saw the old one in week one.

Which feature flag tools include experiment analysis?

Checked on each vendor's pages on 15 November 2026; each profile links to its source.

Analysis Tools
Built-in statistics engine LaunchDarkly (all plans, Bayesian and frequentist, CUPED, sequential), Statsig (all plans, CUPED, sequential), GrowthBook (all plans; CUPED and sequential on Pro and Enterprise), PostHog, Optimizely, Split / Harness FME, Eppo / Datadog Experiments (warehouse-native)
Built in, with limits Flagsmith (analysis in beta), FeatBit (experimentation in the free edition), AWS AppConfig (aggregate analysis, billed per experiment hour)
Analysis in a companion product Firebase Remote Config (Google Analytics), Azure App Configuration (Application Insights; scorecard in preview), Datadog Feature Flags (Datadog Experiments, priced per experiment)
Splits traffic, you analyse Unleash (variants on paid plans), ConfigCat, GO Feature Flag and Flagr (export evaluation data), flagd, DevCycle, Tggl, Vercel Flags
No A/B testing Flipt, Reflag

DevCycle, Tggl and Vercel list A/B testing, but we didn't find a built-in statistics engine described in their docs. For the engines side by side, see the best experimentation platforms; for head-to-heads, see GrowthBook vs PostHog and LaunchDarkly vs Statsig.

How do I log exposures and conversions with a flag?

Log an exposure when the flag is evaluated for a user who will actually see the difference, and log conversions as events tied to the same user. With OpenFeature, a hook records every evaluation and the Tracking API records conversions. This runs with @openfeature/server-sdk 1.23:

import { OpenFeature, InMemoryProvider } from '@openfeature/server-sdk'

const exposures = []
OpenFeature.addHooks({
  after(hookContext, details) {
    exposures.push({ flag: hookContext.flagKey, variant: details.variant, user: hookContext.context.targetingKey })
  },
})

await OpenFeature.setProviderAndWait(
  new InMemoryProvider({
    'checkout-button': {
      variants: { control: 'Buy now', treatment: 'Complete purchase' },
      defaultVariant: 'control',
      disabled: false,
      contextEvaluator: (ctx) => (ctx.targetingKey?.endsWith('7') ? 'treatment' : 'control'),
    },
  }),
)

const client = OpenFeature.getClient()
const label = await client.getStringValue('checkout-button', 'Buy now', { targetingKey: 'user-17' })
client.track('checkout-completed', { targetingKey: 'user-17' }, { value: 42.5 })
// label === 'Complete purchase', exposures === [{ flag: 'checkout-button', variant: 'treatment', user: 'user-17' }]

In production you'd swap the in-memory provider for your flag tool's provider and send exposures to your analytics. The Tracking API "enables the association of feature flag evaluations with subsequent actions"; it's marked experimental in the OpenFeature specification, and track does nothing if your provider doesn't implement it.

Two rules keep the data honest:

  • Log exposure in both variants. If only the treatment logs it, you can't compare.
  • Log it where the user sees the change, not when a page loads that might never show it. Users who were assigned but never exposed dilute the effect.

The hook above logs every successful evaluation of every flag, including repeats. In practice, evaluate the flag only where the variant renders (or log exposure explicitly at render), filter the hook to experiment flags and keep the first exposure per user. An after hook doesn't run when evaluation fails and the default is served, so those users aren't logged.

How many users do I need?

Decide before you start. Kohavi et al. give a rule of thumb for 95% confidence and 80% power: n = 16σ²/Δ² users per variant, where σ² is the metric's variance and Δ the smallest change you want to detect, in absolute units (for a 5% to 5.5% conversion rate, Δ = 0.005); replace 16 with 21 for 90% power (Kohavi et al., 2009, section 3.2).

For conversion rates, this function gives the per-variant size for a two-sided, two-proportion z-test with unpooled variance:

function normInv(p) {
  const a = [-39.69683028665376, 220.9460984245205, -275.9285104469687, 138.357751867269, -30.66479806614716, 2.506628277459239]
  const b = [-54.47609879822406, 161.5858368580409, -155.6989798598866, 66.80131188771972, -13.28068155288572]
  const c = [-0.007784894002430293, -0.3223964580411365, -2.400758277161838, -2.549732539343734, 4.374664141464968, 2.938163982698783]
  const d = [0.007784695709041462, 0.3224671290700398, 2.445134137142996, 3.754408661907416]
  const tail = (q) => (((((c[0] * q + c[1]) * q + c[2]) * q + c[3]) * q + c[4]) * q + c[5]) / ((((d[0] * q + d[1]) * q + d[2]) * q + d[3]) * q + 1)
  if (p < 0.02425) return tail(Math.sqrt(-2 * Math.log(p)))
  if (p > 0.97575) return -tail(Math.sqrt(-2 * Math.log(1 - p)))
  const q = p - 0.5, r = q * q
  return ((((((a[0] * r + a[1]) * r + a[2]) * r + a[3]) * r + a[4]) * r + a[5]) * q) / (((((b[0] * r + b[1]) * r + b[2]) * r + b[3]) * r + b[4]) * r + 1)
}

// Users per variant to detect a change from rate p1 to rate p2
function sampleSize(p1, p2, alpha = 0.05, power = 0.8) {
  const z = normInv(1 - alpha / 2) + normInv(power)
  return Math.ceil((z ** 2 * (p1 * (1 - p1) + p2 * (1 - p2))) / (p2 - p1) ** 2)
}

sampleSize(0.05, 0.055) // 31,231
sampleSize(0.05, 0.06)  // 8,155
sampleSize(0.20, 0.22)  // 6,507

normInv is Acklam's approximation of the inverse normal; we checked these results against Python's statistics.NormalDist. Kohavi's rule with σ² = p(1 − p) gives 30,401 for the first case, close to the exact 31,231. What they mean:

  • A 10% relative lift on a 5% conversion rate (5% to 5.5%) needs about 31,000 users in each variant, about 62,000 in total.
  • Doubling the change you want to detect (5% to 6%) cuts that roughly fourfold, to about 8,000 each, because the size scales with σ²/Δ².
  • Divide by your daily eligible users to get the minimum duration, then round up to whole weeks so weekdays and weekends are both covered.

If you can't reach the number, test a bigger change, pick a metric that happens more often, or accept that the test can only detect large effects.

Why shouldn't I stop when the result looks significant?

Because checking repeatedly and stopping at the first significant result inflates false positives. Johari et al. showed that traditional p-values "give unreliable inference" when people "continuously monitor" a running experiment, and proposed always-valid p-values that stay correct under continuous monitoring (Johari et al., KDD 2017).

You have two safe options:

  • Fix the sample size and look once, at the end.
  • Use sequential testing, which is designed for repeated looks. LaunchDarkly, Statsig, GrowthBook (Pro and Enterprise), Split and Eppo are among the engines that offer it. A middle ground is a group-sequential design with a few looks planned in advance.

Bayesian results aren't automatically safe to stop early either; follow the stopping rules of the engine you use.

How do I know the split itself worked?

Check for a sample ratio mismatch (SRM): a significant difference between the split you configured and the users you actually counted. Fabijan et al. found that about 6% of experiments at Microsoft had an SRM, which usually means the results can't be trusted until the cause is found (Fabijan et al., KDD 2019).

A chi-square test on the counts is enough:

// p-value for an expected 50/50 split (chi-square, 1 degree of freedom)
function srmPValue(a, b) {
  const expected = (a + b) / 2
  const chi2 = ((a - expected) ** 2 + (b - expected) ** 2) / expected
  return erfc(Math.sqrt(chi2 / 2))
}

function erfc(x) {
  const t = 1 / (1 + 0.5 * Math.abs(x))
  const y = t * Math.exp(-x * x - 1.26551223 + t * (1.00002368 + t * (0.37409196 + t * (0.09678418 + t * (-0.18628806 + t * (0.27886807 + t * (-1.13520398 + t * (1.48851587 + t * (-0.82215223 + t * 0.17087277)))))))))
  return Math.min(1, x >= 0 ? y : 2 - y)
}

srmPValue(10_000, 9_900)  // 0.48: consistent with 50/50
srmPValue(50_000, 48_500) // 0.0000018: a sample ratio mismatch

Because SRM checks run on every experiment, often continuously, teams use a strict threshold: flag an SRM when p is below 0.001 (some use 0.0005). A value like 0.01 is worth watching but not conclusive. The function tests a 50/50 split; for other splits, use the total multiplied by each variant's weight as the expected count. Common flag-related causes:

  • Targeting rules changed while the test was running.
  • Exposure logged on only some code paths, or lost when a page redirects before the event is sent.
  • Bots treated differently in one variant.
  • Sticky assignment broken when anonymous users log in and get a new ID.

How can I get results with fewer users?

Reduce variance:

  • Use CUPED. It uses each user's behavior before the experiment to remove noise. Deng et al. reported that on Bing it reduced variance by about 50%, "effectively achieving the same statistical power with only half of the users, or half the duration" (Deng et al., WSDM 2013). The gain depends on how well past behavior predicts the metric; brand-new users get no benefit. LaunchDarkly, Statsig, GrowthBook (Pro and Enterprise), PostHog and Eppo offer it.
  • Count only users who could see the change. Users who never reach the checkout don't belong in a checkout experiment. Two conditions: log the trigger in both variants (for control, where the change would have appeared), and make sure the change itself doesn't affect who reaches that point.

What else can go wrong?

  • Novelty and primacy effects. Users may click a new feature because it's new, or resist it because it's unfamiliar. Kohavi et al. note that "some experiments need to be run for multiple weeks" for this reason (2009, section 3.6).
  • Changing the split mid-test. Moving from 10% to 50% treatment can move some control users into treatment, and pooling periods with different splits can mislead. Ramping up first is fine if you analyse only data from after the final split and exclude users whose variant changed.
  • Overlapping experiments. Two tests on the same page can interact; run them on separate traffic (many tools call this namespaces or layers) when they might.
  • No A/A test. Run the same variant on both sides first; a healthy setup finds a "significant" difference on a given metric only about 5% of the time at 95% confidence, so across 20 metrics expect about one by chance. It also catches broken logging early (Kohavi et al., 2009, sections 3.1 and 6.2.1).

When is a flag rollout enough?

  • You're shipping a fix or a planned change and only need to limit risk: use a percentage rollout with error and latency monitoring, and a kill switch.
  • You need to know whether it moved a business metric: run an experiment with a sample size decided upfront and a proper analysis, in a tool with a stats engine or in your own warehouse.
  • Your traffic is too small for the effect you care about: skip the significance test and treat the rollout as a guarded launch, plus qualitative research.

For the full tool list see the best feature flag tools, and for how flags work in general, what is a feature flag.

Sources