Thompson Sampling is a Bayesian algorithm that selects actions randomly according to their posterior probability of being optimal. For each arm in a multi-armed bandit, the algorithm maintains a probability distribution over its expected reward, samples from each distribution, and chooses the arm with the highest sampled value. This stochastic selection mechanism provides a principled approach to the exploration-exploitation tradeoff.
Glossary
Thompson Sampling

What is Thompson Sampling?
A probabilistic algorithm for the multi-armed bandit problem that selects actions by sampling from their posterior probability distributions, naturally balancing exploration and exploitation.
The algorithm updates its posterior distributions using Bayes' theorem as new reward observations arrive, typically employing Beta distributions for binary outcomes or Gaussian distributions for continuous rewards. Unlike epsilon-greedy strategies that explore uniformly, Thompson Sampling allocates exploration proportionally to uncertainty—arms with high variance are sampled more frequently until their true value is learned. It achieves logarithmic regret and often outperforms Upper Confidence Bound (UCB) methods in practice.
Key Characteristics of Thompson Sampling
Thompson Sampling is a probability matching algorithm that selects actions based on their posterior probability of being optimal. Unlike deterministic methods, it naturally balances exploration and exploitation by sampling from the belief distribution of each arm's reward.
Probability Matching Mechanism
The core mechanism of Thompson Sampling is probability matching: an action is chosen with a frequency proportional to its probability of being the best option. At each decision step, the algorithm draws a random sample from the posterior distribution of each arm's expected reward and selects the arm with the highest sampled value. This stochastic selection ensures that arms with high uncertainty are explored naturally, while arms with high estimated rewards are exploited frequently. The process is inherently self-correcting—as more data is gathered, the posterior distributions narrow, reducing exploration automatically.
Bayesian Foundation and Priors
Thompson Sampling is fundamentally a Bayesian algorithm that requires specifying a prior distribution over each arm's reward parameter. Common choices include:
- Beta-Bernoulli model: For binary outcomes (click/no-click), using a Beta(α, β) prior where α represents successes and β represents failures.
- Gaussian model: For continuous rewards with known variance, using a Normal prior on the mean.
- Dirichlet-Multinomial model: For categorical outcomes with more than two possible results. The choice of prior encodes initial beliefs and can incorporate domain knowledge. A uniform prior (Beta(1,1)) represents complete ignorance, while an informed prior can accelerate early performance.
Regret Minimization Properties
Thompson Sampling achieves logarithmic regret in the stochastic multi-armed bandit setting, meaning the cumulative difference between its performance and an optimal oracle strategy grows only logarithmically with time. This is provably optimal. Key regret characteristics include:
- Lai-Robbins lower bound: Thompson Sampling asymptotically matches the theoretical lower bound for regret in stochastic bandits.
- Finite-time guarantees: Recent theoretical work provides finite-time regret bounds, not just asymptotic results.
- Empirical superiority: In practice, Thompson Sampling often outperforms UCB (Upper Confidence Bound) and ε-greedy strategies, especially in the early stages of learning when uncertainty is high.
Contextual Extension: Contextual Thompson Sampling
The algorithm extends naturally to contextual bandits where side information is available before each decision. In Contextual Thompson Sampling, the reward model becomes a function of context features (e.g., user demographics, time of day). A common implementation uses Bayesian logistic regression or Bayesian linear regression with a prior over the weight vector. At each step:
- A weight vector is sampled from the posterior distribution over model parameters.
- The predicted reward is computed for each arm using the sampled weights and current context.
- The arm with the highest predicted reward is selected. This allows personalization based on observed features while maintaining the exploration-exploitation balance.
Computational Efficiency and Implementation
Thompson Sampling is computationally lightweight compared to many alternatives. For the Beta-Bernoulli case, each update requires only incrementing two counters (successes and failures), and sampling from a Beta distribution is a standard library call. Key implementation considerations:
- Conjugate priors: Using conjugate prior-likelihood pairs (Beta-Binomial, Normal-Normal) ensures the posterior remains in the same distribution family, enabling closed-form updates without MCMC.
- Batch updates: Posterior updates can be performed in batches rather than after every single observation, reducing computational overhead in high-throughput systems.
- Non-conjugate extensions: For complex reward models (e.g., neural networks), approximate inference methods like variational inference or Monte Carlo dropout can approximate Thompson Sampling.
Comparison to Alternative Bandit Algorithms
Thompson Sampling differs from other bandit algorithms in fundamental ways:
- vs. ε-greedy: ε-greedy explores uniformly at random with fixed probability ε, while Thompson Sampling directs exploration toward arms that might plausibly be optimal, making it far more efficient.
- vs. UCB (Upper Confidence Bound): UCB constructs deterministic confidence intervals and always selects the arm with the highest upper bound. Thompson Sampling is stochastic and naturally handles complex posterior shapes that UCB's symmetric intervals cannot capture.
- vs. Boltzmann exploration: Softmax/Boltzmann exploration uses a temperature parameter to control exploration randomness, while Thompson Sampling's randomness is driven by genuine posterior uncertainty, which diminishes automatically with data.
Frequently Asked Questions About Thompson Sampling
Clear, technically precise answers to the most common questions about the Thompson Sampling algorithm, its mechanisms, and its application in modern reinforcement learning and personalization systems.
Thompson Sampling is a Bayesian algorithm for the multi-armed bandit problem that selects actions randomly according to their posterior probability of being optimal, naturally balancing exploration and exploitation. The algorithm works by maintaining a probability distribution over the expected reward for each available action. At each decision step, it samples a single value from each action's posterior distribution and selects the action with the highest sampled value. After observing the actual reward, it updates the posterior distribution for the chosen action using Bayes' theorem. This stochastic selection mechanism ensures that actions with high uncertainty but promising potential are explored proportionally to their chance of being optimal, while actions with high certainty of high reward are exploited consistently. Unlike epsilon-greedy approaches that explore uniformly at random, Thompson Sampling directs exploration toward actions that have a non-trivial probability of being the best.
Thompson Sampling vs. Other Bandit Algorithms
A technical comparison of Thompson Sampling against alternative multi-armed bandit algorithms across key decisioning dimensions.
| Feature | Thompson Sampling | Epsilon-Greedy | Upper Confidence Bound (UCB) |
|---|---|---|---|
Exploration Mechanism | Posterior probability matching via Bayesian sampling | Uniform random exploration with fixed probability | Optimistic bonus based on confidence intervals |
Prior Knowledge Integration | |||
Handles Non-Stationary Rewards | |||
Computational Complexity per Step | O(K) with conjugate priors | O(1) | O(K log N) |
Regret Bound (Asymptotic) | O(log N) with optimal prior | O(N) linear regret | O(log N) |
Cold Start Performance | Excellent with informative priors | Poor without tuning | Moderate |
Deterministic Action Selection | |||
Empirical Regret on Standard Benchmarks | 0.3% | 1.2% | 0.4% |
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 cornerstone of modern decision theory. Explore the foundational concepts and related algorithms that define the exploration-exploitation landscape.
Contextual Bandit
An extension of the multi-armed bandit problem where the agent observes contextual information (e.g., user demographics, time of day) before making a decision. Unlike standard Thompson Sampling which assumes a static reward distribution, contextual bandits use this side information to personalize actions. The algorithm learns a mapping from context to expected reward, often using linear models or neural networks to generalize across similar contexts.
Exploration-Exploitation Tradeoff
The fundamental dilemma that Thompson Sampling elegantly addresses. Exploitation involves choosing the action with the highest known reward to maximize immediate gains. Exploration involves selecting uncertain actions to gather data that may lead to higher rewards in the future. Thompson Sampling naturally balances these by sampling from the posterior distribution: actions with high uncertainty are chosen proportionally to their probability of being optimal.
Regret Minimization
The standard framework for evaluating bandit algorithms. Regret is defined as the difference between the cumulative reward obtained by an optimal oracle strategy and the reward accumulated by the algorithm. Thompson Sampling is proven to achieve logarithmic regret under many standard settings, meaning the rate of suboptimal choices decreases rapidly over time, making it highly efficient for production environments.
Bayesian Inference
The mathematical backbone of Thompson Sampling. Instead of point estimates, Bayesian inference maintains a posterior probability distribution over the unknown reward parameters. Key concepts include:
- Prior Distribution: Initial belief about the reward probability (e.g., Beta(1,1) for binary outcomes).
- Likelihood: How probable the observed data is given the parameters.
- Posterior Update: Using Bayes' theorem to refine beliefs after each observation. This probabilistic approach naturally quantifies uncertainty.
Upper Confidence Bound (UCB)
A frequentist alternative to Thompson Sampling for solving the exploration-exploitation dilemma. UCB algorithms select the action that maximizes an optimistic estimate of the reward, calculated as the empirical mean plus an uncertainty bonus. While both achieve optimal regret bounds, Thompson Sampling often outperforms UCB empirically because its randomized selection is more robust to delayed feedback and non-stationary environments.
Markov Decision Process (MDP)
A generalization of the bandit problem where actions influence not just immediate rewards but also future states. While Thompson Sampling solves single-step decisions, MDPs model sequential planning. Extensions like Posterior Sampling for Reinforcement Learning (PSRL) apply the Thompson Sampling principle to MDPs by maintaining a posterior over transition dynamics and reward functions, sampling a full model, and solving it to generate a policy.

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