Sub topic 9
How variants are assigned and exposed
This chapter assumes you know what a hypothesis, a randomization unit and a feature flag are, from earlier chapters. It covers two separate events in an experiment. Assignment decides which variant a user belongs to. Exposure records that the user actually saw it. Many data-quality problems come from treating these as the same event.
Assignment and exposure are different events
Assignment is a calculation. Given a user and an experiment, the system returns "control" or "treatment". It can run for every request, whether or not the user ever reaches the changed screen.
Exposure is an observation. It is logged at the moment the user could first have been affected by the difference. For the checkout autofill test, that is the moment the address form renders, not the moment the user logs in.
This matters because analysis should compare users who could have been affected. If you count everyone assigned, including users who never reached checkout, the effect is diluted. The metric moves less, and you need more users to detect it. If you count only users who clicked something inside the treatment, you introduce selection bias, because only the treatment has that click.
The safe rule is to log exposure at a point that both variants reach. The control path must log the same event at the same point in the flow, with the variant name "control".
| Event | When it fires | Who produces it | Used for |
|---|---|---|---|
| Assignment | Flag evaluated for a user | Flag or experimentation service | Debugging, audit |
| Exposure | User reaches the changed experience | Client or server code at that surface | Defining the analysis population |
| Outcome | User does the thing being measured | Product instrumentation | Metrics |
Deterministic assignment with hashing
Most teams assign variants by hashing instead of storing a random draw per user. The user ID and an experiment key go into a hash function. The result maps to a bucket from 0 to 9,999, and ranges of buckets map to variants.
Hashing gives three properties:
- Stability. The same user gets the same variant on every visit, on every server, with no lookup table.
- Independence across experiments. The experiment key is part of the hash input, so being in treatment for one experiment says nothing about another.
- Reproducibility. Data can recompute any user's variant later, which helps when you investigate odd results.
import hashlib
def bucket(user_id: str, experiment_key: str, buckets: int = 10000) -> int:
digest = hashlib.sha256(f"{experiment_key}:{user_id}".encode()).hexdigest()
return int(digest[:8], 16) % buckets
def assign_variant(user_id: str, experiment_key: str, treatment_share: float = 0.5) -> str:
threshold = int(treatment_share * 10000)
return "treatment" if bucket(user_id, experiment_key) < threshold else "control"
users = [f"user-{i}" for i in range(20000)]
key = "checkout_address_autofill"
at_10 = {u for u in users if assign_variant(u, key, 0.10) == "treatment"}
at_50 = {u for u in users if assign_variant(u, key, 0.50) == "treatment"}
print(round(len(at_10) / len(users), 3))
print(round(len(at_50) / len(users), 3))
print(at_10 <= at_50)The last line prints True. Everyone in treatment at a 10% share is still in treatment at 50%. That property is what makes ramping safe, as described below.
If you left the experiment key out of the hash, a user in the first 10% of buckets would be in the first 10% for every experiment. Experiments would then be correlated, and effects from one would leak into the others.
Eligibility comes before assignment
The brief defines who is eligible. For the autofill test that is logged-in web users with at least one saved address. The flag system should check eligibility first and assign only eligible users. Users who fail the check get the default experience and no exposure event.
Do not check eligibility based on something the treatment changes. If eligibility depends on behavior after the change, the variants will have different populations, and the comparison is invalid before you start.
Feature flags as the delivery mechanism
A feature flag is the switch that runs the assignment logic and serves the right code path. An experiment flag differs from a plain release flag in four ways:
- It has a defined allocation, such as 50/50 or 10/90.
- It evaluates a stable ID, which is the randomization unit.
- It emits exposure events.
- It has an owner and an end date, so it does not become permanent clutter.
Engineering decides where the flag is evaluated. Server-side evaluation is easier to keep consistent across web, mobile and email, and it avoids flicker. Client-side evaluation is faster to build but can show a user the default for a moment before switching. That flash can contaminate the experience and the metrics.
Agree on a fallback in the brief. If the flag service times out, every user should receive the control experience. They should also be marked as not exposed, so they are excluded instead of silently counted as control.
Logging exposure correctly
An exposure event needs enough fields to join to outcomes and to audit the experiment. This example shows a minimal version that logs once per user per experiment per session.
import json
import time
_seen = set()
def log_exposure(user_id, experiment_key, variant, surface, session_id):
dedupe_key = (user_id, experiment_key, session_id)
if dedupe_key in _seen:
return None
_seen.add(dedupe_key)
event = {
"event": "experiment_exposure",
"timestamp": int(time.time()),
"user_id": user_id,
"experiment_key": experiment_key,
"variant": variant,
"surface": surface,
"session_id": session_id,
}
print(json.dumps(event))
return event
log_exposure("user-123", "checkout_address_autofill", "treatment", "checkout_address_form", "s-1")
log_exposure("user-123", "checkout_address_autofill", "treatment", "checkout_address_form", "s-1")The second call prints nothing because it is a duplicate. Analysis usually uses the first exposure timestamp per user. Outcomes before that timestamp are not attributed to the experiment.
Both variants must run this same call at the same point. A common bug is logging exposure only inside the treatment code branch. Control users are then never recorded, and the experiment looks as though it has no control group.
How the pieces fit together
Ramping without breaking the experiment
Ramping means increasing the share of users in treatment in stages, for example 1%, 10%, then 50%. Because the hash buckets are stable, widening the threshold adds new treatment users and does not reshuffle existing ones.
Ramping has one trap. At a 10% treatment share, the control group is 90% of users. When you move to 50/50, 40% of all users move from control to treatment. Users who saw control early and treatment later are contaminated. Metrics also shift over time, so pooling ramp days with full-allocation days can mislead.
The usual practice is to treat low-share stages as safety checks only. Analysis starts when the allocation reaches the planned split and stays fixed. The brief should state the start date of the analysis window.
Common assignment failures
- Unit mismatch. Assigning by session or device when the metric is per user means one person can see both variants. Use the same ID as the randomization unit in the brief.
- ID changes. Users who log in switch from an anonymous ID to a user ID and may switch variants. Decide how identity is handled and test it.
- Caching. A CDN or page cache may serve the same HTML to everyone. The variant must be part of the cache key, or the experience must be applied after the cache.
- Bots and internal traffic. Automated traffic and employee accounts add noise. Filter them in the eligibility rule or in the analysis, and record the choice in the brief.
- Overlapping experiments. If two tests change the same surface, their effects combine. Use mutually exclusive layers, which hold users out of one experiment when they are in the other, or at least record the overlap.
- Targeting changes mid-test. Editing eligibility rules after launch changes the population. Stop and restart instead.
Connecting this to the sample ratio check
The sample ratio mismatch test from the data-quality chapter reads exposure counts. If you planned 50/50 and the exposure counts are 50,210 versus 49,790, the test checks whether that gap is plausible by chance. A tiny p-value usually points back to an assignment or exposure bug from this chapter: a branch that logs only on treatment, a redirect that drops users, a cache that serves one variant, or a client that crashes before the event fires.
Run the check on exposure counts, not assignment counts. Assignment counts can be perfectly balanced while exposure is not, and the exposure imbalance is the one that biases the result.
What to put in the brief
Add an assignment section to the experiment brief. It should state:
- The experiment key and the randomization unit.
- The eligibility rule, and where in the flow it is evaluated.
- The allocation and the ramp schedule, including the date full allocation starts.
- The exposure point, as a named event on a named surface, for both variants.
- The fallback behavior if the flag service fails.
- Any overlapping experiments or exclusion layers.
Exercise
A team logs the exposure event inside the treatment code branch only. Control users trigger no event, so the team counts everyone who visited the site as control. What is wrong, and how would you fix it?
Show answer
The control group is defined differently from the treatment group. Control includes every visitor, including people who never reached the changed surface, while treatment includes only those who did. This dilutes the control metrics and can produce a false lift or hide a real one, and it often causes a sample ratio mismatch. Fix it by logging the same exposure event at the same point in the flow for both variants, with the variant name recorded, then analyze users who have an exposure event.
Exercise
You ramp a test from 10% to 50% treatment using hash buckets. Why do users who were in treatment at 10% stay in treatment at 50%, and why should you still not analyze the ramp period together with the full-allocation period?
Show answer
The threshold test is "bucket below threshold", so raising the threshold only adds buckets and never removes any. Users in the original 10% keep their variant. The ramp period should be analyzed separately or excluded because about 40% of users move from control to treatment, so those users saw both experiences. The allocation ratio and the user mix also differ between stages, which can bias a pooled comparison.