Did a New Dispatch Algorithm Cut Rider Wait Times? A/B Analysis
Statistics & ExperimentsModel answerLast updated
Analyze a city-level dispatch A/B test in pandas, run a Welch t-test on wait time, and discuss clustering, selection bias, effect size, and a stronger experiment design.
A ride-hailing team ran an experiment during July 2024 in a single city (San Francisco) to check whether a new dispatch algorithm shortens the time riders wait to be picked up. You are given two tables:
df_users(user_id, variant)
df_rides(ride_id, user_id, ride_date, city, time_to_pickup)
Assumptions
- Use Python with pandas and a standard statistics library such as scipy or statsmodels.
- Only rides in San Francisco from July 1 through July 31, 2024 (inclusive of the whole last day) are in scope.
- The requested test is a two-sided Welch's t-test on
time_to_pickupbetween the two variants. - If a user can appear in many rides, you must state what that does to the test's independence assumption.
Questions you would want answered before starting
- Was the treatment randomized per user, and is each user assigned exactly once and permanently?
- Which variant is the control? Are any assignments missing or duplicated?
- Is
ride_datetimezone-aware? Are canceled or invalid rides already removed? - What significance level and what minimum practically meaningful improvement were set before looking at the data?
Part 1: Compute the p-value
Filter the rides, attach each ride's user variant, run Welch's t-test on time_to_pickup, and return the p-value. Describe the data-quality checks you would run along the way, and report group sizes and means next to the p-value.
Part 2: Interpret and strengthen the experiment
Explain when the result counts as statistically significant and whether significance alone shows the new algorithm is better. Then propose a more robust experiment and analysis plan.
Hints
Hint 1
For the date filter, use a half-open interval (`>= 2024-07-01` and `< 2024-08-01`) so rides late on July 31 are not dropped, and confirm the timezone before comparing.
Hint 2
Validate the join: assert that `user_id` is unique in `df_users`, check for rides whose user has no variant, and pass `equal_var=False` to get Welch rather than Student's test.
Hint 3
Think about the unit of randomization versus the unit of analysis. If users were randomized but you test rides, repeated rides from one user are correlated, so aggregate per user or use cluster-robust standard errors.
Hint 4
A small p-value says the difference is unlikely under the null, not that it is large or valuable. Report the difference in means with a confidence interval and compare it to a pre-set minimum effect.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part 1: Computing the p-value
Approach
- Restrict rides to San Francisco and to a half-open date window.
- Validate and join variants onto rides.
- Run Welch's t-test (unequal variances) and report counts, means, difference, and p-value.
import pandas as pd
from scipy import stats
def pickup_test(df_users, df_rides):
rides = df_rides.copy()
rides["ride_date"] = pd.to_datetime(rides["ride_date"])
in_window = (
(rides["city"] == "San Francisco")
& (rides["ride_date"] >= "2024-07-01")
& (rides["ride_date"] < "2024-08-01")
)
rides = rides.loc[in_window].dropna(subset=["time_to_pickup"])
# Each user must have exactly one variant
assert df_users["user_id"].is_unique, "duplicate assignments"
merged = rides.merge(df_users, on="user_id", how="inner", validate="many_to_one")
groups = {v: g["time_to_pickup"] for v, g in merged.groupby("variant")}
a, b = list(groups.values()) # control, treatment (check labels!)
t, p = stats.ttest_ind(b, a, equal_var=False) # two-sided by default
print(merged.groupby("variant")["time_to_pickup"].agg(["count", "mean", "std"]))
return p
Data-quality checks
- Date boundary: using
<= "2024-07-31"on a timestamp column silently drops almost all of July 31. Use< 2024-08-01. Convert to a single timezone (the city's local time) first. - Join cardinality:
validate="many_to_one"fails loudly if a user has two variants. Count rides that lost their variant in the join; a large number signals a pipeline problem. - Nulls and outliers: drop or investigate missing pickup times; check for negative values, zero values, and extreme tails (for example, a 3-hour pickup). Wait times are right-skewed, but with large samples the Welch test is still reasonable by the central limit theorem. Consider a winsorized or log-scale sensitivity check.
- Variant labels: confirm which label is control so the sign of the difference is interpreted correctly.
- Sample ratio mismatch (SRM): compare user counts per arm against the planned split (for example 50/50) with a chi-square test. A significant mismatch means the randomization or logging is broken and the result should not be trusted.
The independence problem
Welch's test assumes independent observations. If a user takes many rides, their rides share the same neighborhood, habits, and device, so they are correlated. Treating each ride as independent understates the standard error, makes the p-value too small, and inflates false positives. Since randomization happened at the user level, the effective sample size is closer to the number of users than the number of rides.
Part 2: Interpretation and a stronger design
When is it significant?
Compare the p-value with an alpha chosen before the experiment (commonly 0.05). If p < alpha, reject the null of equal mean pickup time. But significance is not the same as being better or worth shipping:
- Report the effect: difference in mean pickup time (for example, -12 seconds, or -4%), with a 95% confidence interval.
- Judge practical significance: is the interval's plausible range above a minimum worthwhile improvement, given engineering and operational cost? With millions of rides, trivially small gaps become significant.
- A p-value is not the probability the new algorithm is better, and a non-significant result is not proof of no effect. It may be underpowered.
Fixing the unit of analysis
- User-level aggregation: compute each user's mean pickup time, then run Welch's test on the per-user means. This matches the randomization unit and is simple, though it weights light and heavy users equally.
- Cluster-robust regression: fit
time_to_pickup ~ variantwith standard errors clustered byuser_id(for example,statsmodelsOLS withcov_type="cluster"). This keeps ride-level weighting and gives valid inference. - Alternatives: a mixed-effects model with a user random intercept, or a bootstrap that resamples users, not rides.
- Variance reduction with pre-experiment covariates (CUPED) can shorten the test.
Post-treatment selection
Pickup time exists only for rides that happened. If the new algorithm changes whether people request, cancel, or complete rides (for example, shorter waits mean fewer cancellations), then comparing only observed rides compares different populations. Mitigate this by:
- Analyzing all assigned users (intention to treat), including those with zero rides, and tracking rides per user, request rate, and cancellation rate as separate outcomes.
- Treating completed-ride pickup time as a conditional metric and labeling it as such.
Experiment integrity checks
- SRM and balance on pre-period covariates (past rides, city zone, device).
- Interference: drivers are shared between arms. If treated riders take nearby drivers, control riders can get worse waits, biasing the estimate. Consider geo or time-slice randomization (switchback) so supply is not shared.
- Attrition, logging gaps, and novelty effects across weeks.
Plan for a stronger experiment
- Primary metric: mean (or median and 90th percentile) pickup time, per user, pre-registered.
- Guardrails: cancellation rate, trip completion, driver earnings and utilization, trip duration and cost, rider retention.
- Duration: run at least one to two full weeks, ideally covering weekday and weekend cycles, sized from a power calculation using the minimum detectable effect and the user-level variance. Do not stop early when the p-value dips below alpha.
- Segmentation: examine by time of day, zone density, and new versus returning users, labeled exploratory with multiple-comparison control.
- Launch rule (defined in advance): ship if the confidence interval's upper bound is below a threshold improvement (for example, at least a 5-second reduction), no guardrail degrades beyond tolerance, and SRM and integrity checks pass.
Common mistakes
- Dropping the last day through an inclusive date comparison on timestamps.
- Using Student's t-test or forgetting
equal_var=False. - Treating ride-level rows as independent when users were randomized.
- Reporting only a p-value without effect size or interval.
- Ignoring SRM, interference, and changes in who takes rides.