Multi-armed bandits for routing
Thompson sampling: route each request by a draw from \(\text{Beta}(1+s_i,\ 1+f_i)\)
Takeaway
Testing three prompts with an even split over conversations loses 400 successes to the weaker prompts. Thompson sampling loses about 48.
Change the blue number. Every figure on this page updates with it.
Why care
An A/B test pays for its answer with real users.
When you compare prompts, models or agent configurations on live traffic, every request sent to a weaker option is a worse outcome for someone. A classic A/B test splits traffic evenly until the end, then switches. A multi-armed bandit learns while it serves: as evidence builds, it shifts traffic toward whatever is working, while still sending enough to the others to notice if it was wrong. For agents, where routing between several models or prompts is routine and the options change monthly, bandits turn evaluation into a continuous, low-cost process.
The intuition
Picture a row of slot machines (the "one-armed bandits") with unknown payout rates. Playing only the machine that looks best so far risks missing a better one you tried too little. Playing them all equally wastes money on machines you already know are worse. The trade-off is between exploring and exploiting.
Thompson sampling resolves it with one rule: for each request, imagine a plausible payout rate for every machine, drawn from what you have seen so far, and play the machine whose imagined rate is highest. Machines with little data have wide uncertainty, so they sometimes draw high and get tried. Machines that are clearly worse almost never win the draw. Traffic to each option ends up matching the probability that it is the best one.
The math
Each option \(i\) has an unknown success rate \(\theta_i\). After \(s_i\) successes and \(f_i\) failures, a uniform prior gives the posterior
Strategies are compared by regret: how many successes they lose against always picking the best option, which nobody knows in advance:
- \(\theta_i\)
- true success rate of option \(i\) (resolution rate, task success, thumbs-up rate)
- \(s_i,\ f_i\)
- successes and failures observed so far for option \(i\)
- \(\theta^*,\ \Delta_i\)
- the best option's rate, and option \(i\)'s gap to it
- \(n_i(N)\)
- number of requests sent to option \(i\) out of \(N\)
- Even split: regret grows in a straight line, \(N\) times the average gap.
- A/B test then commit: regret grows linearly during the test, then stops, unless the test picked the wrong winner, in which case it grows linearly forever.
- Thompson sampling: regret grows only like \(\log N\), which is the best possible rate. Each weaker option gets roughly \(\ln N / \text{KL}(\theta_i\,\|\,\theta^*)\) requests, fewer the bigger its gap.
Where each of these comes from is worked through in Derivations at the end of the page.
Interactive calculator
Three prompts with true success rates you set (the strategies don't know them). Each strategy is simulated 120 times; the chart shows the average.
Worked example: three prompts for a support agent
A support team had three candidate system prompts. Unknown to them, the prompts resolve 62%, 66% and 70% of conversations without a human. Over the next 10,000 conversations they could split traffic in one of four ways. Each strategy was simulated 300 times:
| Strategy | Lost resolutions, average | Worst 5% of runs | Traffic to the best prompt |
|---|---|---|---|
| Even split throughout | 400 | 400 | 33% |
| A/B test for 3,000, then commit to the leader | 126 | 120+ | 79% |
| Epsilon-greedy: best so far, 10% random | 87 | up to 319 | 83% |
| Thompson sampling | 48 | up to 94 | 90% |
The A/B test lost 120 resolutions during its test phase in almost every run, and in 2% of runs committed to the wrong prompt, after which it kept losing. Epsilon-greedy was usually good but sometimes locked onto an early lucky leader and took thousands of conversations to recover. Thompson sampling lost about an eighth of what the even split did, with no test length to choose. The team still reported the final comparison with confidence intervals (M06), computed on the traffic each prompt actually received.
Assumptions and where it breaks
- Success rates are assumed stable. Model updates and seasonal traffic change them. Discount old results, or use a sliding window, so the bandit can notice when a former loser improves.
- Rewards may arrive late. A ticket's resolution may only be known days later. Update in batches, and expect early decisions to lean on less data.
- The best option may differ by segment. One prompt may win on billing questions and lose on technical ones. Contextual bandits condition on request features to learn a per-segment route.
- The reward must be the outcome you want. Optimizing thumbs-up rate can reward flattery. Choose a reward close to the business outcome, and watch guardrail metrics alongside it.
- Bandit data is not a clean experiment. Weaker options get little traffic, so their estimates stay wide, and naive averages are biased. If you need a rigorous comparison, keep a small uniform slice or use inverse-propensity weighting.
How to apply it
- Define one binary reward that tracks the outcome you care about, and log it per request with the option used.
- Gate options with offline evals first. Only options that pass safety and quality checks enter the bandit.
- Start with Thompson sampling on Beta posteriors. It is a few lines of code, needs no tuning, and handles any number of options.
- Keep a small exploration floor, such as 2–5% spread across options, so new or improved options can be discovered.
- Review the posteriors weekly. Retire options whose chance of being best stays near zero, and add new candidates.
How to explain it to a stakeholder
"Instead of splitting customers evenly between three prompts for a month and then picking a winner, the system shifts traffic toward the prompt that's working as the evidence comes in. We learn the same thing, and far fewer customers get the weaker experience along the way."
Related models and patterns
For coding agents
A machine-readable summary and a reference implementation. The same spec is embedded in this page as <script type="application/json" id="model-spec">, and the whole series is listed in models.json.
id: bandits-routing
number: M12
name: Multi-armed bandits for routing (Thompson sampling)
family: multi-model
answers: "Which model or prompt should get the next request, while still learning?"
formula:
posterior: "theta_i ~ Beta(1 + successes_i, 1 + failures_i)"
route: "argmax_i of one posterior draw per option"
regret: "sum_i (theta_best - theta_i) * n_i"
asymptotic_pulls: "n_i ~ ln(N) / KL(theta_i || theta_best)"
inputs:
options: {type: list, meaning: candidate models, prompts or configurations}
reward: {type: bool, meaning: success signal logged per request}
assumptions:
- stationary success rates (discount or window otherwise)
- rewards observed reasonably soon after each request
- one best option for all traffic (use contextual bandits otherwise)
use_when:
- comparing options on live traffic
- routing among several models whose quality shifts over time
related_patterns: [routing, learning-loop, guardrails]import random
class ThompsonRouter:
def __init__(self, options, floor=0.02):
self.options = list(options)
self.s = {o: 0 for o in self.options} # successes
self.f = {o: 0 for o in self.options} # failures
self.floor = floor # small uniform exploration
def choose(self):
if random.random() < self.floor:
return random.choice(self.options)
draws = {o: random.betavariate(1 + self.s[o], 1 + self.f[o]) for o in self.options}
return max(draws, key=draws.get)
def update(self, option, success):
if success:
self.s[option] += 1
else:
self.f[option] += 1
def prob_best(self, samples=4000):
wins = {o: 0 for o in self.options}
for _ in range(samples):
draws = {o: random.betavariate(1 + self.s[o], 1 + self.f[o]) for o in self.options}
wins[max(draws, key=draws.get)] += 1
return {o: w / samples for o, w in wins.items()}
if __name__ == "__main__":
true_rate = {"prompt_a": 0.62, "prompt_b": 0.66, "prompt_c": 0.70}
router = ThompsonRouter(true_rate, floor=0.0)
for _ in range(10_000):
o = router.choose()
router.update(o, random.random() < true_rate[o])
print({o: router.s[o] + router.f[o] for o in true_rate}) # most traffic on prompt_c
print(router.prob_best())Derivations
For the math-curious: where each result in The math comes from. Nothing above depends on reading this.
The Beta posterior
With a uniform prior on \(\theta\) and \(s\) successes in \(s+f\) independent trials, the posterior density is proportional to the likelihood \(\theta^{s}(1-\theta)^{f}\), which is the Beta\((1+s, 1+f)\) distribution. Its mean is \((1+s)/(2+s+f)\) and its spread shrinks like \(1/\sqrt{s+f}\). Updating is just adding one to the right count.
Why Thompson sampling explores the right amount
Drawing one sample per option and picking the largest sends each request to option \(i\) with probability equal to the posterior probability that \(i\) is the best. An option that is clearly worse has almost no chance of drawing the highest sample, so it stops getting traffic. An option with few observations has a wide posterior, so it occasionally draws high and gets tested. Exploration therefore shrinks automatically as evidence accumulates, with no schedule to tune.
Regret of the simpler strategies
Even split: each option gets \(N/K\) requests, so regret is \(\frac{N}{K}\sum_i \Delta_i\): with gaps of 0.08, 0.04 and 0 over 10,000 requests, \(\frac{10000}{3}\times 0.12 = 400\).
A/B then commit: a test of \(T\) requests costs \(\frac{T}{K}\sum_i\Delta_i\) (120 for \(T = 3000\)), plus \((N-T)\Delta_j\) if the test wrongly picks option \(j\). The chance of that falls exponentially in \(T\Delta^2\), so short tests are cheap but risky, and long tests are safe but expensive.
Epsilon-greedy: exploring a fixed share \(\varepsilon\) forever costs \(\varepsilon N \bar\Delta\), which grows linearly; with greedy choices early on, an unlucky start can also lock in a worse option for a long time.
The logarithmic lower bound
Lai and Robbins (1985) proved that any strategy that does well on every problem must send each weaker option at least about \(\ln N / \text{KL}(\theta_i\,\|\,\theta^*)\) requests, where \(\text{KL}(p\,\|\,q) = p\ln\frac pq + (1-p)\ln\frac{1-p}{1-q}\) measures how hard \(\theta_i\) is to tell apart from \(\theta^*\). So regret must grow at least like \(\log N\). Thompson sampling with Beta posteriors matches this bound, which is why its curve in the calculator flattens while the others keep climbing.
References
- Russo, D. et al. (2018). A Tutorial on Thompson Sampling. Foundations and Trends in Machine Learning 11(1).
- Thompson, W. R. (1933). On the likelihood that one unknown probability exceeds another in view of the evidence of two samples. Biometrika 25(3/4), 285–294.
- Lai, T. L. and Robbins, H. (1985). Asymptotically efficient adaptive allocation rules. Advances in Applied Mathematics 6(1), 4–22.