Sub topic 9
Choosing the Randomization Unit and Keeping Assignment Sticky
This chapter assumes you can read short Python and YAML snippets. It also assumes you know what a weighted traffic split is, as covered in the traffic routing chapter, and that you understand proportions and averages.
A weighted route such as 95/5 decides where each request goes. It does not decide who sees the candidate model. Without that second decision, one person can see the stable model on one click and the candidate on the next. That makes behavior confusing and the data hard to interpret.
What a randomization unit is
The randomization unit is the entity you assign to a variant. Every request, event, or outcome that belongs to the same unit gets the same variant. Examples are a request, a session, a user, a device, or an organization.
The unit decides three things:
- Consistency. What the person or system experiences over time.
- Independence. Whether two observations can be treated as separate samples in a statistical test.
- Analysis. Which rows you aggregate, and how many independent samples you really have.
Common units and their trade-offs
| Unit | Sticky for the user? | Typical use | Main risk |
|---|---|---|---|
| Request | No | Stateless scoring such as fraud checks, where no one sees the model | The same user is exposed to both variants, and repeated requests are correlated |
| Session | Within one visit | Short, self-contained flows | Users return and flip variants, which hurts learning effects |
| User ID | Across sessions and devices (if logged in) | Recommendations, ranking, personalization | Anonymous traffic has no ID |
| Device or cookie ID | Per device | Anonymous traffic | Cleared cookies and multiple devices reassign the same person |
| Account or organization | All members together | B2B products, shared state | Few units, so low statistical power |
| Region or cluster | All traffic in a place | Marketplaces and network effects | Very few units, and regions differ in ways you cannot control |
For a canary release, request-level assignment is often acceptable, because you are checking safety and not measuring user behavior. For an A/B test against a business outcome, you almost always need a unit that stays fixed for the whole experiment.
Match the unit to the analysis
Pick the coarsest unit at which interference can occur, and analyze at that same level.
Suppose you assign by request but measure purchases per user. A user with ten requests now contributes to both arms, and the two arms are no longer independent groups of users. The reverse mistake is also common. If you assign by organization and then run a z-test over individual users, the users inside one organization are correlated. Your effective sample size is closer to the number of organizations, so the p-value is too optimistic.
If the assignment unit is coarser than the analysis unit, do one of two things. Aggregate to the assignment unit, for example the mean conversion per organization, and test on those aggregates. Or use a method that accounts for clustering, such as cluster-robust standard errors.
Deterministic assignment by hashing
Storing an assignment table works, but it needs a database lookup on the hot path and a policy for new units. Hashing avoids both. Hash the unit ID together with an experiment-specific salt, map the result to a fixed number of buckets, and compare the bucket with a threshold.
import hashlib
BUCKETS = 10_000
def bucket(unit_id: str, salt: str, buckets: int = BUCKETS) -> int:
digest = hashlib.sha256(f"{salt}:{unit_id}".encode()).hexdigest()
return int(digest, 16) % buckets
def choose_variant(unit_id: str, salt: str, candidate_percent: float) -> str:
threshold = round(candidate_percent * 100) # percent of 10000 buckets
return "candidate" if bucket(unit_id, salt) < threshold else "stable"
users = [f"user-{i}" for i in range(20000)]
salt = "ranker-v2-exp1"
at_5 = {u for u in users if choose_variant(u, salt, 5) == "candidate"}
at_20 = {u for u in users if choose_variant(u, salt, 20) == "candidate"}
print(len(at_5) / len(users), len(at_20) / len(users))
print(at_5 <= at_20)The output shows two shares close to 0.05 and 0.20. The last line prints True, which is the next property.
Three properties make this approach work:
- Deterministic. The same unit and salt always give the same bucket, on any server, with no shared state.
- Monotonic ramp-up. Raising the threshold from 5% to 20% only adds units to the candidate group. Everyone who already saw the candidate keeps seeing it. This is why staged canary releases do not flip users back and forth.
- Approximately uniform. A cryptographic hash spreads IDs evenly, so group sizes track the requested percentage.
Use a stable hash such as SHA-256 or MurmurHash. Do not use Python's built-in hash() for strings. It is randomized per process, so two replicas would disagree about the same user.
Salts keep experiments independent
If every experiment hashed only the user ID, the same users would land in the candidate group of every experiment. Effects from different experiments would be confounded, and the same 5% of users would absorb all the risk.
A per-experiment salt makes the bucket for each experiment effectively independent of the others. Treat the salt as part of the experiment's identity:
- Choose it once, before launch, and store it with the experiment configuration.
- Never change it mid-experiment. Changing the salt reshuffles everyone.
- Use a new salt when you want a fresh randomization, such as a re-run after a bug fix, so the old assignment does not carry over bias.
Carrying the assignment through the serving stack
Make the assignment once, as early as possible, and pass the result downstream as a header or field. Do not recompute it at every service. Istio's weighted routes pick a destination per request, so they are not sticky. To get stickiness, have the gateway or application compute the variant and set a header. The mesh then routes on that header.
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
name: fraud-model
spec:
hosts:
- fraud-model
http:
- match:
- headers:
x-model-variant:
exact: candidate
route:
- destination:
host: fraud-model
subset: candidate
- route:
- destination:
host: fraud-model
subset: stableLog the variant, the unit ID, and the salt (or experiment ID) with every prediction. The analysis needs them, and they let you check later that assignment behaved as designed.
Choosing a unit step by step
Failure modes
- Identity changes. A visitor browses anonymously (assigned by device ID), then logs in (assigned by user ID). The two hashes differ, so the person may switch variants. Decide which ID is authoritative. If the identity switch is common, analyze only units whose ID was stable, or assign everyone by device ID.
- Cleared cookies and multiple devices. One person becomes several units. This dilutes the effect and can expose the same person to both models. It is hard to remove fully for anonymous traffic.
- Hashing a mutable attribute. If you hash an email address or a plan name that can change, the unit moves between arms. Hash a permanent identifier.
- Bucket count mismatch. Two services using different bucket counts or hash functions will disagree. Share one library or one assignment service.
- Interference. If the candidate changes what other users see, for example a ranking model that changes prices in a shared marketplace, per-user randomization contaminates the control group. Move to a coarser unit, such as a region, or a time-sliced design.
- Unequal unit sizes. With organization-level assignment, one large organization can dominate an arm. Check arm sizes in both units and in traffic volume.
Independence between assignment and traffic
Assignment is only random if it does not depend on user characteristics. If you assign by a hash of the ID, that holds. If you assign "the first 5% of users who arrive", or by region, or by app version, the groups differ in ways unrelated to your model. Hash-based assignment on a stable, non-informative ID is the default for good reason.
One more detail: sticky assignment guards against flipping, but it does not guard against stale state. If a user's stored features were computed by the stable model, a candidate-assigned user may behave oddly right after the switch. Where this matters, exclude a short warm-up window, or analyze only post-exposure behavior.
Exercise
A team tests a new recommender by hashing the user ID with the salt "rec-v3". At 10% candidate traffic, the metrics look good, so they ramp to 50%. They also change the salt to "rec-v3-ramp" "to keep things clean". What goes wrong, and what should they do instead?
Show answer
Changing the salt reassigns users. Many users who saw the candidate at 10% are now in the stable group, and many who saw stable are now in the candidate group. Each user's behavior is mixed across arms, so their earlier outcomes cannot be attributed to one variant, and users flip models mid-experience. Keep the original salt and raise only the threshold from 10% to 50%. Because the threshold increase is monotonic, everyone who already saw the candidate keeps seeing it.
Exercise
You assign a B2B analytics product's model change by organization (40 organizations per arm) but run a two-proportion z-test over all individual users. Why is the result unreliable, and what is one fix?
Show answer
Users in the same organization are correlated, so the 40 organizations per arm, not the user count, set the real sample size. The z-test treats every user as independent, which makes the standard error too small and the p-value too optimistic. One fix is to compute the metric per organization and test on those 40 + 40 aggregates. Another is to use cluster-robust standard errors.