Inferensys

Glossary

Thompson Sampling

Thompson Sampling is a Bayesian algorithm for solving the multi-armed bandit problem that selects actions by sampling from the posterior distribution of rewards, naturally balancing exploration and exploitation.
Developer reviewing multi-agent chat interface on laptop, agent conversation logs visible, casual coding session at WeWork desk.
ONLINE LEARNING ARCHITECTURE

What is Thompson Sampling?

Thompson Sampling is a foundational Bayesian algorithm for solving sequential decision-making problems under uncertainty.

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.

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.

BAYESIAN BANDIT ALGORITHM

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.

01

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.
02

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.
03

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).
04

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.
05

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.
06

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.
COMPARISON

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 / MechanismThompson SamplingEpsilon-GreedyUpper 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

THOMPSON SAMPLING

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:

  1. 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.
  2. Sample from Beliefs: On each decision round, the algorithm draws a single random sample from the posterior distribution of each arm.
  3. Select the Best Sample: It executes the action whose sampled reward value is the highest.
  4. 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.

Prasad Kumkar

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.