Sub topic 15
Beyond fixed splits: bandits and interleaving
This chapter covers two ways to learn which model is better without a fixed traffic split. It assumes you have read the chapters on A/B testing, sticky assignment, and significance testing. You should also be comfortable with proportions and short Python snippets.
Why fixed splits are sometimes the wrong tool
A classic A/B test fixes the split in advance, for example 50/50. It then waits until the planned sample size is reached and tests once. This design is simple and gives clean statistical answers. It also has two costs.
- Regret. While the test runs, half of the traffic sees the worse model. If the candidate is clearly bad after two days, a fixed split keeps sending users to it anyway.
- Sensitivity. Many ranking and recommendation changes move a business metric by a very small amount. Detecting that shift between two groups of different users can need a huge sample.
Two techniques address these costs. Multi-armed bandits shift traffic toward the better variant while the experiment runs. Interleaving mixes results from two rankers inside one response, so each user compares both models directly.
Neither technique replaces A/B testing. They fit specific situations, and they have their own failure modes.
Multi-armed bandits
A multi-armed bandit is a method that allocates traffic among several options (called arms) and updates the allocation as results arrive. Each arm is a model version. Each request is a pull. Each outcome, such as a click or a conversion, is a reward.
The core tension is exploration versus exploitation. Exploitation means sending traffic to the arm that looks best so far. Exploration means sending some traffic to the other arms to check whether your current belief is wrong. A fixed split explores forever. A pure "always pick the best" rule never recovers from early bad luck.
Epsilon-greedy
The simplest rule is epsilon-greedy. With probability epsilon (for example 0.1), pick an arm at random. Otherwise pick the arm with the highest observed reward rate. It is easy to explain and implement. It keeps exploring at the same rate even after the answer is obvious, which wastes traffic.
Thompson sampling
Thompson sampling keeps a probability distribution over each arm's true reward rate. For a binary reward such as click or no click, a Beta distribution works well. For each request, the router draws one sample from each arm's distribution and picks the arm with the highest draw. Arms that are uncertain get drawn high sometimes, so they still receive traffic. Arms that are clearly worse are rarely picked.
import random
class ThompsonRouter:
"""Beta-Bernoulli Thompson sampling over named model variants."""
def __init__(self, arms):
# Beta(1, 1) is a uniform prior: no belief before any data.
self.successes = {arm: 1 for arm in arms}
self.failures = {arm: 1 for arm in arms}
def choose(self) -> str:
draws = {
arm: random.betavariate(self.successes[arm], self.failures[arm])
for arm in self.successes
}
return max(draws, key=draws.get)
def update(self, arm: str, reward: bool) -> None:
if reward:
self.successes[arm] += 1
else:
self.failures[arm] += 1
random.seed(7)
true_rates = {"stable": 0.048, "candidate": 0.054}
router = ThompsonRouter(true_rates)
served = {arm: 0 for arm in true_rates}
for _ in range(20000):
arm = router.choose()
served[arm] += 1
router.update(arm, random.random() < true_rates[arm])
print(served)In this simulation the candidate has a slightly higher true rate. Over time it receives most of the traffic. The exact counts depend on the seed, but the allocation drifts toward the better arm without anyone changing a weight by hand.
What bandits give up
Bandits trade statistical clarity for lower regret. Know these costs before choosing one.
- Weaker inference. Because the allocation depends on earlier results, the groups are unbalanced and the simple two-proportion test from the A/B chapter no longer applies as written. Estimates of the size of the difference are biased unless you use methods designed for adaptive data.
- Non-stationarity. Reward rates change with time of day, season, and traffic mix. A bandit that learned on weekday traffic may starve an arm that would win on weekends. Use a sliding window or discounted counts if the environment drifts.
- Delayed rewards. If labels arrive days later, the router updates on stale data. Early traffic looks like "no conversion yet", which punishes every arm and can distort the allocation. Count only requests old enough to have a mature label, or model the delay explicitly.
- Sticky assignment conflicts. A bandit chooses per request by default. If users must see one model consistently, make the choice per user and store it, or hash the user into a bucket and let the bandit set the bucket-to-arm weights.
- Sample ratio checks change. The sample ratio mismatch check from the pitfalls chapter compares observed counts to planned counts. With a bandit, the plan itself changes over time. Log the allocation probability for each request so you can check it against what actually happened.
Bandits and guardrails
A bandit optimizes one reward. It will happily raise clicks while latency or refund rates get worse. Keep the guardrail metrics from earlier chapters outside the bandit and check them on a schedule. Treat a guardrail breach as a hard stop that removes the arm, not as one more term in the reward.
Interleaving
Interleaving is a technique for comparing two rankers, such as search or recommendation models, inside a single result list. Instead of sending user A to model 1 and user B to model 2, you show every user one merged list built from both models. You then credit the model whose results the user clicked.
The advantage is that each user acts as their own control. Differences between users, which add noise in an A/B test, cancel out. Interleaving often detects a ranking preference with far less traffic than a split test.
Team-draft interleaving
In team-draft interleaving, the two rankers take turns picking their highest-ranked item that is not yet in the merged list, like captains choosing teams. A coin flip decides who picks first in each round. The system records which ranker contributed each item. When the user clicks an item, that ranker earns the credit.
import random
def team_draft(list_a, list_b, k, rng=random):
"""Merge two rankings. Returns (merged_items, owner_of_item)."""
merged, owner = [], {}
while len(merged) < k:
added = False
order = ["A", "B"]
rng.shuffle(order) # coin flip for who picks first this round
for team in order:
source = list_a if team == "A" else list_b
pick = next((x for x in source if x not in owner), None)
if pick is not None and len(merged) < k:
merged.append(pick)
owner[pick] = team
added = True
if not added:
break
return merged, owner
def credit(owner, clicked_items):
score = {"A": 0, "B": 0}
for item in clicked_items:
if item in owner:
score[owner[item]] += 1
return score
random.seed(1)
a = ["d1", "d2", "d3", "d4", "d5"]
b = ["d3", "d1", "d6", "d2", "d7"]
merged, owner = team_draft(a, b, k=5)
print(merged)
print(credit(owner, clicked_items=["d3"]))Over many sessions you count how often A wins, B wins, or the two tie. A sign test or a binomial test on the win counts tells you whether one ranker is preferred more often than chance would explain.
What interleaving cannot do
- It only applies to ranked lists. You cannot interleave a fraud score or a single yes/no decision.
- It measures preference, not business value. Users may click the results of the ranker that is more clickable but leads to fewer purchases. Confirm a winner with a short A/B test on the real business outcome.
- It needs both models online. You pay the serving cost of both models for every request, similar to a shadow deployment.
- Position bias interacts with the merge. The randomized turn order protects against systematic favoritism, but you should still check that wins are not concentrated in one position.
Choosing between the approaches
| Situation | Better fit | Reason |
|---|---|---|
| You need a defensible effect size for a decision or report | Fixed A/B test | Balanced groups and a standard test |
| Many variants, short-lived content, cost of showing a bad arm is high | Bandit | Traffic moves to winners quickly |
| Two rankers, small expected difference, limited traffic | Interleaving | Within-user comparison removes between-user noise |
| Outcome is a delayed label such as a loan default | Fixed A/B test | Bandit updates would run on immature data |
| Release risk is about crashes or latency | Canary | The question is safety, not preference |
A common sequence combines them. Use shadow and canary stages to confirm the candidate is safe. Use interleaving to screen several ranking candidates quickly. Run a fixed A/B test on the best one to measure its business effect. Use a bandit afterward for ongoing choices among many cheap variants where regret matters more than exact estimates.
Common errors
- Using a bandit when you need a number. If a stakeholder will ask "how much better is it, with what confidence?", a bandit's adaptive data makes that harder to answer.
- Letting the bandit converge on a novelty effect. Users often click new things at first. A bandit may lock onto the candidate during that spike. Keep a small floor of exploration and revisit the allocation after the effect fades.
- Dropping the exploration floor. If an arm's share reaches zero, you can never learn that it improved. Set a minimum share, such as 1 to 5 percent.
- Treating interleaving wins as launch approval. A preference win does not cover latency, cost, or business outcomes. Run the guardrails and a final A/B test.
- Forgetting to log the merge. For interleaving, store which ranker owned each shown item. Without that record the clicks cannot be credited later.
Exercise
A team runs a Thompson sampling router over two ranking models. After a week, the candidate holds 90% of traffic and the dashboard shows a higher click rate. The product lead asks for a p-value from the two-proportion z-test used in the earlier A/B chapter. Why is that test a poor fit here, and what should the team do?
Show answer
Allocation changed over time depending on earlier outcomes, so the groups are unbalanced and the observations are not independent draws from a fixed design. The z-test assumes a fixed split and a single analysis, so its p-value is not reliable. The team should log the assignment probability for each request and use methods built for adaptive data, such as inverse-probability weighting. Or they can confirm the result with a short fixed-split A/B test on the same two models.
Exercise
In team-draft interleaving, rankers A and B produce the merged list [d3, d1, d6, d2, d7], where A owns d1 and d2 and B owns d3, d6, and d7. A user clicks d1 and d6. Which ranker wins this session?
Show answer
The session is a tie. A owns d1, and B owns d6, so each ranker gets one click credit. Ties are counted separately from wins when you aggregate sessions.