Building an Experimentation Platform
Running one A/B test needs a notebook and a script. Running two hundred a year needs infrastructure, because at that scale the failure modes are no longer statistical. Assignments drift, users see different variants on refresh, sample sizes go unchecked, three teams test the same surface simultaneously, and someone ships a decision on a result that was peeked at for three weeks. An experimentation platform exists to make those failures impossible rather than merely unlikely, and this lesson walks the four subsystems that any such platform needs.
The four jobs a platform must do
Before choosing tools, separate the responsibilities. Assignment decides which variant a user sees, and it must be deterministic so that a page reload does not shuffle the experience. Analysis decides whether the difference is real, which means power calculations, the right estimator, and guards against peeking. Delivery controls how much traffic reaches the treatment, from a one percent canary to a full ramp, with the ability to reverse instantly. Governance records what was run, what was decided, and why, so that the same question is not re-litigated every quarter.
Most teams build analysis first because it feels like the hard part. It is not. Assignment is where platforms quietly fail, because a non-deterministic scheme corrupts every downstream number while still producing plausible-looking results. Get assignment stable, then layer analysis, delivery, and governance on top.
Assignment: deterministic hashing instead of coin flips
The standard technique is to hash a stable identifier together with the flag name, take the hash modulo one hundred, and walk a cumulative weight table. Because the same inputs always produce the same bucket, a user keeps their variant across sessions, devices are not reshuffled mid-journey, and results remain reproducible when you re-analyse a month later. Including the flag name in the hash is what keeps buckets independent between experiments, so two flags do not accidentally correlate.
import hashlib
def bucket_for(key: str, flag_name: str) -> int:
"""Stable bucket in [0, 100) for a user and flag."""
digest = hashlib.md5(f"{flag_name}:{key}".encode()).hexdigest()
return int(digest, 16) % 100
def assign_variant(flag_name: str, user_id: str, weights: dict) -> str:
"""Walk a cumulative weight table of percentages summing to 100."""
bucket = bucket_for(user_id, flag_name)
cumulative = 0
for variant, weight in weights.items():
cumulative += weight
if bucket < cumulative:
return variant
return next(reversed(weights))
weights = {"control": 50, "treatment": 50}
print(assign_variant("new_checkout", "user_123", weights))
print(assign_variant("new_checkout", "user_123", weights))
print(assign_variant("search_ranking_v2", "user_123", weights))
Two calls with the same inputs return the same variant, which is the property that makes everything else trustworthy. Validate your weights at configuration time, since a table summing to ninety-eight silently starves the last bucket.
Feature flags, targeting rules, and kill switches
Flags are the delivery mechanism, and a good flag service separates targeting from weighting. Targeting decides whether a user is eligible at all, using conditions on attributes such as country, plan tier, or app version. Weighting decides which variant an eligible user receives. Keeping these apart lets you restrict a rollout to internal accounts while still splitting them fifty-fifty, and it keeps rule evaluation from contaminating the bucketing hash.
The kill switch deserves its own field rather than a check you remember to run during an incident. When error rates spike at three in the morning, the responder needs one control that forces every user to the control variant regardless of targeting, and it should take effect on the next request without a deploy.
import hashlib
from dataclasses import dataclass, field
from typing import List
@dataclass
class Flag:
name: str
enabled: bool = True
kill_switch: bool = False
weights: dict = field(default_factory=lambda: {"control": 100})
rules: List[dict] = field(default_factory=list)
def _bucket(self, user_id: str) -> int:
digest = hashlib.md5(f"{self.name}:{user_id}".encode()).hexdigest()
return int(digest, 16) % 100
def _eligible(self, user_id: str, context: dict) -> bool:
for rule in self.rules:
if all(self._matches(context, c) for c in rule.get("conditions", [])):
return True
return not self.rules
@staticmethod
def _matches(context: dict, condition: dict) -> bool:
value = context.get(condition["field"])
op = condition["operator"]
if op == "equals":
return value == condition["value"]
if op == "in":
return value in condition["value"]
if op == "gte":
return value is not None and value >= condition["value"]
return False
def variant_for(self, user_id: str, context: dict = None) -> str:
if not self.enabled or self.kill_switch or not self._eligible(user_id, context or {}):
return "control"
bucket = self._bucket(user_id)
cumulative = 0
for variant, weight in self.weights.items():
cumulative += weight
if bucket < cumulative:
return variant
return "control"
flag = Flag(
name="new_checkout",
weights={"control": 50, "treatment": 50},
rules=[{"conditions": [
{"field": "country", "operator": "in", "value": ["US", "CA"]},
{"field": "plan", "operator": "equals", "value": "pro"},
]}],
)
print(flag.variant_for("user_123", {"country": "US", "plan": "pro"}))
print(flag.variant_for("user_123", {"country": "DE", "plan": "pro"}))
Staged rollouts and automatic rollback
A ramp converts an experiment from a binary decision into a sequence of cheap ones. Start with one percent of traffic long enough to observe error rate and latency, widen to ten percent for a full day, then to fifty percent, and only then to everyone. Each stage has explicit thresholds, and breaching one triggers a rollback without human debate. The threshold should be set in advance, because a threshold invented after the metric drops is just a rationalisation.
from dataclasses import dataclass, field
from typing import Callable, Dict, List
@dataclass
class Stage:
name: str
traffic_pct: float
thresholds: Dict[str, float]
hours: float
@dataclass
class Rollout:
stages: List[Stage]
checks: List[Callable[[dict], bool]] = field(default_factory=list)
index: int = 0
def healthy(self, metrics: dict) -> bool:
stage = self.stages[self.index]
if any(metrics.get(k, 0) > v for k, v in stage.thresholds.items()):
return False
return all(check(metrics) for check in self.checks)
def advance(self, metrics: dict) -> str:
if not self.healthy(metrics):
self.index = max(0, self.index - 1)
return f"rollback to {self.stages[self.index].name}"
if self.index < len(self.stages) - 1:
self.index += 1
return f"advance to {self.stages[self.index].name}"
return "complete"
rollout = Rollout(
stages=[
Stage("canary", 1, {"error_rate": 0.01, "p99_ms": 300}, 2),
Stage("early", 10, {"error_rate": 0.005, "p99_ms": 200}, 24),
Stage("ramp", 50, {"error_rate": 0.005, "p99_ms": 200}, 48),
Stage("full", 100, {"error_rate": 0.005, "p99_ms": 200}, 0),
],
checks=[lambda m: m.get("conversion_lift", 0) > -0.05],
)
print(rollout.advance({"error_rate": 0.002, "p99_ms": 180, "conversion_lift": 0.01}))
print(rollout.advance({"error_rate": 0.02, "p99_ms": 400, "conversion_lift": 0.01}))
| Stage | Traffic | Minimum dwell | Primary gate | Rollback trigger |
|---|---|---|---|---|
| Canary | 1 percent | 2 hours | Error rate and latency | Error rate above 1 percent |
| Early | 10 percent | 1 full day cycle | Guardrail metrics stable | Any guardrail breach |
| Ramp | 50 percent | 2 days | Primary metric direction holds | Sustained negative lift |
| Full | 100 percent | Ongoing | Post-launch monitoring | Alert on regression |
The statistical engine
With assignment and delivery solved, analysis becomes configuration. The engine should compute required sample size from a baseline rate and a minimum detectable effect before the test starts, refuse to evaluate until the planned duration has elapsed or a sequential boundary is crossed, and produce a confidence interval rather than a bare decision. Supporting both frequentist and Bayesian readouts matters less than being consistent: teams that switch frameworks between experiments inevitably compare numbers that are not comparable.
Peeking is the classic failure, and it is an infrastructure problem rather than a willpower problem. If the platform exposes a p-value every day, someone will act on it. Spending the alpha budget across planned looks, or using a sequential test with proper boundaries, lets stakeholders watch progress without inflating the false positive rate.
Governance: stopping bad decisions before they ship
Governance is the pre-review that runs before a human ever sees a result. It checks that the sample size target was met, that the run lasted long enough to cover a weekly cycle, that no sample ratio mismatch appeared, that guardrails stayed green, and that the analysis matches the plan registered when the experiment started. Passing every check produces a recommendation; failing any produces a list of problems instead of a chart.
The second half is the decision record: ship, iterate, or kill, with a named reviewer and a written rationale. Six months later, when someone asks why the old checkout is still in place, that record is the difference between an answer and an argument. It also feeds a registry that lets teams search for prior tests on the same surface, which is the cheapest form of organisational memory available.
from datetime import datetime
def pre_review(results: dict, plan: dict) -> dict:
"""Automated gate before a human reads the results."""
checks = {
"sample_size": results["n_total"] >= plan["min_sample"],
"duration": results["days"] >= plan["min_days"],
"srm": results["srm_p"] > 0.001,
"guardrails": all(
results.get(name, 0) >= floor
for name, floor in plan["guardrails"].items()
),
"planned_metric": results["primary_p"] < plan["alpha"],
}
ready = all(checks.values())
return {
"checks": checks,
"recommendation": "ready_for_review" if ready else "needs_attention",
"failing": [name for name, ok in checks.items() if not ok],
}
decision = {
"experiment": "checkout_v3",
"verdict": "ship",
"reviewer": "growth-lead",
"reason": "Primary metric up 4.1 percent, guardrails green, SRM clean",
"timestamp": "2026-04-18T10:12:00Z",
}
print(pre_review(
{"n_total": 42000, "days": 14, "srm_p": 0.42, "primary_p": 0.01,
"conversion_lift": 0.041, "error_rate": 0.001},
{"min_sample": 40000, "min_days": 14, "alpha": 0.05,
"guardrails": {"conversion_lift": -0.001, "error_rate": 0.0}},
))
print(decision["verdict"], "-", decision["reason"])
Operating the platform in production
Two operational realities separate a demo from a system. The first is contention: overlapping experiments on the same metric need mutual exclusion or a layered assignment scheme, otherwise interaction effects get attributed to whichever test ran second. The second is latency: variant resolution sits on the request path, so the flag lookup needs a local cache with a short time to live, because a platform that adds eighty milliseconds to a page load will be bypassed by engineers under deadline pressure.
Treat the platform as a product with its own service level objectives. Track assignment coverage, flag evaluation latency, and the percentage of experiments that completed with all governance checks green. That last metric is the honest measure of whether the system is doing its job, and it is the number to bring to leadership when asking for investment.
Common Mistakes
Assigning variants with a random number generator evaluated on each request
Fix: Bucket from a hash of the user identifier and flag name so assignment stays stable across sessions and reproducible in analysis.
Reading a p-value daily and stopping the test as soon as it crosses the threshold
Fix: Pre-register the duration or use a sequential boundary that spends the alpha budget across planned looks.
Shipping on a primary metric while guardrails quietly regress
Fix: Run an automated pre-review that blocks any result with a guardrail breach or a sample ratio mismatch.
Best Practices
- Validate that weight tables sum to 100 before any flag is enabled
- Include the flag name in the hash so buckets are independent between experiments
- Set rollout thresholds in advance and let the platform reverse traffic automatically
- Record every decision with a named reviewer and written rationale
- Monitor assignment coverage and flag evaluation latency as first-class service metrics
Key Takeaways
- Deterministic hashing is the foundation; everything downstream depends on stable buckets
- Separate targeting rules from variant weighting to keep evaluation simple
- Staged rollouts with pre-set thresholds turn incidents into non-events
- The statistical engine must prevent peeking by design, not by policy
- Governance pre-reviews and a decision registry are what make experiments cumulative