Sub topic 5
Picking the randomization unit and who is eligible
This chapter assumes you know what a hypothesis and a primary metric are, and that you have seen the sample size formula for two proportions. It covers two decisions that go into the experiment brief before any code is written. The first is which thing gets randomized. The second is which of those things are allowed into the test at all.
What the randomization unit is
The randomization unit is the entity that receives a variant. Every unit is assigned once, and all of its activity is then served from that variant. If the unit is a user, a given user sees control on every visit or treatment on every visit.
The analysis unit is the entity your primary metric is computed over, such as users, sessions or orders. Most of the trouble in this area comes from picking a randomization unit that does not match the analysis unit.
| Unit | Typical use | Strength | Weakness |
|---|---|---|---|
| Logged-in user ID | Features tied to an account | Consistent across devices and visits | Does not cover logged-out traffic |
| Device or cookie ID | Anonymous or pre-signup flows | Works before login | Same person can land in both variants on different devices; cookies get cleared |
| Session | UI tweaks with no memory, such as ranking | Many units, fast sample growth | Same person sees both variants; carryover and confusion |
| Account or organization | B2B products with shared workspaces | Teammates share one experience | Few units, so wide intervals |
| Page view or request | Latency or infrastructure tests | Very large sample | Cannot measure anything about people over time |
| Geography or cluster | Pricing, marketplaces, ads | Limits interference between units | Very few units, high variance |
Match the unit to the metric
Choose the unit that is at or above the level of your metric, not below it. If the metric is "checkout completion rate per user", randomize by user. If the metric is "30-day retention", a session-level split is meaningless, because one person would be counted in both arms.
Two problems appear when the randomization unit is coarser than the analysis unit.
- Correlated observations. Suppose you randomize by user but compute click-through rate per page view. One heavy user produces hundreds of page views that all share the same variant and similar behavior. Treating those as independent makes the standard error too small. The confidence interval looks tight, and the test produces false positives more often than the stated alpha.
- Unequal weighting. Per-page-view rates give heavy users more influence than light users. The result answers a different question from "what does this do to the average user?".
You have three ways out. Compute the metric per randomization unit, for example the share of each user's page views that were clicks, and then compare those user-level values. Use a method built for clustered data, such as the delta method or cluster-robust standard errors, and ask your data partner which they use. Or randomize at the level of the metric, when that is feasible.
The opposite mismatch is also possible. If you randomize by session but your hypothesis is about long-term user behavior, the experiment cannot answer it.
Consistency and interference
Two further considerations push you toward a coarser unit.
Consistency of experience. If a user sees a new checkout on Monday and the old one on Tuesday, you measure confusion rather than the feature. For anything a person would notice, use a stable ID so the assignment is sticky. A logged-in user ID is the best choice. A cookie is acceptable for anonymous traffic, but expect some leakage across devices and some loss from cleared cookies.
Interference. Randomization assumes one unit's outcome does not depend on another unit's variant. This breaks in several places:
- Two-sided marketplaces: if treated buyers win more bids, control buyers lose them.
- Social or collaborative features: a treated user invites a control user.
- Shared inventory or budgets: a discount that drains stock affects everyone.
- Team workspaces: one member's variant changes what the rest of the team sees.
When interference is likely, randomize at the level where it stays contained, such as the workspace, the market or the region. You pay for this with fewer units and less power. Tell your data partner early, because the sample size calculation then runs over clusters and not users.
Who is eligible
Eligibility is the rule that decides which units can enter the experiment. Write it in the brief in terms of attributes you can check at the moment of assignment, for example "logged-in users on web with at least one saved address". It has two jobs.
First, it keeps out people who cannot experience the change. A saved-address autofill cannot affect a user who has no saved address. Including them adds noise and shrinks the measured effect.
Second, it keeps the comparison fair. The rule must be applied identically to both arms and must depend only on information that exists before, or independently of, the variant.
Dilution
If only part of your population can be affected, including everyone dilutes the effect. Say 20% of users ever reach checkout, and the feature lifts completion by one point among those who do. Across all users the lift is about 0.2 points. Required sample size grows roughly with the inverse square of the effect, so detecting 0.2 points takes about 25 times as many users as detecting 1 point. Restricting the analysis to users who actually reach the point where the variants differ is called triggering. It is usually the cheapest way to gain power.
Triggering has a rule: the trigger event must be logged for both arms, at the point where the experiences would diverge. Control users need an equivalent log entry, often called a counterfactual log, even though they see nothing different. Without it, you cannot define the same population in both arms.
Do not filter on what happens after assignment
Excluding users based on behavior that the variant could influence breaks the randomization. Examples are "only users who opened the new page" or "only users who stayed more than a minute". Treatment may change who does these things, so the two arms stop being comparable. Define the population by eligibility or by a trigger that is logged symmetrically, and analyze everyone who meets it.
Putting it into code
The assignment function should take the unit ID and the eligibility rule explicitly. The eligibility check runs first, and the experiment key goes into the hash so that assignments are independent across experiments.
import hashlib
EXPERIMENT_KEY = "checkout_address_autofill"
def bucket(unit_id: str, experiment_key: str, buckets: int = 10000) -> int:
digest = hashlib.sha256(f"{experiment_key}:{unit_id}".encode()).hexdigest()
return int(digest[:8], 16) % buckets
def is_eligible(user: dict) -> bool:
return (
user.get("logged_in", False)
and user.get("platform") == "web"
and user.get("saved_address_count", 0) >= 1
)
def assign(user: dict, treatment_share: float = 0.5):
"""Return 'control', 'treatment', or None if the user is not eligible."""
if not is_eligible(user):
return None
threshold = int(treatment_share * 10000)
unit_id = user["user_id"] # change this field to randomize by account instead
return "treatment" if bucket(unit_id, EXPERIMENT_KEY) < threshold else "control"
users = [
{"user_id": "u-1", "logged_in": True, "platform": "web", "saved_address_count": 2},
{"user_id": "u-2", "logged_in": True, "platform": "web", "saved_address_count": 0},
{"user_id": "u-3", "logged_in": False, "platform": "web", "saved_address_count": 1},
]
for u in users:
print(u["user_id"], assign(u))Users u-2 and u-3 return None and are never logged as part of the experiment. To randomize by account, change the one line that picks unit_id to read user["account_id"]. Every member of an account then shares a variant.
The brief should state both decisions in the same place as the metric:
randomization_unit: user_id
eligibility: logged-in users on web with at least one saved address
trigger_event: checkout_started # logged for control and treatment
analysis_unit: user_idCommon errors
- Changing identity mid-experiment. A visitor is assigned by cookie, then logs in and is assigned by user ID. They may switch variants. Decide which ID wins and whether the mapping is stable, and ask engineering how the flag service handles the transition.
- Eligibility that changes over time. If "has a saved address" is evaluated on every visit, a user can become eligible after assignment, or lose eligibility. Evaluate at first exposure and keep the assignment sticky.
- Reusing the same hash input across experiments. Without the experiment key in the hash, the same users land in treatment every time, and effects from different experiments become confounded.
- Different eligibility in the analysis than in production. The data team filters on a rule that differs slightly from what the flag evaluated. This often shows up later as a sample ratio mismatch, which a later chapter covers.
- Expecting a unit to be clean when it is not. Cookie-based units overcount people. Be honest about this in the brief and in the readout.
Exercise
A team tests a new product-ranking algorithm on a marketplace. They randomize by search session and measure "orders per buyer over 14 days". Name two problems with this design and propose a better setup.
Show answer
First, the unit is finer than the metric. One buyer runs many sessions, so the same buyer appears in both arms and their 14-day orders cannot be attributed to a single variant. Second, sessions from one buyer are correlated, so treating sessions as independent understates variance. A better setup randomizes by logged-in buyer ID, so each buyer has one stable experience, and computes orders per buyer over 14 days. If sellers compete for the same demand, so that treated buyers' purchases change what control buyers see, consider randomizing by market or region and accept the lower power.