Experiments inside your own shop: feature flags, A/B tests and holdouts you can trust
TL;DR
Difficulty: Advanced
A test result is only as good as the code underneath it.
- Put every change behind a feature flag, so one command switches it off.
- Pick the randomisation unit first (visitor, session or customer) and assign by hashing, so each unit always sees the same version.
- Log the exposure where the difference is seen, not the assignment: it cut the example test from 11 weeks to 7.
- Work out the sample size before you start, and check the split every day for a sample ratio mismatch.
- Do not stop at the first green day: daily peeking turned a 5% false alarm rate into about 32% in a simulation. Plan your looks instead.
- Read the interval, not the verdict, use CUPED to cut noise, keep guardrails, and keep a long term holdout to see what all the wins add up to.
Every testing tool shows you a winner sooner or later. This chapter builds the machinery that decides whether to believe it: feature flags, deterministic assignment, exposure logging, sample ratio checks, honest early looks, CUPED and long term holdouts, with the Ruby, SQL and Python for each, worked through for an invented homeware shop in Limerick testing a one page checkout.
A test result is only as good as the machinery behind it
Every testing tool shows you a winner sooner or later. The harder question is whether you should believe it. This chapter answers one question: how do I build A/B tests and holdouts into my own shop so that the results can be trusted?
An A/B test (also called a controlled experiment) shows two versions of something to two randomly chosen groups of visitors at the same time, and compares what they do. A holdout is the same idea turned round: a small random group that keeps the old version for a long time, so you can see what all your changes together were worth.
The statistics of testing are covered elsewhere in this blog. The complete guide to testing methods explains which kind of test fits which question, and the article on statistical significance explains p values and margins of error. The previous chapter in this series, measuring each part of your shop in isolation, showed why you need a random holdout to know what a feature earns.
This chapter is about the build side: who gets which version and how it stays that way, what you record and when, how many visitors you need, how to spot a broken split, how to look early without cheating, and how consent fits in. If you own your shop's code, you can build all of it yourself, and it is not much code.
Most ideas do not work, which is why this matters. Kohavi, Tang and Xu, whose book is the standard reference on online experiments, report that only about one third of the ideas tested at Microsoft improved the metric they were designed to improve1. If two out of three changes do nothing or harm, a shop that ships without measuring is guessing two times out of three. A shop with a broken test setup is worse off: it guesses and thinks it knows.
The example: Shannonside Home tests a one page checkout
Every number in this chapter is worked through for one invented shop. Shannonside Home (shannonsidehome.example) is an online homeware shop in Limerick. Niamh owns it and Callum is her developer. It runs on Ruby on Rails and Solidus, so every part of the shop is code that Callum can change.
Example: these are Shannonside Home's baseline figures for a typical month, all invented for this series. The shop has 110,000 sessions, a conversion rate of 1.8% and 1,980 orders at an average order value of €84. The contribution before marketing is €22.44 per order (the unit economics chapter builds that figure step by step). For this chapter I add two invented figures: the 110,000 sessions come from about 74,000 different visitors, and 5,200 of those visitors start checkout in a month. So 38.1% of the people who start checkout finish an order ().
Niamh wants to replace the three step checkout with a one page checkout that has an address lookup. Callum has built it. The question for the rest of this chapter is how they find out, with numbers they can trust, whether it earns more than it costs.
Feature flags are the backbone of every experiment
A feature flag is a switch in your code. The new checkout and the old checkout both live in the application, and a flag decides at the moment a page is built which one a visitor sees. Flags let you ship code to production without showing it to anyone, turn it on for yourself first, then for a small share of visitors, and turn it off again in seconds if something goes wrong. That last part is called a kill switch.
In a Rails shop, a well established choice is the Flipper gem. It can turn a feature on for everyone, for named people, for groups, for a percentage of actors (people or accounts), for a percentage of time or by custom rules2. The percentage of actors gate is deterministic: Flipper takes the feature name and the actor's ID, computes a checksum called CRC32, and switches the feature on if the result falls below the percentage3. The same person therefore gets the same answer on every request, and because the feature name is part of the input, two different flags split people independently of each other.
A flag and an experiment are related but not the same. A flag is about release: who can see the code. An experiment is about measurement: who is assigned to which version, logged so the comparison is fair. The flag is the safety switch around the experiment, and the experiment decides the split inside it.
# config/initializers/flipper.rb sits in the app after `bin/rails g flipper:setup`.
# Turning the new checkout on step by step, from the Rails console:
Flipper.enable_actor :one_page_checkout_2027, Flipper::Actor.new("customer:48213") # Callum's account
Flipper.enable_percentage_of_actors :one_page_checkout_2027, 5
# During the ramp the checkout asks Flipper directly: any ID can be an actor
actor = Flipper::Actor.new("visitor:7d1c2e9a")
Flipper.enabled?(:one_page_checkout_2027, actor) # => true or false, the same every time
# Start of the experiment: flag fully on, the experiment decides the split from now
Flipper.enable :one_page_checkout_2027
Experiment.find_by!(key: "one_page_checkout_2027").update!(status: "running")
# The kill switch: everyone back on the old checkout, no deploy needed
Flipper.disable :one_page_checkout_2027
The first two lines turn the feature on for Callum's account and then for 5% of visitors. Flipper::Actor wraps any ID so that Flipper can hash it. When the experiment starts, the flag is switched fully on and the experiment code (shown below) takes over the split, so from then on the flag is only the safety switch. The last line is the one that matters at 2am: one command and every visitor is back on the old checkout.
Example: Callum ramps the one page checkout in three steps before the real test starts. On day one only his and Niamh's accounts see it, and they place test orders with every payment method. On day two he turns it on for 5% of visitors, about 60 checkout starters a day, and watches the error log and the payment failure rate for 48 hours. Nothing breaks, so on day four he switches the flag fully on and sets the experiment to running, and from then on the experiment decides the split, as the next sections show. Had the payment failure rate doubled on day two, one Flipper.disable would have ended the problem in seconds, for the 5% who saw it, not for everyone.
One rule keeps flags from turning into clutter: every flag gets an owner and a removal date when it is created. When the experiment is decided, the losing branch of the code is deleted and the flag goes with it. Old flags are code paths nobody tests any more.
Choose the randomisation unit before anything else
The randomisation unit is the thing you split: a visitor, a session, a customer account, sometimes a basket. It sounds like a detail. It decides what your test can measure and what it can get wrong. Kohavi, Tang and Xu give the unit its own chapter, and their main rule is simple: pick a unit at least as large as the thing your metric and your change touch, so the same person does not see both versions4.
| Unit | What identifies it | Good for | Watch out for |
|---|---|---|---|
| Session | A session cookie, ends when the visit ends | Changes that only matter within one visit, such as search ranking | The same person sees both versions on different visits. Never use it for prices, delivery fees or anything they will remember |
| Visitor | A first party cookie with a random ID | Most shop tests: product pages, checkout, navigation | A visitor on two devices counts as two people. Cookies get cleared. Needs a consent decision (see the consent section) |
| Customer | The customer account ID | Tests that run over weeks: loyalty, emails, repeat purchase | Only works for people who are logged in, who are your better customers, so results may not carry over to new visitors |
Example: why Shannonside splits the checkout test by visitor. If Niamh split by session, a visitor who starts checkout on Monday and comes back on Wednesday might see the one page checkout first and the three step checkout second. Some would get confused and leave, and that confusion would count against both versions. By customer would be cleaner, but most checkout starters at Shannonside check out as guests, so a customer split would test the new checkout on a minority of regulars. The visitor is the right unit here. For a test of a loyalty email sequence a month later, Niamh would switch to the customer, because emails go to accounts, not to cookies.
Deterministic assignment: the same visitor always gets the same version
Once you know the unit, you need a rule that puts each unit into a version. You could roll a dice on every request and store the answer, but then you need a database lookup on every page and the stored answers can get out of step. The cleaner way is deterministic assignment by hashing. A hash function turns any text into a long number that looks random but is always the same for the same input.
For a unit ID and an experiment salt (a short text unique to the experiment), the bucket is (Foundations: probability):
where:
- is the bucket, a whole number from to
- is the salt, a colon and the unit ID joined into one text
- is a standard hash function that returns 64 hexadecimal characters
- keeps the first eight of them
- reads those eight characters as a number in base 16
- keeps the remainder after dividing by 10,000.
Because the hash spreads inputs evenly, every bucket is equally likely, so buckets 0 to 4,999 hold half of all visitors.
Example: Shannonside's checkout experiment has the salt one_page_checkout_2027 and a 50/50 split: buckets 0 to 4,999 get the current checkout (control), buckets 5,000 to 9,999 get the one page checkout. Visitor 7d1c2e9a arrives. The text one_page_checkout_2027:visitor:7d1c2e9a hashes to a value that starts with 0134f446. Read as a base 16 number, that is 20,247,622. Divided by 10,000 it leaves a remainder of 7,622, so this visitor is in bucket 7,622 and sees the one page checkout, today, tomorrow and on every page in between. Visitor a04f61b3 lands in bucket 2,686 and sees the current checkout. A second experiment with a different salt, say a delivery message test with the salt delivery_message_2027, puts the same two visitors in buckets 9,476 and 3,395. The two splits have nothing to do with each other, which is exactly what you want.
Here is the assignment service in Callum's shop. It is plain Ruby with no gem.
# app/models/experiment.rb
# Columns: key, salt, unit ("visitor" or "customer"), status,
# allocations (jsonb, e.g. {"control" => 50, "one_page" => 50})
class Experiment < ApplicationRecord
def running?
status == "running" && Flipper.enabled?(key) # the flag is the kill switch
end
def control
allocations.keys.first
end
end
# app/services/experiments/assigner.rb
require "digest"
module Experiments
class Assigner
BUCKETS = 10_000
def self.bucket(salt, unit_id)
Digest::SHA256.hexdigest("#{salt}:#{unit_id}")[0, 8].to_i(16) % BUCKETS
end
def initialize(experiment)
@experiment = experiment
end
# Same experiment, same unit: always the same variant
def variant_for(unit_id)
return @experiment.control if unit_id.nil? || !@experiment.running?
bucket = self.class.bucket(@experiment.salt, unit_id)
upper = 0
@experiment.allocations.each do |variant, percent|
upper += percent * BUCKETS / 100
return variant if bucket < upper
end
@experiment.control
end
end
end
Experiment#running? checks both the status and the Flipper flag, so switching the flag off sends everyone to control at once. Assigner.bucket is the formula above, line for line. variant_for walks through the allocations: with 50 and 50, buckets below 5,000 get the first variant and the rest get the second. A visitor with no unit ID (for example someone who declined the storage the test needs) always gets control.
Two rules protect this design. First, a new experiment always gets a new salt, otherwise the same visitors land in the treatment group test after test and carry over what they learnt. Second, never change the allocation of a running experiment. Moving from 50/50 to 70/30 halfway through moves some visitors from one version to the other and mixes the before and after. If the split must change, stop the experiment and start a new one with a new salt.
Log the exposure, not the assignment
Every visitor to the shop has a bucket, but most of them never reach checkout, so most of them never see the difference. If you include them in the analysis, they add noise and no signal. The fix is to record an exposure: a row written at the moment a visitor actually sees the part of the page that differs between versions. The analysis then only includes exposed visitors. Kohavi, Tang and Xu call this triggering, and they treat it as one of the best ways to make a test more sensitive5.
The exposure must be logged the same way in both groups. The control group never sees anything new, so you log them at the point where they would have seen it: when the checkout page renders, whichever version it is.
# db/migrate/20270301090000_create_experiment_exposures.rb
class CreateExperimentExposures < ActiveRecord::Migration[8.0]
def change
create_table :experiment_exposures do |t|
t.string :experiment_key, null: false
t.string :unit_id, null: false
t.string :variant, null: false
t.datetime :first_exposed_at, null: false
t.timestamps
end
add_index :experiment_exposures, %i[experiment_key unit_id], unique: true
add_column :spree_orders, :experiment_unit_id, :string
end
end
# app/controllers/concerns/experiment_helpers.rb
module ExperimentHelpers
extend ActiveSupport::Concern
# Call it only where the visitor actually sees the difference
def experiment_variant(key)
experiment = Experiment.find_by!(key: key)
@experiment_unit_id = experiment_unit_id(experiment)
variant = Experiments::Assigner.new(experiment).variant_for(@experiment_unit_id)
log_exposure(experiment, variant) if @experiment_unit_id && experiment.running?
variant
end
private
def experiment_unit_id(experiment)
return spree_current_user && "customer:#{spree_current_user.id}" if experiment.unit == "customer"
return nil unless experiment_storage_allowed? # the consent decision, see below
if cookies.signed[:exp_uid].blank?
cookies.signed[:exp_uid] = { value: SecureRandom.uuid, expires: 6.months, httponly: true, same_site: :lax }
end
"visitor:#{cookies.signed[:exp_uid]}"
end
# One row per unit and experiment: the first exposure wins
def log_exposure(experiment, variant)
ExperimentExposure.insert_all(
[{ experiment_key: experiment.key, unit_id: @experiment_unit_id,
variant: variant, first_exposed_at: Time.current }],
unique_by: %i[experiment_key unit_id]
)
end
end
# In the storefront's checkout controller
def edit
variant = experiment_variant("one_page_checkout_2027")
if @experiment_unit_id && current_order.experiment_unit_id.nil?
current_order.update_column(:experiment_unit_id, @experiment_unit_id)
end
render(variant == "one_page" ? "checkouts/one_page" : "checkouts/edit")
end
The migration creates one table and one extra column on the order, so every order can be traced back to the experiment unit that placed it. insert_all with unique_by skips the row if this unit already has one, so the first exposure time is kept however many times the page reloads. Rails fills in the timestamps itself6. spree_current_user and current_order are the helpers Solidus gives every storefront controller. The checkout action logs the exposure for both versions and only then decides which template to render.
Example: what triggering saves Shannonside. The one page checkout is expected to lift the share of checkout starters who order by 8%, from 38.1% to 41.1%. Analysed over the 5,200 monthly checkout starters, the test needs about 4,043 starters per version, which takes 7 weeks (the next section shows the formula). Analysed over all 74,000 monthly visitors instead, the same extra orders are a lift from 2.68% to 2.89% of visitors. That tiny difference is buried under 68,800 visitors a month who never saw a checkout, and the test would need about 92,680 visitors per version, which is 11 weeks. Logging the exposure where it happens cuts the test from 11 weeks to 7.
Sample size and duration, decided before the start
Before the test begins, decide how big an effect you want to be able to detect, and work out how many units that takes. The smallest effect worth detecting is called the minimum detectable effect (MDE). Smaller effects need many more units, because the noise does not shrink as fast as the effect does. The sample size article covers the background. Here is the formula for a yes or no metric such as "ordered or not" (Foundations: sample size):
where:
- is the number of units needed in each version
- is the conversion rate of the control
- is the conversion rate you hope the new version reaches, so is the minimum detectable effect in percentage points
- is the false alarm rate you accept, usually , which makes
- is the power, the chance of detecting the effect if it is real, usually , which makes .
Example: Shannonside's checkout test. The control rate is . Niamh wants to detect an 8% relative lift, so . The top line is times , which gives . The bottom line is . So:
That is checkout starters per version, 8,086 in total. At 1,200 starters a week, that takes 6.7 weeks, which Niamh rounds up to 7 full weeks. Full weeks matter: people shop differently at weekends and on paydays, and a test that stops on a Thursday has seen more Mondays than Saturdays.
The table shows why the choice of MDE is a business decision, not a statistical one.
| Lift to detect (relative) | Conversion to detect | Starters per version | Weeks at 1,200 a week |
|---|---|---|---|
| 3% | 38.1% to 39.2% | 28,522 | 47.5 |
| 5% | 38.1% to 40.0% | 10,302 | 17.2 |
| 8% | 38.1% to 41.1% | 4,043 | 6.7 |
| 10% | 38.1% to 41.9% | 2,595 | 4.3 |
| 15% | 38.1% to 43.8% | 1,160 | 1.9 |
| 20% | 38.1% to 45.7% | 655 | 1.1 |
A shop of Shannonside's size cannot afford to look for a 3% improvement in checkout: it would take most of a year. It can afford to look for 8%. That is a useful rule for smaller shops: test bold changes, not button colours, because only bold changes produce effects large enough to measure in weeks. The article on how much data you need goes further on what a small budget can and cannot test.
Check the split before you read the result: sample ratio mismatch
If you assigned 50% to each version, you should see roughly 50% in each. When the observed split is clearly different from the planned one, the test has a sample ratio mismatch (SRM). An SRM means something removed or added units in one group and not the other, and the result cannot be trusted, however good it looks. Fabijan and colleagues, writing from Microsoft, Booking.com and others, found that about 6% of experiments at Microsoft had one, and listed the usual causes: redirects that lose visitors in one version, bots that behave differently, tracking that is lost more often in one version, and analysis filters that treat the groups differently7.
The check is a chi square test that compares the counts you observed with the counts the allocation predicts (Foundations: hypothesis tests):
where:
- is the observed number of exposed units in version
- is the expected number, the total multiplied by the planned share of version
- is the test statistic, which grows as the observed split moves away from the plan
- is the probability of a split at least this uneven if nothing is wrong
- is the complementary error function, which gives that probability directly when there are two versions (one degree of freedom).
Because the check runs on every experiment, set a strict threshold such as , so that it only raises an alarm when something is really broken.
Example: two checks at Shannonside. In the real run, after 7 weeks, 4,190 starters were exposed to the current checkout and 4,210 to the one page checkout, 8,400 in total, so 4,200 were expected in each. , and . Grand, nothing is wrong. Now an earlier attempt, where the one page checkout first sent visitors through a redirect to a new address: 4,412 starters in control and only 3,988 in the one page version. , and . The redirect lost visitors on slow mobile connections before the exposure was logged, so the treatment group was missing exactly the visitors most likely to abandon. That version looked like a winner. It was not a result at all. Callum removed the redirect, gave the experiment a new salt and started again.
The check is a few lines of Ruby, run every morning as a job.
# app/jobs/sample_ratio_check_job.rb
class SampleRatioCheckJob < ApplicationJob
THRESHOLD = 0.001
def perform
Experiment.where(status: "running").find_each do |experiment|
next unless experiment.allocations.size == 2 # erfc gives the p value for two versions
counts = ExperimentExposure.where(experiment_key: experiment.key).group(:variant).count
total = counts.values.sum
next if total < 1_000 # too early to judge
chi2 = experiment.allocations.sum do |variant, percent|
expected = total * percent / 100.0
(counts.fetch(variant, 0) - expected)**2 / expected
end
p_value = Math.erfc(Math.sqrt(chi2 / 2))
if p_value < THRESHOLD
experiment.update!(status: "paused")
ExperimentMailer.with(experiment: experiment, counts: counts, p_value: p_value)
.sample_ratio_mismatch.deliver_later
end
end
end
end
# config/recurring.yml (Solid Queue)
production:
sample_ratio_check:
class: SampleRatioCheckJob
schedule: every day at 6am
The job counts exposures per version with one grouped query, computes the formula above, and pauses the experiment and sends an email when the split is off. Ruby's Math.erfc is built in, so no statistics library is needed. Solid Queue, the default job backend in Rails 8, runs it every morning from the recurring schedule8. With more than two versions, use a chi square function with the right degrees of freedom, such as scipy.stats.chisquare in Python.
A related habit: before the first real experiment, run an A/A test, where both groups get exactly the same version. It should show no difference and no SRM. If it shows either, the problem is in your pipeline, and it is better to find it with nothing at stake9.
Peeking: why looking every day breaks the maths
A 95% confidence level promises that, when there is no real difference, you will be fooled only 5% of the time. That promise holds for one look at the end of the test. Every extra look is another chance to catch the noise at a moment when it happens to cross the line. Look every day and stop the first time the dashboard says "significant", and the 5% becomes something much larger. The significance article shows this with one test. Here is how big the effect is.
Example: how often a shop with no real difference "finds" a winner. I simulated 60,000 A/A tests, where both groups get the same version, and stopped each one the first time the usual test crossed 95% confidence. With one look at the end, 5.0% of the tests produced a false winner, as promised. With two looks, 8.3%. With five, 14.1%. With a look every week for seven weeks, 16.8%. With a look every day for seven weeks, 31.9%. Nothing about the shop changed. Only the number of looks did.
Example: what peeking would have done to Niamh's test. After the first week the one page checkout had converted 43.5% of its starters against 37.8% for the current checkout, a lift of 15%, and the usual test statistic was 2.00, just over the 1.96 line. A daily dashboard would have shown green. Had she stopped there, she would have booked a 15% lift. The test went on to settle at 8.6%. The early number was not a lie, it was noise on top of a real effect, and stopping at the first green moment picks the noisiest moment by design.
Sequential testing: looking early, honestly
There are good reasons to look early. A change might be harming sales, or might be so clearly better that waiting costs money. Sequential testing lets you look several times and still keep the 5% promise, by setting a stricter bar for the early looks.
A classic method from clinical trials is the one by O'Brien and Fleming10. You decide in advance how many looks you will take, , and set a boundary for each look (Foundations: hypothesis tests):
where:
- is the value the test statistic must exceed at look to stop
- is the total number of planned looks
- is the number of the current look, from to
- is a constant chosen so that the overall false alarm rate stays at 5%.
For seven equally spaced looks, my simulation gives . Early looks need overwhelming evidence, and the last look needs only a little more than the usual .
Example: Niamh's test with seven weekly looks. The boundaries are for weeks to .
| Week | Boundary | Test statistic observed | Decision |
|---|---|---|---|
| 1 | 5.47 | 2.00 | Continue |
| 2 | 3.87 | 2.22 | Continue |
| 3 | 3.16 | 2.57 | Continue |
| 4 | 2.73 | 2.50 | Continue |
| 5 | 2.45 | 2.76 | Stop, the one page checkout wins |
| 6 | 2.23 | 2.95 | Not needed |
| 7 | 2.07 | 3.06 | Not needed |
With this plan, Niamh could have stopped after five weeks and saved two, with the false alarm rate still at 5%. One caution: a test stopped early at a boundary tends to overstate the size of the effect a little, because it stopped on a high point. Use the early stop to decide, and keep measuring the effect after launch.
Another family of methods, called always valid inference, lets you look at any time without planning the looks in advance. Johari, Pekelis and Walsh describe the approach and show that ordinary p values are "wholly unreliable" when people monitor tests continuously11. Either way, write the plan down before the test starts. A rule invented after looking at the data is not a rule.
Reading the result: the interval, not the verdict
At the end of the test, the question is not "did it win?" but "by how much, and how sure am I?". The answer is a confidence interval on the difference between the two versions (Foundations: confidence intervals):
where:
- and are the observed conversion rates of control and treatment
- and are the numbers of exposed units in each
- is the observed difference
- is its standard error, the typical size of the noise
- is the 95% confidence interval, the range of true differences that fit the data.
Divide each end by to express it as a relative lift.
Example: the final result of Shannonside's test after 7 weeks. Control: 1,596 orders from 4,190 starters, . One page checkout: 1,741 orders from 4,210 starters, . The difference is , 3.26 percentage points. The standard error is . The interval is , from 0.0117 to 0.0535. Relative to the control, that is a lift of 8.6%, with an interval from 3.1% to 14.1%. The test statistic is .
In money: the shop's 1,980 monthly orders all pass through checkout, so a lift of 8.6% means more orders a month, worth , so €3,822 in contribution. The low end of the interval, 3.1%, means 61.4 orders and €1,378 a month. The high end, 14.1%, means 279.2 orders and €6,265. Even the low end comfortably pays for the work, so the decision is easy. If the interval had run from minus 2% to plus 12%, the honest answer would be "probably positive, not proven", and the decision would depend on what the change costs to keep.
The first week's estimate was almost twice the final one, and its interval fitted almost any outcome. That is the best argument against stopping early.
CUPED: use what you already know about visitors to need fewer of them
Some metrics are very noisy. Contribution per visitor is the best metric for most shop tests, because it counts both more orders and more valuable orders, but it is mostly zeros with a few large values, so it needs huge samples. One way to cut the noise is CUPED (controlled experiments using pre experiment data), described by Deng, Xu, Kohavi and Walker at Microsoft12. The idea: a lot of the difference between visitors was there before the test started. A customer who spent a lot last quarter will probably spend a lot this quarter, whichever version they see. If you subtract the part you could have predicted, what remains is less noisy.
The adjusted metric for each unit is (Foundations: regression):
where:
- is the metric during the test, here contribution per visitor
- is the same unit's value before the test, for example contribution in the 90 days before
- is the average of over all units
- is the slope of on , computed once for both groups together
- and are covariance and variance
- is the correlation between and (Foundations: correlation).
The last part says the variance shrinks by the factor , and the sample size you need shrinks with it. The paper reports a variance reduction of about 50% at Bing, the same as doubling the traffic12. Visitors with no history get and a flag for "new", which the paper also handles12.
Example: a site wide test at Shannonside with contribution per visitor as the main metric. The average is €0.600 per visitor (), and because most visitors buy nothing, the standard deviation is about €4.56, so the variance is 20.80. For a metric like this, with variance , the sample size formula becomes , where is the difference you want to detect. To detect a 10% lift, in euro, it needs visitors per version: about 181,400 in total, almost 2.5 months of traffic. Suppose the correlation between a visitor's contribution in the 90 days before and during the test is (an invented but typical figure for a shop with many returning customers). Then , and the test needs visitors per version, under 2 months. CUPED saves 20% of the traffic, about two weeks, for a few lines of code. If the shop had more returning customers and , the saving would be 36%.
CUPED needs a covariate that the treatment cannot have changed, which is why it must come from before the experiment started. Anything measured after assignment can carry part of the effect and bias the result.
Guardrail metrics: what must not get worse
A test has one primary metric, the one the decision rests on. It should also have guardrail metrics: numbers that must not get worse, even if the primary metric improves. Kohavi, Tang and Xu distinguish two kinds: trust guardrails, which tell you whether the experiment itself is sound (the sample ratio check is the main one), and organisational guardrails, which protect the business13.
For a shop, a sensible set of organisational guardrails is short:
- contribution per order, so a conversion win is not bought with smaller or less profitable baskets
- the return rate after 30 days, because a checkout that pushes people through faster can also push through orders they regret
- payment failures and errors, which show broken code before customers complain
- page speed, measured on the pages the test changed
- contacts to customer service per order, a quiet signal of confusion
- newsletter unsubscribes, for tests that touch email
Example: Shannonside's guardrails for the one page checkout. Niamh wrote them into the plan before the start, each with a limit: average order value must not fall by more than 3%, the 30 day return rate must not rise by more than one percentage point, and the payment failure rate must not rise at all. The results: average order value €83.30 against €84.10, a fall of 1.0% with an interval from minus 3.5% to plus 1.5%. Returns within 30 days 9.2% against 9.0%. Payment failures 4.0% against 4.1%. The page took 1.3 seconds to become usable against 1.1 seconds, because the address lookup loads a script. No limit was broken, so the result stands. The extra 0.2 seconds went onto Callum's list. Whether the small dip in order value is real, the test cannot tell (its interval includes zero), and the €3,822 a month is large enough to carry it either way.
Running several experiments at once
A shop that tests seriously soon has several experiments running at the same time. The worry is interaction: one test changing the effect of another. Because each experiment has its own salt, every visitor is assigned to each test independently, and every combination of versions appears in roughly equal numbers. That makes interactions measurable, and in practice rare. A Microsoft team looked at every pair of tests running on the same day across four large products and found signs of interaction in about 1 in 50,000 test pair metrics, and in none of those did one test's effect turn significantly in the opposite direction because of the other14.
Example: two tests at Shannonside overlap. While the checkout test runs, Niamh also tests a message on the basket page that tells visitors how much more they need to spend for free delivery. Each test splits 50/50 on its own salt, so the 8,400 checkout starters fall into four groups of about 2,100 each. Callum checks the checkout result within each half of the delivery message test. Without the message: 37.6% in control and 40.9% with the one page checkout, a gain of 3.3 points. With the message: 38.6% and 41.8%, a gain of 3.2 points. The checkout effect is the same whichever message the visitor saw, so the two tests can run side by side.
Some tests should not overlap: two experiments that change the same thing, such as two free delivery messages on the same basket page. Run those one after the other, or split visitors so nobody is in both. That costs traffic, so do it only where you expect a real clash.
Long term holdouts: does the sum of the wins really add up?
Each experiment measures one change over a few weeks, and the results do not simply add up. Effects can fade, because novelty wears off, or grow, because returning customers learn to use something better. Hohnhold, O'Brien and Tang at Google showed that the effect people measure in a short test can differ from the long term effect once users have adapted, and they built a method to measure the gap15. Kohavi, Tang and Xu give the topic a whole chapter16.
A long term holdout is the practical answer for a shop: a random share of visitors or customers who get none of the changes you ship during a period. At the end, you compare them with everyone else. The difference is what the whole set of changes is really worth.
To size it, use the number of orders in each group. For a relative difference in orders per unit, the standard error is approximately (Foundations: confidence intervals):
where:
- is the standard error of the relative difference between the holdout and the rest
- is the number of orders in the holdout group
- is the number of orders in the rest of the shop.
The 95% interval is the observed difference plus or minus .
Example: Shannonside's holdout for the first half of 2027. Over six months, five changes ship, and their individual tests add up to an 11% lift in orders per visitor. Callum keeps 10% of visitors in a holdout that sees none of them. Six months of traffic is 444,000 visitors, so 44,400 in the holdout, and at 2.68% that is about 1,188 orders. The rest place about 10,692. The standard error is , so the interval is about plus or minus 6%. At the end, the rest of the shop converts 7% better than the holdout, with an interval from 1% to 13%. The changes are real, but worth less together than the 11% the separate tests suggested, which is a normal finding: some effects overlap, some fade. Niamh now plans with 7%, not 11%.
Two practical points. A 5% holdout at this size would give an interval of about plus or minus 8%, too wide to tell much, so smaller shops need a larger holdout or a longer period. And visitor cookies get cleared over six months, so for long holdouts the customer account is the better unit, at the price of only covering logged in customers.
Analysing the results in SQL and Python
The analysis has two steps. A SQL query turns the exposures and orders into one row per version (or one row per unit, for CUPED). A small script then computes the interval. Everything runs on your own database, which is the point of owning the system: the orders, the costs and the exposures are in one place, so the metric can be contribution, not just clicks.
-- One row per version: exposed units, units that ordered, orders, revenue
WITH exposed AS (
SELECT unit_id, variant, first_exposed_at
FROM experiment_exposures
WHERE experiment_key = 'one_page_checkout_2027'
)
SELECT e.variant,
COUNT(DISTINCT e.unit_id) AS units,
COUNT(DISTINCT o.experiment_unit_id) AS units_with_order,
COUNT(o.id) AS orders,
COALESCE(SUM(o.item_total), 0) AS item_total
FROM exposed e
LEFT JOIN spree_orders o
ON o.experiment_unit_id = e.unit_id
AND o.state = 'complete'
AND o.completed_at >= e.first_exposed_at
AND o.completed_at < e.first_exposed_at + INTERVAL '14 days'
GROUP BY e.variant
ORDER BY e.variant;
The query starts from the exposures, so a unit counts only once it has seen the checkout. Orders count only if they were completed after the first exposure and within 14 days of it, a fixed window that treats both versions the same. item_total is the order's product value in Solidus. For contribution, join the cost and margin figures you already use for unit economics.
# analyse_experiment.py: reads one row per unit (variant, ordered, contribution, pre_contribution)
import csv
from statistics import NormalDist, covariance, mean, variance
rows = [{**r, "y": float(r["contribution"]), "x": float(r["pre_contribution"]), "ordered": int(r["ordered"])}
for r in csv.DictReader(open("one_page_checkout_2027.csv"))]
def interval(control, treatment, level=0.95):
z = NormalDist().inv_cdf(0.5 + level / 2)
diff = mean(treatment) - mean(control)
se = (variance(control) / len(control) + variance(treatment) / len(treatment)) ** 0.5
return diff, diff - z * se, diff + z * se
# Conversion: share of exposed units with an order
by = lambda v, key: [r[key] for r in rows if r["variant"] == v]
print("conversion", interval(by("control", "ordered"), by("one_page", "ordered")))
# CUPED on contribution: one theta for both groups, from data before the test
theta = covariance([r["x"] for r in rows], [r["y"] for r in rows]) / variance([r["x"] for r in rows])
x_bar = mean(r["x"] for r in rows)
for r in rows:
r["y_adj"] = r["y"] - theta * (r["x"] - x_bar)
print("contribution, CUPED", interval(by("control", "y_adj"), by("one_page", "y_adj")))
The script uses only Python's standard library (statistics.covariance needs Python 3.10 or later). interval is the confidence interval formula from earlier, written for any metric: for a yes or no metric the mean is the conversion rate and the variance is , so it gives the same answer as the hand calculation. The CUPED part computes once over both groups, adjusts every unit, and runs the same interval on the adjusted values.
Consent and experiments
An experiment on visitors who are not logged in needs to recognise the same visitor again, and that usually means storing an ID in their browser. Storing or reading information on a visitor's device is regulated separately from data protection. What follows is general information about the law as I read it, not legal advice.
In Ireland the rule is Regulation 5 of the ePrivacy Regulations, S.I. No. 336 of 2011. You may store information on a user's device, or read it, only if the user has consented and has been given clear and comprehensive information, prominently displayed and easily accessible, that includes the purposes. The only exceptions are storage for the sole purpose of transmitting a communication, and storage that is "strictly necessary in order to provide an information society service explicitly requested by the subscriber or user"17. A visitor asks for a shop, not for a test, so a cookie whose only job is to keep them in the same version of an experiment is hard to fit into that exception. The safe reading is that it needs consent, like analytics.
Separately, the experiment data itself is personal data when it is linked to a visitor ID or a customer account, so it needs a lawful basis under Article 6 of the GDPR, usually legitimate interests, and a line in your privacy notice18.
Three design rules follow.
- Respect the decision before assignment. If a visitor does not consent,
experiment_storage_allowed?returns false, the visitor gets the control version, and nothing is logged. Because this happens before assignment, it removes the same kind of people from both groups and does not bias the comparison. - Remember who you measured. The result describes visitors who consented. If they differ from the others (for example more returning customers), the effect for everyone may differ a little.
- Keep the consent banner out of the test. If one version changes the banner or anything that affects consent, the groups no longer have the same consent rate, which shows up as a sample ratio mismatch.
Example: how Shannonside sets it up, and what it costs in time. The shop's consent banner has a separate purpose called "improving the shop with tests", off by default and described in one plain sentence: a first party cookie called exp_uid, used only to keep visitors in the same version of a test, not shared, kept for six months. experiment_storage_allowed? returns true only when that box is ticked. Logged in customers in customer level tests are assigned by account ID on the server, which reads nothing extra from the device, and the privacy notice lists testing as a purpose under legitimate interests. The cost shows up in the sample size. For simplicity, the numbers in this chapter assume everyone takes part. If only 70% of checkout starters consent, the 1,200 a week become 840, and the 8,086 starters the checkout test needs take weeks, so 10 full weeks instead of 7. So always plan with the traffic that consents, not the total. Niamh had the wording checked by her solicitor before the first test.
From idea to decision: the whole flow
Every part of this chapter fits into one sequence. Writing it down as a plan before the start, and as a record at the end, is what turns a test into knowledge the shop keeps.
The plan needs no special software: a table in the shop's admin with one row per experiment is enough, as long as it is written before the first visitor is assigned, so nobody can move the goalposts after seeing the data.
Example: the plan for Shannonside's checkout test, as Niamh wrote it on the first day.
| Field | Entry |
|---|---|
| Hypothesis | A one page checkout with address lookup lets more starters finish, because it removes two page loads and most typing |
| Primary metric | Share of exposed checkout starters who complete an order within 14 days |
| Unit and trigger | Visitor cookie, exposure logged when the checkout page renders |
| Allocation and salt | 50/50, one_page_checkout_2027 |
| Minimum detectable effect | 8% relative (38.1% to 41.1%) |
| Sample size and end | 4,043 starters per version, 7 full weeks, one look at the end |
| Guardrails | Order value no worse than minus 3%, 30 day returns no more than one point higher, payment failures not higher, sample ratio check |
| Decision rule | Ship if the lower end of the interval is above zero and no guardrail is broken |
| Owner and removal date | Callum, flag and old checkout removed two weeks after the decision |
| Result | Lift 8.6% (interval 3.1% to 14.1%), about €3,822 a month in contribution, shipped |
The last row is filled in at the end. Over a year, that table becomes the shop's memory: which ideas worked, by how much, and which ones did not. The next chapter on the improvement loop turns that register into a monthly rhythm.
Conclusion: trust is built into the code
A trustworthy test is not a matter of a better dashboard. It comes from a handful of decisions made in the code before the first visitor arrives: a flag that can switch everything off, a randomisation unit that matches the change, assignment by hashing so each visitor stays in one version, an exposure logged where the difference is seen, a sample size worked out in advance, a daily sample ratio check, a fixed rule for when to look, and guardrails written down before the result is known.
Owning the shop's code makes all of it possible, and none of it is large: one table, one service, one controller concern, one job and one query. The reward is that when the numbers say a change earns €3,822 a month, you can believe them, and when they say an idea did nothing, you can let it go without regret. The chapter on measuring features in isolation uses this machinery to value what you already have, and the improvement loop uses it to decide what to build next.