Thompson Sampling is a Bayesian algorithm for solving the multi-armed bandit problem that selects actions by sampling from the posterior probability distribution of each action's expected reward, thereby naturally balancing exploration and exploitation. Instead of using a deterministic rule, it makes a probabilistic decision at each timestep: it draws a random sample from the current belief about each arm's reward distribution and selects the arm with the highest sampled value. This approach ensures that actions with higher uncertainty are explored sufficiently while gradually converging to exploit the optimal action as evidence accumulates.
Glossary
Thompson Sampling

What is Thompson Sampling?
Thompson Sampling is a foundational Bayesian algorithm for solving sequential decision-making problems under uncertainty.
The algorithm operates in a continuous loop: after taking an action and observing a reward, it updates the posterior distribution for that action using Bayes' theorem. For conjugate prior distributions like the Beta-Bernoulli or Gaussian-Gaussian pair, this update is computationally efficient. Its Bayesian regret—the expected cumulative loss compared to the always-optimal action—is provably optimal for many problem classes. In practice, it is widely deployed in online A/B testing, recommendation systems, and clinical trial adaptive designs due to its simplicity, strong empirical performance, and automatic handling of the exploration-exploitation tradeoff without manual tuning.
Key Features of Thompson Sampling
Thompson Sampling is a probabilistic algorithm for the multi-armed bandit problem that naturally balances exploration and exploitation by sampling actions from posterior reward distributions.
Bayesian Probability Matching
The core mechanism of Thompson Sampling is probability matching. Instead of selecting the arm with the highest estimated mean reward, the algorithm samples a potential reward value from the posterior distribution of each arm. The arm whose sampled value is highest is chosen for that round. This elegantly encodes uncertainty: arms with wider (more uncertain) posteriors have a higher chance of being sampled, driving exploration.
- Example: If Arm A has a posterior mean of 0.8 with high confidence (narrow distribution) and Arm B has a posterior mean of 0.7 with low confidence (wide distribution), Thompson Sampling will still choose Arm B a non-zero percentage of the time, probing to see if its true mean is higher.
Automatic Explore-Exploit Balance
Thompson Sampling requires no external tuning parameter (like the ε in ε-greedy or the exploration constant in UCB) to control the exploration rate. The balance emerges automatically from the Bayesian update process. As an arm is pulled and its posterior distribution narrows (uncertainty decreases), the probability of sampling a high value from it decreases unless its mean is truly high. This leads to a natural progression from exploration to exploitation.
- Key Benefit: This eliminates the need for costly hyperparameter sweeps to set an exploration schedule, making the algorithm simpler to deploy in production systems where conditions may change.
Conjugate Prior Updates for Efficiency
For computational efficiency, Thompson Sampling is typically implemented with conjugate prior distributions. A common choice is using a Beta distribution for Bernoulli rewards (click/no-click) and a Normal-Gamma distribution for Gaussian rewards. This allows the posterior distribution to be updated analytically with simple parameter updates upon observing a new reward, enabling constant-time, O(1) updates per round.
- Update Rule (Beta-Bernoulli): Starting with prior Beta(α=1, β=1). After observing a reward of 1 (success), update to Beta(α+1, β). After a reward of 0 (failure), update to Beta(α, β+1).
Asymptotic Optimality & Regret Bounds
Thompson Sampling achieves strong theoretical performance guarantees. For the classical K-armed bandit problem, it is asymptotically optimal, meaning its cumulative regret grows at the optimal rate described by the Lai-Robbins lower bound. Modern analyses provide finite-time Bayesian regret bounds that are sublinear in the time horizon T.
- Practical Implication: This theoretical foundation assures engineers that the algorithm will not just perform well empirically but is provably efficient in the long run, converging to the best arm and minimizing lost reward.
Contextual Extension (Linear Models)
The algorithm extends powerfully to contextual bandits, where side information (context) is available for each decision. In Linear Thompson Sampling, a linear function models the expected reward given the context. A prior distribution is placed over the weight vector. The algorithm samples a weight vector from its posterior, computes the expected reward for each arm using the sampled weights and the current context, and selects the arm with the highest value.
- Use Case: This is foundational for personalized recommendations, where the context is user features, and arms are articles or products.
Robustness to Delayed or Batched Feedback
Thompson Sampling is inherently robust to delayed feedback, a common challenge in production systems (e.g., an ad click may be reported minutes later). Because it operates by maintaining a posterior distribution, feedback can be incorporated whenever it arrives, simply by updating the posterior parameters with the historical context. This also allows for efficient batched updates, where decisions are made in real-time, but the Bayesian updates are applied in mini-batches for system efficiency.
- System Design Impact: This decouples the low-latency inference path from the potentially higher-latency training update loop.
Thompson Sampling vs. Other Bandit Algorithms
A feature and mechanism comparison of Thompson Sampling against other core multi-armed bandit algorithms, highlighting their distinct approaches to the explore-exploit tradeoff.
| Feature / Mechanism | Thompson Sampling | Epsilon-Greedy | Upper Confidence Bound (UCB) |
|---|---|---|---|
Core Philosophy | Bayesian probability matching | Fixed exploration rate | Optimism in the face of uncertainty |
Action Selection | Sample from posterior, choose argmax | Random with probability ε, else greedy | Deterministic: argmax(estimate + confidence bound) |
Exploration Mechanism | Inherent, probabilistic via posterior sampling | Explicit, random uniform exploration | Explicit, deterministic optimism bonus |
Handles Uncertainty | Directly models via posterior distribution | No explicit model; explores randomly | Models via confidence interval (frequentist) |
Theoretical Guarantee | Asymptotically optimal Bayesian regret | Sublinear regret with tuned ε | Provable sublinear frequentist regret |
Parameter Tuning | Requires prior specification; less sensitive to hyperparameters post-convergence | Highly sensitive to the ε schedule | Sensitive to confidence bound scaling parameter |
Contextual Bandits | Natural extension via Bayesian linear regression or neural networks | Requires separate value function (e.g., LinUCB is not standard ε-greedy) | Direct extension via LinUCB or NeuralUCB |
Computational Overhead | Higher (requires posterior sampling) | Very low | Low to moderate (requires bound calculation) |
Non-Stationary Environments | Adapts naturally if priors/posteriors are updated (e.g., via forgetting) | Poor adaption unless ε is high or decayed | Can adapt with sliding windows or discounted UCB |
Frequently Asked Questions
Thompson Sampling is a foundational Bayesian algorithm for solving the explore-exploit dilemma in online decision-making. These questions address its core mechanics, practical applications, and relationship to other bandit algorithms.
Thompson Sampling is a Bayesian algorithm for solving the multi-armed bandit problem that selects actions by sampling from the posterior probability distribution of each action's reward, naturally balancing exploration and exploitation.
Its mechanism follows a simple, iterative loop:
- Maintain a Belief: For each possible action (or 'arm'), the algorithm maintains a posterior distribution over its expected reward. This is often modeled with a Beta distribution for binary rewards (success/failure) or a Normal-Gamma distribution for continuous rewards.
- Sample from Beliefs: On each decision round, the algorithm draws a single random sample from the posterior distribution of each arm.
- Select the Best Sample: It executes the action whose sampled reward value is the highest.
- Observe Reward & Update: After observing the real reward from the chosen action, it uses Bayes' theorem to update that specific action's posterior distribution, making it more accurate.
This process ensures that arms with higher uncertainty (wider posteriors) are explored more often, as their random samples have a higher chance of being large, while arms with high, certain rewards are reliably exploited.
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Related Terms
Thompson Sampling is a core algorithm within the broader field of online learning and sequential decision-making. These related concepts define the theoretical frameworks, alternative strategies, and system architectures that surround its application.
Multi-Armed Bandit
A multi-armed bandit is a sequential decision-making framework where an agent must balance exploring unknown actions with exploiting the best-known action to maximize cumulative reward. It is the foundational problem Thompson Sampling is designed to solve.
- Analogy: A gambler choosing between multiple slot machines (bandits) with unknown payout rates.
- Key Challenge: The agent lacks prior knowledge of the true reward distribution for each action.
- Applications: Clinical trial designs, website A/B testing, and real-time recommendation systems.
Upper Confidence Bound (UCB)
Upper Confidence Bound is a deterministic algorithm for the multi-armed bandit problem that selects the action with the highest estimated reward plus an exploration bonus proportional to the uncertainty of that estimate.
- Contrast with Thompson Sampling: UCB uses a deterministic, optimism-in-the-face-of-uncertainty principle, while Thompson Sampling is probabilistic and Bayesian.
- Mechanism: The bonus term, often derived from the Hoeffding inequality, shrinks as an action is sampled more.
- Use Case: Preferred in environments where deterministic, explainable action selection is required.
Regret Minimization
Regret minimization is the theoretical framework for analyzing online learning and bandit algorithms, where the goal is to minimize the cumulative loss difference between the algorithm's predictions and the best fixed decision in hindsight.
- Regret Definition: The total reward lost by not always playing the optimal arm.
- Theoretical Guarantee: A key metric for proving an algorithm's asymptotic optimality; both UCB and Thompson Sampling can be shown to have sublinear regret.
- Importance: Provides a rigorous, mathematical benchmark for comparing the performance of different exploration strategies.
Online Learning
Online learning is a machine learning paradigm where a model updates its parameters sequentially, one data point or mini-batch at a time, without revisiting past data.
- Core Property: Suitable for streaming data and real-time adaptation where storing the entire dataset is infeasible.
- Foundation: Algorithms like Stochastic Gradient Descent (SGD) are the fundamental update rule for most online learning systems.
- System Context: Thompson Sampling is an online learning algorithm specifically for the sequential decision-making subclass of problems.
Bayesian Inference
Bayesian inference is a statistical method where Bayes' theorem is used to update the probability for a hypothesis as more evidence or data becomes available. Thompson Sampling is a direct application of this framework.
- Posterior Distribution: Represents updated beliefs about an unknown parameter (e.g., reward rate of a bandit arm) after observing data.
- Prior Distribution: Encodes initial beliefs before seeing any data.
- Thompson Sampling Mechanism: The algorithm works by sampling a potential reward model from this posterior distribution for each arm and then selecting the arm with the highest sampled value.
Contextual Bandits
Contextual bandits extend the multi-armed bandit framework by incorporating side information (context) about each decision round, allowing the optimal action to depend on the observed context.
- Example: Recommending an article based on a user's browsing history and demographic data.
- Thompson Sampling Extension: Contextual Thompson Sampling uses a probabilistic linear model (or deep neural network) where parameters are sampled from a posterior, enabling personalized exploration.
- Industrial Application: The primary framework for modern, real-time personalization systems in tech companies.

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us