Audit a Flaky Free-Trial Rollout Function for Experiment Safety
Statistics & ExperimentsModel answerLast updated
Find at least eight correctness and reliability bugs in a Python function that randomizes users into a free-trial test, then redesign it so the experiment and billing data stay trustworthy.
A growth team is testing a one-month free trial. The function below decides which arm a user belongs to, records that the user was exposed, and calls the billing service to begin the trial for treatment users.
import random, datetime, requests
def maybe_start_trial(user_id):
if random.random() < 0.5:
variant = 'trial'
else:
variant = 'control'
now = datetime.datetime.now()
exposed_at = now
log_exposure(user_id, exposed_at, variant)
if variant == 'trial':
r = requests.post('https://billing/start_trial', json={'user_id': user_id})
if r.status_code == 200:
log_trial(user_id, now)
(Assume the indentation was lost when the code was pasted, and that the logic is what matters.)
Your tasks
- Identify at least eight distinct problems that could corrupt the experiment or the underlying data. Consider assignment stability, bias, time zones, idempotency, retries, race conditions, privacy and observability.
- For each problem, describe the failure mode and its effect on experiment metrics.
- Propose concrete fixes. Examples: stable hash-based bucketing with per-experiment salts, UTC timestamps, exactly-once exposure logging, an outbox or queue, idempotency keys, transactional writes, circuit breakers, exponential backoff, and eligibility checks.
- Sketch a hardened version (pseudocode or high-level design) that is safe for production use and for experiment analysis.
Hints
Hint 1
Walk the function line by line and ask: what happens if this runs twice for the same user, runs concurrently, or crashes halfway through?
Hint 2
Separate the three responsibilities: deciding the arm, recording exposure, and causing a billing side effect. Each needs a different guarantee (determinism, uniqueness, idempotency).
Hint 3
Think about how each bug would show up in analysis: diluted effect, sample-ratio mismatch, non-compliance in the treatment arm, or misaligned cohort dates.
Hint 4
For the fix, look at the transactional outbox pattern: write assignment, exposure and a pending job atomically, then let a worker call billing with an idempotency key.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Overview
The function bundles three concerns that need different guarantees:
- Assignment must be deterministic, sticky and reproducible.
- Exposure logging must occur once per user per experiment, at the moment the offer is really shown.
- The billing side effect must be idempotent, retried safely, and consistent with the logs.
Everything currently runs inline with local time and a fire-and-forget network call, so any retry, crash or concurrent request can silently corrupt the results.
Problems, failure modes, and fixes
1. Non-sticky assignment. random.random() runs on every call, so one user can flip between arms. Users appear in both arms, contamination pushes the measured effect toward zero, and the trial-arm population is polluted. Fix: hash bucketing, sha256(exp_id:salt:user_id) mod 10000, plus a persisted first assignment.
2. Unversioned, unauditable randomness. The split cannot be recomputed or checked, and the hard-coded 0.5 lives in code. Reusing one split across experiments correlates buckets and creates carryover. Fix: a per-experiment salt and the allocation held in versioned config.
3. No eligibility check. Current subscribers, people who already had a trial, employees, bots and unsupported regions are all enrolled. This biases the population, enables trial abuse and distorts conversion. Fix: apply eligibility before bucketing, identically for both arms, and log the exclusion reason.
4. Naive local time. datetime.now() has no time zone. Hosts differ, DST creates ambiguous hours and clocks skew. Daily cohorts shift and joins with billing data break. Fix: datetime.now(timezone.utc) and ISO-8601 or epoch storage.
5. Duplicate or premature exposure logging. Each call logs an exposure, even if the user never saw the offer. Denominators inflate, and if one arm triggers more often a sample-ratio mismatch (SRM) can appear. Fix: log once, with a unique key (exp_id, user_id), when the offer is actually rendered.
6. Non-idempotent billing call. A retry or double request can start several trials. Fix: send an idempotency key such as exp_id:user_id:trial, and have billing dedupe on it.
7. No timeout, retry or backoff. requests.post can hang, and a transient 5xx silently drops the trial. Some treatment users are never treated, and that non-compliance correlates with load, which biases and attenuates the effect. Fix: timeouts, exponential backoff with jitter, a retry cap, a dead-letter queue and a circuit breaker.
8. Non-atomic dual write. Exposure is logged, billing succeeds, then the process dies before log_trial. Logs and billing disagree, and trial-start and treatment-on-treated numbers are wrong. Fix: the transactional outbox. Write the assignment, exposure and outbox row in a single DB transaction, and let a worker call billing.
9. Race conditions. Two concurrent requests can both assign the user, possibly to different arms, and both start trials. Fix: a unique constraint with INSERT ... ON CONFLICT DO NOTHING, then read back the winning row.
10. Narrow success check. Only 200 counts. A 201 or 202 is treated as failure, and errors are swallowed. Trial starts are under-reported and outages are invisible. Fix: accept any 2xx, parse the body, and emit structured error logs.
11. Asymmetric latency. Only the trial arm blocks on billing, so the experience differs by arm for reasons unrelated to the offer. This confounds engagement metrics. Fix: make the side effect asynchronous so both arms share one request path.
12. Privacy and security. Raw user_id is sent to logs and payloads, the URL is hard-coded and there is no service authentication. This is a GDPR/CCPA risk and allows spoofed grants. Fix: pseudonymous analytics IDs, mTLS or token auth, config-driven endpoints and minimal payloads.
13. No observability or kill switch. Without per-arm counters, SRM alerts, billing success rate and latency, or a flag to halt, bugs can ship for weeks. Fix: add all of these.
14. Wrong trial timestamp. now is taken before billing responds, so the recorded start precedes the real one. Trial windows and retention curves shift. Fix: store the timestamp billing returns.
Hardened design
Request path (cheap, identical for both arms):
- Check the kill switch.
- Check eligibility.
- Compute the deterministic bucket.
- In one transaction, upsert the assignment, insert the exposure (unique) and, for the trial arm, insert an outbox job.
Worker (asynchronous):
- Claim pending jobs with
FOR UPDATE SKIP LOCKED. - Call billing with an idempotency key, a timeout, backoff and a circuit breaker.
- Record the trial start using billing's timestamp.
- Send exhausted jobs to a dead-letter queue and alert.
Analysis:
- Use intent-to-treat on assigned and exposed users.
- Report the trial-grant rate as a compliance metric.
- Run a daily SRM chi-square test.
import hashlib
from datetime import datetime, timezone
EXP = {"id": "trial_1m_v2", "salt": "a9f3c1", "treatment_bp": 5000, "enabled": True}
def utcnow():
return datetime.now(timezone.utc)
def bucket(user_id, exp=EXP):
h = hashlib.sha256(f"{exp['id']}:{exp['salt']}:{user_id}".encode()).hexdigest()
return int(h[:15], 16) % 10000
def variant_for(user_id, exp=EXP):
return "trial" if bucket(user_id, exp) < exp["treatment_bp"] else "control"
def on_offer_rendered(db, user, metrics):
if not EXP["enabled"]:
return None
ok, reason = is_eligible(user)
if not ok:
metrics.incr("trial_exp.ineligible", tags={"reason": reason})
return None
v = variant_for(user.id)
with db.transaction():
db.execute(
"INSERT INTO assignment(exp_id, user_id, variant, ts) "
"VALUES (%s,%s,%s,%s) ON CONFLICT DO NOTHING",
(EXP["id"], user.id, v, utcnow()))
v = db.query_one(
"SELECT variant FROM assignment WHERE exp_id=%s AND user_id=%s",
(EXP["id"], user.id))
db.execute(
"INSERT INTO exposure(exp_id, user_id, variant, ts) "
"VALUES (%s,%s,%s,%s) ON CONFLICT DO NOTHING",
(EXP["id"], user.id, v, utcnow()))
if v == "trial":
db.execute(
"INSERT INTO outbox(key, user_id, status) "
"VALUES (%s,%s,'pending') ON CONFLICT DO NOTHING",
(f"{EXP['id']}:{user.id}:trial", user.id))
return v
def worker_step(db, billing, metrics):
for job in db.claim_pending("outbox", skip_locked=True, limit=100):
try:
r = billing.start_trial(
user_id=job.user_id,
idempotency_key=job.key,
timeout=2.0)
if 200 <= r.status_code < 300:
db.mark_done(job, started_at=r.json()["started_at"])
metrics.incr("trial.started")
else:
db.retry_later(job, backoff="exp+jitter", max_attempts=6)
except Exception:
db.retry_later(job, backoff="exp+jitter", max_attempts=6)
metrics.incr("trial.billing_error")
Common mistakes
- Fixing only randomness and ignoring exposure and billing consistency.
- Adding retries without idempotency, which turns a dropped trial into a double trial.
- Logging exposure at assignment time instead of when the user sees the offer, which dilutes the effect.
- Analyzing only users who received a trial (per-protocol), which breaks randomization. Prefer intent-to-treat and report compliance separately.
- Forgetting an SRM check, the cheapest detector of most of the bugs above.
Trade-offs
The outbox adds latency to trial activation (seconds) and operational components, but it removes both lost and duplicate trials. Hash bucketing makes re-splitting require a new salt, which is the correct behavior since it starts a new experiment.