Experimentation Platforms and Infrastructure Questions
Infrastructure for A/B testing and experimentation: assignment/bucketing, metric pipelines for experiments, guardrail and variance-reduction plumbing, and experiment result storage. Covers building the platform that powers trustworthy online experiments at scale. Distinct from the statistics of experiment analysis.
Given exposures, events, and users tables, describe how you would compute normalized lift and a bootstrap confidence interval for the metric purchase_value per variant over a 14-day window. Outline the SQL for the aggregation step and sketch the Python for the bootstrap, including how you handle user-level aggregation and stratified resampling.
Sample Answer
Direct answer
Aggregate purchase_value per user per variant in SQL first (so each user contributes exactly one row), then bootstrap by resampling users WITH replacement independently within each arm, recomputing the relative lift on each resample, and taking the 2.5th and 97.5th percentiles of the resulting distribution as the 95% confidence interval; user-level resampling, not event-level, is what correctly respects the actual unit of randomization.
Structured elaboration
SQL aggregation sketch:
SELECT e.variant, e.user_id,
COALESCE(SUM(CASE WHEN ev.event_type='purchase'
AND ev.occurred_at >= e.assigned_at
AND ev.occurred_at <= e.assigned_at + INTERVAL '14 days'
THEN ev.value ELSE 0 END), 0) AS purchase_value
FROM exposures e LEFT JOIN events ev ON ev.user_id = e.user_id
GROUP BY e.variant, e.user_id;
Both bounds of the attribution window matter: the upper bound (assigned_at + 14 days) caps how long after assignment a purchase still counts, but the lower bound (ev.occurred_at >= e.assigned_at) is just as necessary, without it the join would sum a user's entire purchase history, including purchases made long before the experiment even existed, into purchase_value, since the CASE condition only ever checked the upper bound. That silently inflates purchase_value for any user with pre-experiment purchase history and corrupts the metric everything downstream depends on.
Python bootstrap sketch (executed and verified):
def bootstrap_lift_ci(control_values, treatment_values, n_boot=2000, seed=42):
rng = random.Random(seed)
n_c, n_t = len(control_values), len(treatment_values)
lifts = []
for _ in range(n_boot):
c_sample = [control_values[rng.randrange(n_c)] for _ in range(n_c)]
t_sample = [treatment_values[rng.randrange(n_t)] for _ in range(n_t)]
c_mean, t_mean = sum(c_sample)/n_c, sum(t_sample)/n_t
if c_mean != 0:
lifts.append((t_mean - c_mean) / c_mean)
lifts.sort()
lo, hi = lifts[int(0.025*len(lifts))], lifts[int(0.975*len(lifts))]
point = (sum(treatment_values)/n_t - sum(control_values)/n_c) / (sum(control_values)/n_c)
return point, lo, hi
User-level aggregation matters because the randomization unit was the USER, not the event; resampling individual purchase events would treat a high-frequency purchaser's many events as many independent observations, when they're really one randomized unit. Stratified resampling (resampling within each variant independently, as done here) preserves each arm's own sample size in every bootstrap draw, keeping the comparison apples-to-apples.
Worked example (executed)
On a synthetic dataset with a known true +20% lift (control drawn from a distribution with mean 20, treatment from one with mean 24, 3,000 users per arm), the bootstrap produced a point estimate of approximately 0.19 with a 95% CI of roughly [0.17, 0.22], correctly containing the true 0.20 lift. On a null case (both arms drawn from the identical distribution), the CI straddled zero (approximately [-0.02, 0.02]), correctly showing no significant difference.
Trade-offs and pitfalls
Bootstrapping at the event level instead of the user level is the most common version of this mistake, and it understates the true variance because it implicitly treats a user's multiple purchases as independent randomized units when they aren't. A second common mistake, seen in an earlier draft of the SQL above, is an attribution window that only enforces its upper bound and forgets the lower one, silently pulling in a user's entire purchase history rather than just the post-assignment window; always write and test both bounds explicitly. The other pitfall is a small sample size making the percentile bootstrap itself noisy (with very few users per arm, 2,000 resamples of a tiny population doesn't manufacture information that isn't there); in that regime a parametric or bias-corrected bootstrap method is usually more appropriate than the plain percentile method used here.
Design experiment infrastructure for validating a new ML model in production: shadow testing, a canary model route, holdout groups, model versioning, and feature-store dependencies. How does rollout gating differ when the metrics you're gating on are model-specific (inference latency, fairness checks) rather than generic product metrics, and what does rollback look like for a model regression?
Sample Answer
Direct answer
Validating a new ML model online needs infrastructure beyond a standard A/B test: shadow testing (running the new model's predictions alongside production without acting on them, to catch problems before any user is affected), canary model routes (a small, controlled slice of real traffic on the new model), holdout groups (a slice permanently withheld from any model update, to measure drift in the underlying population over time), model versioning tied to every prediction logged, and rollback gated on model-specific metrics like inference latency and fairness checks, not just the product's usual business metrics.
Structured elaboration
- Shadow testing: the new model runs on live traffic in parallel with the production model, its predictions logged but never shown to users; this catches gross failures (crashes, wildly wrong predictions, latency blowups) with zero user-facing risk, before the model is trusted enough to touch a canary.
- Canary model routes: once shadow testing passes, route a small percentage of real traffic to the new model's actual predictions, gated the same way a code canary is, with automated rollback if model-specific guardrails breach.
- Holdout groups: a slice of traffic permanently kept on an OLDER, frozen model version (not necessarily the immediately-prior one) gives a stable baseline to detect population-level drift over time, distinct from the canary's job of validating a specific new version.
- Model versioning: every prediction logged with the exact model version that produced it, which is what makes a later question like "was this specific bad recommendation from the new model or the old one" answerable at all.
- Feature-store dependencies: the platform needs to track which feature-store version and feature definitions a given model version was trained and served against, since a feature-definition change (even without touching the model itself) can silently degrade predictions if serving-time features drift from what the model was trained on.
- Model-specific rollout gating: inference latency and fairness checks (disparate performance across user segments) are guardrails a standard product experiment wouldn't naturally include, and both need to gate rollout the same way a business-metric guardrail does.
- Rollback for model regressions: reverting to a prior model version needs to be as fast and as automatable as reverting a code deploy, since a model regression (systematically worse recommendations for a segment) can be just as costly as a code bug.
- Champion-challenger automation: once a canary is trusted, the platform can automate the promote-or-kill decision itself (a "champion-challenger" pattern), continuously testing a challenger model against the current champion and auto-promoting a winner once it clears both the statistical bar and every guardrail, which matters specifically under non-stationarity, where a model that was the best choice last month may not be today.
- Handling noisy online metrics for personalization: personalization rollouts often show noisy primary metrics, so the platform should let a team define a minimum-detectable-effect target and pay attention to whether metrics move consistently across segments rather than trusting one noisy aggregate number; two model versions that look similar in aggregate can still diverge sharply for a specific segment, which is exactly what the fairness and segment-level guardrails above are built to catch.
- Feedback loops and population shift: a model that influences what users see also influences what data gets collected next (a recommendation model shapes future training data), so continuous evaluation needs to watch for the model's own predictions drifting the underlying population it's being measured against, not just for the model's accuracy degrading in isolation.
- Comparing two model versions specifically: the simplest case of this infrastructure, A/B testing exactly two model versions with deterministic bucketing and an offline analysis pipeline reading the same exposure and outcome events described elsewhere, is the same infrastructure at smaller scope, not a separate system.
Worked example
A new recommendation model passes shadow testing cleanly (predictions look reasonable, latency is fine) and is canaried to 5% of traffic. A fairness guardrail then flags materially worse recommendation quality for a specific user segment that wasn't well represented in the new model's training data, a regression the shadow test's aggregate-latency-and-crash checks would never have caught, since it required actually observing engagement outcomes for that segment specifically once the canary was live.
Trade-offs and pitfalls
Shadow testing catches failures cheaply but can't catch anything that depends on the model actually influencing user behavior (since shadow predictions are never shown to anyone), which is exactly why a canary stage is still needed even after a clean shadow run. The other common mistake is gating rollout only on the usual business metrics and skipping model-specific checks like fairness across segments, which can leave a real regression invisible in the aggregate metric while it's actively harming a specific, smaller population.
Propose an automated guardrail system that flags harmful regressions shortly after an experiment launches. What statistical tests, thresholds, and alert tiers would you use, and when would the system take automated action (pausing the ramp or rolling traffic back) versus just paging a human?
Sample Answer
Direct answer
An automated guardrail system needs a defined set of guardrail metrics with pre-agreed statistical tests and thresholds, a tiered alerting scheme (a small dip pages a human, a large or fast-moving dip triggers automatic action), and an explicit distinction between pausing the ramp (stop exposing new users, keep existing ones as-is) and rolling back (revert everyone), because those are different remediations for different severities.
Structured elaboration
- Statistical tests: a one-sided test against a pre-agreed harm threshold (not just "any statistically significant change") is usually the right framing for a guardrail, since the goal is catching real harm fast, not detecting any change in either direction with maximum power.
- Thresholds and tiers: a common design is two tiers, a "watch" threshold (a smaller, statistically detected regression) that pages the on-call owner for a human decision, and a "stop" threshold (a larger or faster regression, or a regression combined with high statistical confidence) that triggers automated action without waiting for a human.
- Automated protections: pausing the ramp (freezing the traffic percentage, or reverting new users to control while leaving already-exposed users in place) is the lower-risk default action; a full rollback (reverting everyone immediately) is reserved for guardrails severe enough that leaving anyone exposed even briefly is unacceptable, like a payment-failure spike.
- Avoiding false alarms: because this system runs continuously across every guardrail metric on every experiment, it needs its own multiple-testing discipline (checking dozens of metrics many times a day inflates the false-alarm rate) and typically a minimum-duration or minimum-sample-size floor before an alert can fire at all, so early noise in a tiny sample doesn't trigger a spurious automatic rollback.
Worked example
A login-flow experiment is being monitored for guardrail metrics including a technical one (login success rate) and a business one (session-start rate). Login success rate drops sharply and quickly past the "stop" threshold within the first hour of a ramp. The system automatically pauses new exposure and pages the on-call engineer, rather than waiting for a scheduled daily report, because an hour of a login-flow regression at scale is costly enough that the automated action has to happen faster than any human review cycle could. The response here is deliberately a roll-FORWARD (pause new exposure, keep serving the same code path to already-affected users while a fix ships) rather than a full rollback, since the team judges that a fast fix is available and re-exposing the already-affected cohort to yet another code change would add more risk than it removes; a different guardrail (a payment-failure spike, say) would instead call for an immediate full rollback, which is exactly why the decision between rolling forward and rolling back has to be a judgment call encoded per guardrail severity, not a single fixed response for every breach.
Trade-offs and pitfalls
Setting the automatic-action threshold too aggressive causes false rollbacks on ordinary noise, which erodes trust in the system and tempts teams to disable it; setting it too conservative means real harm runs for longer before anything happens. The typical resolution is to start conservative (a genuinely severe, high-confidence threshold for full automatic rollback) while using the "watch" tier liberally, since a false page to a human is a much cheaper mistake than a false automatic rollback that a team then has to understand and re-enable.
Implement a simulator (pseudocode or Python) that models user assignment across multiple overlapping experiments and measures the bias this introduces into a treatment-effect estimate when the assignments are not independent. Describe the simulation parameters you would vary and what output would tell you the bias is large enough to worry about.
Sample Answer
Direct answer
Simulate two overlapping experiments A and B where every user is independently assigned a treatment indicator for each, generate an outcome as a function of both treatments plus an interaction term plus noise, then measure the bias introduced when assignment is NOT actually independent (for example, a bucketing bug that correlates the two assignments) by comparing the naive difference-in-means estimate of A's effect under independent versus correlated assignment.
Structured elaboration
def simulate_overlapping_experiments(n_users, true_effect_A, true_effect_B,
interaction, independent_assignment, seed):
rng = random.Random(seed)
baseline = 10.0
rows = []
for i in range(n_users):
treat_A = rng.random() < 0.5
if independent_assignment:
treat_B = rng.random() < 0.5
else:
# correlated: a bucketing-bug shape, B mostly copies A's assignment
treat_B = treat_A if rng.random() < 0.9 else (rng.random() < 0.5)
y = (baseline + (true_effect_A if treat_A else 0) + (true_effect_B if treat_B else 0)
+ (interaction if (treat_A and treat_B) else 0) + rng.gauss(0, 5))
rows.append((treat_A, treat_B, y))
treat_vals = [y for (a, b, y) in rows if a]
control_vals = [y for (a, b, y) in rows if not a]
return sum(treat_vals)/len(treat_vals) - sum(control_vals)/len(control_vals)
Simulation parameters to vary: the correlation strength between the two assignments (from fully independent to fully correlated), the interaction term's magnitude (a larger interaction amplifies the bias from non-independence), and the individual effect sizes of A and B. The output that tells you the bias is large enough to worry about is simply the difference between the naive estimate under correlated assignment and the same estimate under independent assignment; a difference that's small relative to the true effect size of A is probably tolerable noise, while one that's a large fraction of (or larger than) the true effect is a real, actionable bias.
Worked example (executed and derived analytically)
With true_effect_A = 2.0, true_effect_B = 1.0, interaction = 3.0: under independent assignment, the simulated naive effect of A converged to 3.502, matching the analytical prediction of effect_A + interaction times P(B=1) = 2.0 + 3.0 times 0.5 = 3.5. Under a 90%-correlated bucketing-bug assignment, the simulated estimate converged to 5.754, matching the analytical prediction (using P(B=1|A=1)=0.95 and P(B=1|A=0)=0.05) of 15.80 minus 10.05 = 5.75. The bias introduced by non-independent assignment here is 2.25, more than two-thirds of A's true effect size, which is large enough that any real experimentation platform should treat this as a serious problem, not a rounding error.
Trade-offs and pitfalls
The most useful adversarial case to construct is exactly this one, deliberately correlating the two assignments to mimic a realistic bucketing bug (shared low-entropy hash inputs across experiments), rather than only testing with fully independent assignment, which would never reveal the bias this simulator exists to quantify. A subtlety worth flagging explicitly: even under fully independent assignment, A's naive effect estimate is NOT simply true_effect_A, it legitimately includes A's average interaction with B (since B is independent of A but not absent), which is expected and correct, not itself a bias; the actual bias is specifically the ADDITIONAL shift caused by non-independence, which is why comparing the correlated case against the independent case, not against the bare true_effect_A, is the right measurement.
You observe a persistent Sample Ratio Mismatch across several experiments. Walk through the debugging steps you would take, including how you would use logs, request replays, SDK version breakdowns, cookie or domain changes, and recent deployment timelines to find the root cause.
Sample Answer
Direct answer
Start from logs, request replays, SDK version breakdowns, cookie or domain changes, and the deployment timeline, in that order of cheapest-to-check first, because a persistent SRM is almost always a symptom of one specific upstream event, and the fastest way to find it is to look for what changed around when the mismatch started, not to re-derive the assignment logic from scratch.
Structured elaboration
- Confirm the mismatch is real and persistent, not a one-off blip: pull the daily (not just cumulative) split to see whether it's been off since day one (suggests a config or logic bug) or started partway through (suggests something changed mid-experiment, like a deploy or a cookie policy change).
- Break down by SDK version: if one client version shows a much worse split than others, the bug is very likely in how that specific client version fires (or fails to fire) the exposure event, not in the assignment logic itself.
- Break down by domain, region, or platform: a mismatch concentrated in one geography or platform points at something environment-specific, like a CDN or redirect that behaves differently there, or a bot-filtering rule that isn't applied evenly across variants.
- Check cookie behavior specifically: if assignment is pinned via a first-party cookie, a recent change to cookie domain scoping, SameSite policy, expiry, or a browser's third-party-cookie blocking rollout can cause a user's assignment to silently reset or fail to persist across requests, more often for one arm than the other (for example, a variant that redirects through a different subdomain, so its cookie doesn't get set or read the same way as control's). This is a distinct root cause from a geographic or platform effect and needs its own check: compare the cookie-write success rate and cookie-read-back rate by variant, not just by region.
- Check the deployment timeline: line up the date the mismatch started against recent deploys of the assignment service, the client SDK, cookie/consent-banner logic, or anything else on the request path; a persistent SRM that starts precisely on a deploy date is close to a smoking gun.
- Replay a sample of affected requests: manually trace a handful of individual user journeys around the time of the issue to see, concretely, where an event is missing, a cookie failed to persist, or an assignment call behaved unexpectedly, which usually confirms or rules out whatever the aggregate breakdowns suggested.
Worked example
An SRM alert has been firing for a week on an experiment showing 48% control versus 52% treatment. Breaking down by SDK version shows no anomaly, but comparing cookie-read-back rates by variant shows the treatment arm (which renders through a slightly different page template) fails to read back its assignment cookie 6% more often than control, because that template loads a script that runs before the cookie consent banner resolves. Some of those users get silently re-randomized on their next visit, and re-randomization isn't uniform across arms because it correlates with how quickly each template's page finishes loading. The fix is in the cookie-write timing on that template, not in the assignment service's hashing logic at all.
Trade-offs and pitfalls
The most common mistake is jumping straight to "the assignment logic must be broken" and re-auditing the hashing function, which is rarely where the bug actually lives, rather than first slicing the data by version, region, cookie behavior, and time to let the data point at the likely cause. The other pitfall is stopping the investigation once a plausible correlated factor is found (say, "it's worse on iOS" or "it's worse on one template") without confirming a causal mechanism, since a correlated factor can itself be a downstream symptom of the real root cause (like the cookie-timing bug above) rather than the cause itself.
Unlock Full Question Bank
Get access to all Experimentation Platforms and Infrastructure interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.