Picking a Retry Cap for Flaky Audio Streaming
Statistics & ExperimentsModel answerLast updated
Use logged interruption events to pick a maximum retry count that balances playback recovery against battery cost, and explain how to correct for bias and validate the choice before launch.
You are on the team that owns audio playback for a mobile streaming app. While a track is playing, the connection sometimes drops. Two situations look identical at first:
- Transient drop: a few more reconnect attempts would restore the stream.
- Real outage: no connectivity is available, and every extra attempt just wakes the radio and drains the battery.
You have a historical log with one row per interruption event:
| Column | Type | Meaning |
|---|---|---|
retry_count | integer | How many reconnect attempts were made before the event closed. |
is_success | boolean | Whether the app ultimately reconnected and received audio data. |
Product wants a single cap T: the app retries at most T times and then stops and shows a graceful failure state.
Question. How would you use this log to choose a good value of T? In your answer, cover:
- How you interpret each row and which quantity you estimate.
- The metrics and the objective, including the reliability vs. battery trade-off.
- The statistical method, including uncertainty.
- Biases and limitations in the historical data.
- How you would validate the choice before a full rollout.
Hints
Hint 1
Think about what a row with is_success = false really tells you: you know the event lasted at least that many retries, but not whether the next one would have worked. How does that change the way you estimate recovery by retry number?
Hint 2
Frame the choice as a marginal one: at retry k, what is the chance the next attempt succeeds given all earlier ones failed, and is that chance worth the extra battery cost? Consider both a cost-per-recovery rule and a constrained 'near-max recovery within a battery budget' rule.
Hint 3
The log only reflects whatever cap the app used before. Ask what that implies for any T above the old cap, whether retry count is a good stand-in for elapsed time, and what randomized experiment and guardrail metrics you would run to confirm the answer.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Model answer
1. Reframe the problem
Choosing T is a stopping problem: after each failed attempt, is one more attempt worth it? Each row is a discrete-time event history:
is_success = true,retry_count = k: recovery was observed at attempt k.is_success = false,retry_count = k: the event ended after k attempts without recovery. This is right-censored. The cause may be the old cap, the user skipping or pausing, or the OS suspending the app. We do not know whether attempt k+1 would have worked.
So the right tool is survival analysis, not a simple "fraction of successes with retry_count ≤ k".
2. Core quantity: the discrete hazard
$$\hat h(k) = \frac{#{\text{successes at } k}}{#{\text{events with retry_count} \ge k}}$$
Censored events stay in the denominator up to the attempt where they ended. The cumulative recovery by cap T is
$$F(T) = 1 - \prod_{k\le T}(1-\hat h(k))$$
This is the Kaplan–Meier construction. Hazards typically fall with k, because the events that survive many attempts are increasingly true outages. That decline is the reason a cap makes sense at all.
3. Metrics and objective
- Benefit: recovery rate F(T), or better, playback-failure rate per listening hour and stalls per session.
- Cost: expected retries per event, E[retries | T] = Σ_{k=1..T} S(k−1), where S is the probability of still being disconnected. Convert to radio-on time or energy if the platform can measure it.
Two ways to pick T:
- Marginal rule. Let V be the value of a recovered playback and c the cost of one attempt. Continue while h(k)·V > c, giving T* = max{k : h(k) ≥ c/V}. The weakness is that you must price a lost listening moment against energy.
- Constrained rule. Plot F(T) against expected retries (a Pareto curve). Choose the smallest T that reaches, say, 98–99% of achievable recovery within a battery budget. This is usually easier to agree on with stakeholders, and the "knee" of the curve is where hazard flattens near zero.
Context matters: with 30 seconds of audio buffered, a slow recovery is invisible, whereas with an empty buffer every attempt counts. This argues for a policy that depends on buffer level rather than one global number.
4. Estimation procedure
- Compute the hazard table and F(T) for each k, with bootstrap confidence intervals. Resample by user or device, not by event, since events within a user are correlated.
- Replay each candidate T on the history: a success with retry_count ≤ T stays a success, a success beyond T becomes a failure, and each event costs min(retry_count, T) attempts.
- If the tail is sparse, smooth with a parametric hazard (geometric, Weibull) or a discrete-time logistic model, logit h(k) = f(k, covariates), fit on person-period data.
- Segment by network type, signal strength, device and OS, mobility, and region. A contextual cap (higher on cellular while moving, lower when airplane mode was just toggled) usually beats one global T.
import pandas as pd
def hazard_table(df, max_k):
rows = []
for k in range(max_k + 1):
at_risk = (df.retry_count >= k).sum()
succ = ((df.retry_count == k) & df.is_success).sum()
rows.append((k, at_risk, succ, succ / at_risk if at_risk else float("nan")))
t = pd.DataFrame(rows, columns=["k", "at_risk", "successes", "hazard"])
t["recovered_by_k"] = 1 - (1 - t.hazard.fillna(0)).cumprod()
return t
def replay(df, T):
recovered = (df.is_success & (df.retry_count <= T)).mean()
retries = df.retry_count.clip(upper=T).mean()
return recovered, retries
Complexity is O(n) per k, or O(n log n) overall with sorting and cumulative counts.
5. Biases and pitfalls
- Policy censoring. If the old app capped at M retries, there is no information on h(k) for k > M. Raising T above M cannot be justified from this log; it needs an experiment.
- Count is not time. With exponential backoff, attempt 8 may be minutes later. Recovery is driven by elapsed time (leaving a tunnel), so the real knob may be a time budget. Ask for timestamps.
- Informative censoring. Users who skip, pause, or kill the app differ from those who wait, breaking the independent-censoring assumption. Separate policy stops from user or OS stops if logging permits.
- Selection and logging gaps. Crashes, dead batteries, and failed log uploads are missing, and they skew toward bad networks.
- Heterogeneity. A pooled hazard mixes quick transient blips with permanent outages; segment-level curves are more actionable.
- Feedback effects. Aggressive retries can add server load or trigger throttling, and users react to failures (manual retry, switching to offline music).
- Non-stationarity. Networks, app versions, and backoff logic change, so check stability across time windows and favor recent data.
- Event definition. Define success carefully (audio obtained before the buffer ran out?) and avoid double counting repeated interruptions in one session.
6. Validation before launch
- Offline report: Pareto curve with intervals, recommended T (or per-segment T), and predicted change in recovery and retries per event.
- Randomized experiment: assign at the device or user level, not the event level, so battery and experience are attributable. Use arms that bracket the recommendation (current cap, T*−2, T*, T*+2 or more, including values above the old cap to learn the tail). Run long enough to cover weekday and weekend and diverse networks.
- Primary metrics: playback failures and stalls per listening hour, session abandonment.
- Guardrails: measured energy per hour (radio-on time, battery drain on matched devices), crash rate, server request load, and retention.
- Analysis: compare with confidence intervals, check heterogeneity by segment, and set decision thresholds up front (for example, accept if failure rate improves with no more than X% battery cost).
- Rollout: staged ramp with a kill switch, then re-estimate the hazard under the new policy since it now gives data on the previously unobserved tail.
Common mistakes
- Taking a percentile of successful retry counts, which ignores censored events and the cost side.
- Treating failures as true "never recovers" outcomes.
- Using one global T with no segmentation.
- Randomizing at the event level, which contaminates battery measurement.
- Ignoring that retry counts and elapsed time are different quantities.