Thompson Sampling is a Bayesian algorithm that selects actions by randomly sampling from the posterior probability distribution of each action's expected reward, then choosing the action with the highest sampled value. This stochastic selection mechanism naturally balances exploration and exploitation: actions with high uncertainty have wider posterior distributions, giving them a chance to be sampled as optimal even when their estimated mean reward is lower.
Glossary
Thompson Sampling

What is Thompson Sampling?
A probabilistic algorithm for sequential decision-making that selects actions based on their posterior probability of being the optimal choice, providing a natural mechanism for balancing exploration and exploitation.
The algorithm maintains a prior belief about each action's reward distribution and updates it using Bayes' theorem as feedback arrives. For binary rewards, a Beta-Bernoulli conjugate pair is commonly used, while Gaussian posteriors handle continuous outcomes. Thompson Sampling achieves strong empirical performance and theoretical regret bounds, often outperforming deterministic alternatives like Upper Confidence Bound (UCB) in practice, especially in non-stationary environments where uncertainty quantification is critical.
Key Features of Thompson Sampling
Thompson Sampling is a probabilistic algorithm that selects actions by sampling from the posterior distribution of each arm's reward, naturally balancing exploration and exploitation without requiring a manually tuned exploration parameter.
Bayesian Posterior Sampling
The core mechanism of Thompson Sampling is maintaining a posterior probability distribution over each arm's unknown reward parameter. At each decision step, the algorithm draws a random sample from each arm's posterior and selects the arm with the highest sampled value. This means arms with high uncertainty have a chance to produce high samples, driving exploration. As more data is collected, the posterior distributions narrow, reducing exploration naturally. For Bernoulli bandits, this typically uses a Beta distribution as the conjugate prior, updated with observed successes and failures. The elegance lies in the fact that the probability an arm is selected exactly equals the probability it is optimal given current knowledge.
Automatic Exploration-Exploitation Balance
Unlike Epsilon-Greedy, which requires manual tuning of the exploration rate ε, or Upper Confidence Bound (UCB), which requires setting an exploration bonus coefficient, Thompson Sampling automatically calibrates exploration based on uncertainty. When an arm has been tried few times, its posterior is wide, generating highly variable samples that occasionally beat well-established arms. As data accumulates, the posterior concentrates around the true mean, and sampling naturally converges to exploitation. This self-tuning property makes Thompson Sampling particularly robust in non-stationary environments where reward distributions shift over time, as the posterior can widen again with a forgetting mechanism or sliding window.
Contextual Extension for Personalization
Thompson Sampling extends naturally to contextual bandits by modeling the expected reward as a function of context features with a Bayesian model. In the linear contextual case, a Gaussian prior is placed on the weight vector, and the posterior is updated via Bayesian linear regression. At decision time, a weight vector is sampled from the posterior, and the arm with the highest predicted reward given the current context is selected. This enables real-time personalization where the algorithm learns which actions work best for specific user segments, device types, or time-of-day patterns without requiring separate models for each context partition.
Regret Minimization Guarantees
Thompson Sampling provides strong theoretical guarantees on regret minimization. For the standard stochastic K-armed bandit, it achieves a logarithmic regret bound, meaning the cumulative regret grows only logarithmically with the number of rounds. This is asymptotically optimal, matching the theoretical lower bound. In practice, Thompson Sampling often outperforms UCB and Epsilon-Greedy in empirical studies, especially in the early rounds where efficient exploration is critical. The algorithm's regret performance stems from its ability to quickly eliminate clearly suboptimal arms while continuing to sample promising but uncertain arms proportionally to their probability of being best.
Conjugate Prior Computational Efficiency
Thompson Sampling is computationally efficient when using conjugate priors, where the posterior distribution remains in the same family as the prior after observing data. Common pairings include:
- Beta-Bernoulli for binary click/no-click rewards
- Gaussian-Gaussian for continuous rewards like revenue or time-on-site
- Dirichlet-Multinomial for categorical outcomes with more than two possibilities The update step requires only simple parameter additions rather than expensive Markov Chain Monte Carlo sampling. For non-conjugate models, Laplace approximation or bootstrapped Thompson Sampling can approximate the posterior efficiently, making the algorithm viable for high-throughput production systems serving millions of decisions per second.
Cold Start and Prior Specification
Thompson Sampling handles the cold start problem through informative prior specification. Rather than starting with uniform uncertainty, practitioners can encode domain knowledge into the prior distributions. For example, a new product category can inherit the prior from a similar existing category, or a hierarchical Bayesian model can share statistical strength across related arms. This warm-start capability means the algorithm can begin with reasonable performance from the first interaction, avoiding the random exploration phase that plagues uninformed methods. The prior also acts as a natural regularization mechanism, preventing overfitting to early noisy observations.
Thompson Sampling vs. Other Bandit Algorithms
A comparative analysis of Thompson Sampling against Epsilon-Greedy, Upper Confidence Bound, and LinUCB across key operational dimensions for production personalization systems.
| Feature | Thompson Sampling | Epsilon-Greedy | Upper Confidence Bound | LinUCB |
|---|---|---|---|---|
Algorithm Family | Bayesian probabilistic | Semi-uniform random | Deterministic optimistic | Linear contextual |
Exploration Mechanism | Posterior sampling from reward distribution | Random uniform selection with probability ε | Confidence interval bonus added to point estimate | Confidence ellipsoid around linear parameters |
Handles Uncertainty Naturally | ||||
Contextual Awareness | Via Bayesian regression or neural posterior | |||
Empirical Regret on Stationary Problems | Low | Moderate to high | Low | Low |
Hyperparameter Sensitivity | Low (prior parameters only) | High (ε decay schedule critical) | Moderate (confidence radius tuning) | Moderate (regularization parameter α) |
Computational Cost per Decision | Moderate (posterior sampling step) | Negligible | Low (closed-form update) | Low (ridge regression update) |
Cold-Start Performance | Strong (principled uncertainty drives exploration) | Weak (random exploration wastes budget) | Strong (optimistic initialization) | Moderate (requires feature design) |
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.
Frequently Asked Questions
Clear, technical answers to the most common questions about the Bayesian algorithm that optimally balances exploration and exploitation in real-time decisioning systems.
Thompson Sampling is a Bayesian probabilistic algorithm for sequential decision-making that selects actions in proportion to their probability of being optimal given the observed data. The algorithm works by maintaining a posterior probability distribution over the unknown reward parameter for each arm, sampling a value from each distribution, and then selecting the arm with the highest sampled value. This natural stochasticity causes the algorithm to explore arms with high uncertainty and exploit arms with high expected rewards. As more data is collected, the posterior distributions narrow, reducing exploration and converging toward the truly optimal action. The mechanism elegantly solves the exploration-exploitation trade-off without requiring a manually tuned exploration parameter like epsilon in epsilon-greedy approaches.
Related Terms
Thompson Sampling operates within a broader framework of bandit algorithms and evaluation techniques. Understanding these related concepts is essential for implementing robust, production-grade decisioning systems.
Bayesian Bandit
The foundational class of algorithms to which Thompson Sampling belongs. A Bayesian Bandit maintains a posterior probability distribution over the unknown reward parameters of each arm. As new data is observed, this distribution is updated using Bayes' theorem, quantifying the uncertainty around each arm's true value. Unlike deterministic methods like UCB, the Bayesian approach provides a full probabilistic model of the environment, enabling more nuanced exploration strategies and principled uncertainty quantification.
Upper Confidence Bound (UCB)
A deterministic alternative to Thompson Sampling that selects actions by maximizing an optimistic estimate of the expected reward. The algorithm calculates a confidence interval for each arm and chooses the one with the highest upper bound. The key difference from Thompson Sampling is that UCB adds an explicit exploration bonus based on the uncertainty of the estimate, while Thompson Sampling naturally randomizes selection according to the probability of optimality. UCB is often simpler to implement but can be less robust in non-stationary environments.
Regret Minimization
The primary optimization objective in bandit problems. Regret is defined as the difference between the cumulative reward of an optimal oracle policy and the reward accumulated by the learning algorithm. Thompson Sampling is renowned for achieving logarithmic regret bounds in many settings, meaning the per-round regret decreases rapidly as the algorithm learns. This formal framework allows data scientists to prove that an algorithm will converge to near-optimal performance, a critical assurance for business-critical personalization systems.
Counterfactual Evaluation
A statistical method for estimating the performance of a new policy using historical data collected under a different logging policy. This is critical for offline model validation before deployment. Key techniques include:
- Inverse Propensity Scoring (IPS): Re-weights observed rewards by the inverse probability of the action being taken by the logging policy, correcting for selection bias.
- Doubly Robust Estimator: Combines IPS with a direct reward model to provide unbiased estimates even if one of the two models is misspecified.
- These methods allow safe, rigorous comparison of Thompson Sampling against alternative algorithms without risking live user experience.
Non-Stationary Bandit
A bandit problem where the underlying reward distributions change over time, reflecting real-world dynamics like shifting consumer preferences or seasonal trends. Standard Thompson Sampling assumes stationary rewards, but variants exist that incorporate discount factors or sliding windows to forget old observations. In non-stationary environments, the algorithm must continuously adapt, making the balance between stability and plasticity a central design challenge for production personalization systems.
Neural Bandit
A contextual bandit that uses a deep neural network to model the complex, non-linear relationship between context features and expected rewards. While classical Thompson Sampling often assumes a linear or simple parametric reward model, Neural Bandits leverage the representational power of deep learning to capture intricate user behavior patterns. This fusion allows Thompson Sampling's principled exploration to scale to high-dimensional, unstructured context spaces like image embeddings or natural language descriptions.

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