Q-Learning: Off-Policy TD Control

Imagine a robot exploring a maze it has never seen. It bumps into walls and occasionally falls into pits. Slowly, though, it discovers the shortest safe path to the exit. It cannot simulate the maze in advance. Instead, it must learn from the very trajectory of trial and error it is currently living through. The puzzle is this: can an agent learn the optimal way to behave? This must hold even while its actual behavior remains exploratory and imperfect. Q-learning answers yes. The mechanism it uses is one of the most influential ideas in reinforcement learning. Q-learning matters because most real deployments cannot cleanly separate "the policy we learn" from "the policy we execute." Yet they need the learned policy to be the best possible one. It should not merely be the policy currently used to gather data. A trading algorithm must keep taking some exploratory actions to discover new information. Still, it should converge on the profit-maximizing strategy, not a hedged compromise. A recommendation engine logging user clicks under an old policy has a similar need. It would like to extract the best policy from that log without re-collecting data. Q-learning's off-policy character makes it a natural fit for this separation. It cleanly divides exploration from the target objective. The big picture: Q-learning is a temporal-difference (TD) method for control. This means it learns action-value estimates online, one step at a time. It needs no model of the environment's dynamics. What sets it apart from SARSA: On-Policy TD Control is a single but consequential change. Instead of bootstrapping toward the value of the action the agent actually takes next, Q-learning bootstraps toward the value of the best action available in the next state. This decouples the policy being evaluated (the greedy policy) from the policy generating behavior (typically ϵ\epsilon-greedy). That decoupling makes Q-learning the canonical example of On-Policy vs Off-Policy Learning. This article builds the algorithm from its update rule upward. It covers the precise mathematical definition and a full pseudocode implementation. It includes a diagram of the backup structure and a rigorous complexity and convergence discussion. It also offers a worked numerical trace showing the max operator in action. Common pitfalls are covered too, including the overestimation bias it introduces, along with the historical context of its invention. By the end you should be able to implement Q-learning correctly. You should be able to explain why it converges to the optimal action-value function. You should also know exactly where its assumptions can break.

Key takeaways
  • Q-learning learns the optimal action-value function Q∗Q^* while following any exploratory behavior policy, using the update Q(s,a)←Q(s,a)+α[r+γmax⁡a′Q(s′,a′)−Q(s,a)]Q(s,a) \leftarrow Q(s,a) + \alpha[r + \gamma \max_{a'} Q(s',a') - Q(s,a)].
  • It is off-policy: the target uses max⁡a′Q(s′,a′)\max_{a'}Q(s',a'), the value under the greedy policy, regardless of which action the behavior policy actually selects next.
  • It is a sample-based, bootstrapped method — no environment model is needed, and it updates from single transitions rather than full returns.
  • Convergence to Q∗Q^* is guaranteed under standard stochastic approximation conditions: all state-action pairs visited infinitely often, and a Robbins-Monro step-size schedule.
  • The max operator introduces a systematic positive bias (maximization bias) in stochastic environments, motivating Expected SARSA and Maximization Bias and Double Learning.
  • Time per update is O(∣A∣)O(|\mathcal{A}|) for the max, space is O(∣S∣∣A∣)O(|\mathcal{S}||\mathcal{A}|) for the table — both linear and practical, though the table itself does not scale to large state spaces without function approximation.
The core insight

Q-learning learns the value of acting optimally by bootstrapping toward the best next action's value, letting it learn Q∗Q^* off-policy while behaving exploratorily.

The idea

Q-learning estimates the optimal action-value function Q∗(s,a)Q^*(s,a), defined as the expected return from taking action aa in state ss and then behaving optimally forever after. Formally, Q∗Q^* satisfies the Bellman optimality equation:

Q∗(s,a)=E[Rt+1+γmax⁡a′Q∗(St+1,a′)  ∣  St=s,At=a].Q^*(s,a) = \mathbb{E}\Big[R_{t+1} + \gamma \max_{a'} Q^*(S_{t+1}, a') \;\Big|\; S_t = s, A_t = a\Big].

Q-learning turns this equation into a sample-based, incremental update rule. After observing a transition (St,At,Rt+1,St+1)(S_t, A_t, R_{t+1}, S_{t+1}), the agent updates its current estimate Q(St,At)Q(S_t, A_t) toward a TD target built from the observed reward plus the discounted value of the best action in the next state:

Q(St,At)←Q(St,At)+α[Rt+1+γmax⁡aQ(St+1,a)⏟TD target−Q(St,At)].Q(S_t, A_t) \leftarrow Q(S_t, A_t) + \alpha\Big[\underbrace{R_{t+1} + \gamma \max_{a} Q(S_{t+1}, a)}_{\text{TD target}} - Q(S_t, A_t)\Big].

The quantity in brackets is the TD error, δt\delta_t. This is a genuine TD method: it bootstraps (uses an existing estimate, max⁡aQ(St+1,a)\max_a Q(S_{t+1},a), rather than a full Monte Carlo return) and it updates online from single steps. The crucial design choice is the max⁡\max. The action actually executed at time t+1t+1, call it At+1A_{t+1}, is chosen by the behavior policy — usually ϵ\epsilon-greedy with respect to the current QQ, to ensure exploration. But the target used in the update ignores At+1A_{t+1} entirely and instead asks: whatever the best action available in St+1S_{t+1} turns out to be, what is its value? This means Q-learning is evaluating and improving a target policy (the greedy policy π(s)=arg⁡max⁡aQ(s,a)\pi(s) = \arg\max_a Q(s,a)) using data generated by a different behavior policy (the exploratory one). This is precisely the definition of off-policy learning: target policy and behavior policy differ, and the update remains valid because the max operator supplies exactly the value the target policy would have obtained, without needing an importance-sampling correction. Contrast this with SARSA's update, which plugs in Q(St+1,At+1)Q(S_{t+1}, A_{t+1}) — the value of the action actually taken next. SARSA therefore evaluates whatever policy is generating behavior (on-policy), including its exploratory mistakes, and tends to learn safer, exploration-aware policies. Q-learning evaluates the greedy policy directly, learning the objectively optimal values even while its own behavior continues to explore and occasionally step off cliffs.

How it works

Q-learning is implemented as a loop over episodes and, within each episode, a loop over time steps. At every step the agent: observes the current state, selects an action via its (exploratory) behavior policy, executes it, observes the reward and next state, and applies the update rule above. Critically, unlike SARSA, the agent does not need to pre-select the next action before updating — the update only needs max⁡aQ(St+1,a)\max_a Q(S_{t+1},a), which can be computed by scanning the next state's row in the Q-table. ``` Algorithm: Q-Learning (off-policy TD control) Input: step size α ∈ (0,1], exploration rate ε, discount γ ∈ [0,1] Initialize Q(s,a) arbitrarily for all s,a; Q(terminal, ·) = 0 for each episode: Initialize S (start state) for each step of episode, until S is terminal:

# behavior policy: e.g. ε-greedy derived from Q With probability ε: A ← random action in A(S) Otherwise: A ← argmax_a Q(S, a) Take action A; observe reward R and next state S'

# off-policy target: use best next action's value,

# regardless of what the behavior policy will pick next if S' is terminal: target ← R else: target ← R + γ max_a' Q(S', a') δ ← target − Q(S, A) Q(S, A) ← Q(S, A) + α δ S ← S' end for end for return Q # π(s) = argmax_a Q(s,a) is the learned greedy policy ``` A few implementation notes that matter in practice. First, ties in the arg⁡max⁡\arg\max / max⁡\max should be broken randomly (or consistently) — always breaking ties toward the first action biases learning. Second, the max over actions is the only extra cost relative to SARSA, and it is computed fresh at each step from the current QQ table, so it always reflects the latest estimate, never a stale cached value. Third, Q(terminal,⋅)Q(\text{terminal}, \cdot) must be fixed at 00, since there is no future return after termination — omitting this base case is a common bug that inflates values near episode ends. Fourth, exploration (ϵ>0\epsilon > 0) must persist throughout learning (or decay slowly enough) so that every state-action pair continues to be visited; without this, some Q(s,a)Q(s,a) estimates never get corrected. The diagram below shows the backup structure: the algorithm updates Q(St,At)Q(S_t,A_t) using the actual reward received, but the best possible* continuation value from St+1S_{t+1}, drawn from a branching set of candidate next actions rather than the one truly taken.

Figure
Q-learning backup diagram: the update uses the max over next-state actions, not the action actually executed
Sₜ Aₜ (behavior policy) Rₜ₊₁ Sₜ₊₁ Q=1.2 Q=3.8 ← max Q=0.4 Q=2.1 update target here actual A₍ₜ₊₁₎ may differ used regardless of behavior target = Rₜ₊₁ + γ·max Q(Sₜ₊₁, a)

Complexity & correctness

Per-step time complexity. Each update requires computing max⁡aQ(S′,a)\max_{a} Q(S', a), a scan over ∣A(S′)∣|\mathcal{A}(S')| entries, so the per-step cost is O(∣A∣)O(|\mathcal{A}|) (or O(log⁡∣A∣)O(\log|\mathcal{A}|) if a max-heap per state is maintained, though this is rarely worth the overhead for typical discrete action sets). Selecting the behavior action via ϵ\epsilon-greedy is also O(∣A∣)O(|\mathcal{A}|). An entire episode of length TT costs O(T⋅∣A∣)O(T \cdot |\mathcal{A}|).

Space complexity. The tabular representation stores one value per state-action pair: O(∣S∣⋅∣A∣)O(|\mathcal{S}| \cdot |\mathcal{A}|). This is identical to SARSA and to tabular Monte Carlo control — the table size is determined by the problem, not the algorithm. This is also the central scalability limitation: for continuous or combinatorially large state spaces, tabular Q-learning is infeasible and one turns to function approximation (as in Deep Q-Networks), trading exact tabular guarantees for approximation error.

Correctness — why Q-learning converges to Q∗Q^*. The convergence argument rests on treating Q-learning as a stochastic approximation algorithm for solving the Bellman optimality equation. Define the operator

(TQ)(s,a)=Es′[R(s,a,s′)+γmax⁡a′Q(s′,a′)].(\mathcal{T}Q)(s,a) = \mathbb{E}_{s'}\Big[R(s,a,s') + \gamma \max_{a'} Q(s',a')\Big].

T\mathcal{T} is a contraction in the sup-norm with modulus γ<1\gamma < 1: for any two Q-functions Q1,Q2Q_1, Q_2,

∥TQ1−TQ2∥∞≤γ∥Q1−Q2∥∞,\|\mathcal{T}Q_1 - \mathcal{T}Q_2\|_\infty \le \gamma \|Q_1 - Q_2\|_\infty,

because the max operator is non-expansive (∣max⁡af(a)−max⁡ag(a)∣≤max⁡a∣f(a)−g(a)∣|\max_a f(a) - \max_a g(a)| \le \max_a |f(a)-g(a)|) and expectation only averages, never amplifies, differences. By the Banach fixed-point theorem, T\mathcal{T} has a unique fixed point, and that fixed point is exactly Q∗Q^* by definition of the Bellman optimality equation. Q-learning's update is a stochastic version of the fixed-point iteration Q←TQQ \leftarrow \mathcal{T}Q: instead of the exact expectation, it uses a single sampled transition, so the update has the form

Qt+1(s,a)=(1−αt)Qt(s,a)+αt[R+γmax⁡a′Qt(S′,a′)],Q_{t+1}(s,a) = (1-\alpha_t)Q_t(s,a) + \alpha_t\big[R + \gamma \max_{a'}Q_t(S',a')\big],

which is a Robbins-Monro stochastic approximation to TQt(s,a)\mathcal{T}Q_t(s,a) with noise that has zero mean (the sampled next state is an unbiased draw from the transition distribution) and bounded variance (rewards and Q-values are bounded in bounded MDPs). Watkins and Dayan's convergence theorem states: if every state-action pair is updated infinitely often, and the step sizes satisfy the Robbins-Monro conditions

∑tαt(s,a)=∞,∑tαt(s,a)2<∞,\sum_t \alpha_t(s,a) = \infty, \qquad \sum_t \alpha_t(s,a)^2 < \infty,

then Qt→Q∗Q_t \to Q^* with probability 1, for any behavior policy that guarantees infinite visitation of every pair (it need not be greedy, or even related to QQ at all, beyond exploring sufficiently). This is the formal justification for calling Q-learning off-policy: the proof places no constraint on how actions are chosen, only that exploration never stops.

Tradeoffs. The guarantee is asymptotic and requires infinite exploration — a purely greedy behavior policy can get stuck and never converge to Q∗Q^* if it stops visiting some pairs. In finite time, and especially with function approximation, convergence is not guaranteed at all (the "deadly triad" of bootstrapping, function approximation, and off-policy updates can diverge). The max operator, while what enables direct learning of Q∗Q^*, introduces a statistical bias: because max⁡aQ^(s′,a)\max_a \hat Q(s',a) is generally an overestimate of max⁡aQ∗(s′,a)\max_a Q^*(s',a) when Q^\hat Q is a noisy estimate (Jensen's inequality applied to the convex max function), Q-learning tends to systematically overestimate action values in stochastic environments — the maximization bias, resolved by Double Q-learning.

Worked example

Consider a tiny two-state chain: state AA has actions {left, right}; going right transitions to terminal state TT with a stochastic reward that is +10+10 half the time and −10-10 half the time (mean 00); going left transitions to state BB, which has a single action leading to terminal with reward +1+1 deterministically. The true optimal value is Q∗(A,left)=1Q^*(A,\text{left}) = 1 and Q∗(A,right)=0Q^*(A,\text{right}) = 0, so the optimal action is left. Suppose after some early noisy episodes, due to sampling variance, the agent has observed the +10+10 outcome from right more often than the −10-10 outcome (pure chance), so its current estimate is Q(A,right)=4Q(A,\text{right}) = 4 and Q(A,left)=0.9Q(A,\text{left}) = 0.9 (not yet converged). Trace one further transition, taken via ϵ\epsilon-greedy with α=0.5\alpha = 0.5, γ=1\gamma = 1:

stepSA (behavior, ε-greedy)R observedS'max_a Q(S',a)targetδnew Q(S,A)
1Aright (greedy, since 4 > 0.9)−10 (unlucky draw)T0−10 + 1·0 = −10−10 − 4 = −144 + 0.5·(−14) = −3
2Aright (exploratory ε-pick, unlucky again)+10T01010 − (−3) = 13−3 + 0.5·13 = 3.5
3Aleft (exploratory ε-pick)— (transition, not terminal)BQ(B,·) = 1 (already converged)0 + 1·1 = 11 − 0.9 = 0.10.9 + 0.5·0.1 = 0.95

Even though a single unlucky −10-10 sample violently swings Q(A,right)Q(A,\text{right}), and a following +10+10 swings it back up, the left branch's estimate steadily tightens toward the true value 11 because its reward has zero variance. Over many episodes the law of large numbers averages out the ±10\pm 10 noise on the right branch toward its true mean of 00, and — because the algorithm keeps exploring both actions with probability ϵ\epsilon — Q(A,right)Q(A,\text{right}) eventually settles near 00 while Q(A,left)Q(A,\text{left}) settles at 11, so the greedy policy correctly prefers left. Notice this example also illustrates the maximization bias concretely: early in learning, because the agent picks the max of two noisy branches when acting greedily, it disproportionately samples (and reinforces) whichever branch happened to look good by chance, temporarily inflating Q(A,right)Q(A,\text{right}) above its true value of 00 before enough data accumulates to correct it.

Common pitfalls & traps

PitfallWhat goes wrongFix
Forgetting Q(terminal,⋅)=0Q(\text{terminal}, \cdot) = 0Bootstrapping past episode end inflates or corrupts values near terminal statesExplicitly zero terminal-state values and never bootstrap through them
Letting ϵ→0\epsilon \to 0 too fastSome state-action pairs stop being visited, violating the infinite-visitation condition, so estimates for rarely-tried actions never convergeDecay ϵ\epsilon slowly, or keep a floor ϵmin⁡>0\epsilon_{\min} > 0 during learning
Confusing Q-learning with SARSA's targetAccidentally plugging in Q(S′,A′)Q(S',A') for the actual next action instead of max⁡aQ(S′,a)\max_a Q(S',a) turns Q-learning into SARSA, changing its risk profile and convergence guaranteesKeep the max explicit in code; do not pre-sample A′A' before computing the target
Ignoring maximization bias in stochastic-reward tasksLearned QQ values are systematically optimistic, and the greedy policy may prefer actions with high reward variance over the truly best actionUse Double Q-learning, or diagnose by comparing learned QQ to Monte Carlo estimates
Step size too large or non-decayingUpdates overshoot and QQ oscillates instead of converging, especially in stochastic-reward environmentsUse a schedule satisfying Robbins-Monro conditions, or a small constant α\alpha if the environment is non-stationary by design
Treating tabular guarantees as automatic under function approximationQ-learning with neural networks (DQN-style) can diverge; the contraction argument does not carry overUse target networks, experience replay, and gradient clipping as stabilizers

Pioneers & history

Q-learning was invented as a doctoral contribution to reinforcement learning theory, and it remains one of the field's most cited and widely implemented algorithms — the direct ancestor of Deep Q-Networks and much of modern value-based deep RL.

Origins · 1 minChristopher J. C. H. Watkins and how this was discovered
CJ
Christopher J. C. H. Watkins
1989 (PhD thesis) · University of Cambridge, reinforcement learning theory

Watkins introduced Q-learning in his 1989 doctoral thesis "Learning from Delayed Rewards," framing it as a way to learn optimal control policies from delayed, evaluative feedback without a model of the environment. He showed how the algorithm connects to dynamic programming's Bellman optimality equation while requiring only sampled experience. Together with Peter Dayan, he later provided the formal convergence proof (1992) that placed Q-learning on rigorous stochastic-approximation footing, establishing conditions under which convergence to Q∗Q^* is guaranteed with probability 1.

History
1989
— Christopher Watkins introduces Q-learning in his PhD thesis, "Learning from Delayed Rewards."
1992
— Watkins and Peter Dayan publish a formal convergence proof for Q-learning under stochastic approximation conditions.
1994
— Convergence results are extended and simplified (Tsitsiklis, and independently Jaakkola–Jordan–Singh), connecting Q-learning to general stochastic approximation theory.
2010
s — Overestimation bias is formally diagnosed and addressed via Double Q-learning (Hasselt, 2010) and later Double DQN (van Hasselt et al., 2016).
2015
— DeepMind's Deep Q-Network combines Q-learning with deep neural networks and experience replay, achieving human-level performance across Atari games from raw pixels.

Where this matters

Q-learning's tabular form is a staple of introductory RL coursework and small-scale control tasks — gridworlds, inventory control, simple game-playing agents — precisely because its update rule is simple to implement and its convergence guarantees are clean. Its conceptual core, however, extends far beyond the tabular setting. The Deep Q-Network (DQN) architecture that reignited deep reinforcement learning research in 2013–2015 is Q-learning with a neural network approximating Q(s,a;θ)Q(s,a;\theta), stabilized with experience replay and a slowly-updated target network — the same max-based Bellman target, just estimated by gradient descent rather than a table lookup. Variants and descendants of Q-learning power research and production systems in robotics (learning grasping and manipulation policies from trial interaction), recommendation systems (learning which action to recommend from off-policy logged interaction data, exploiting exactly the off-policy property), autonomous resource allocation (network routing, data center cooling control), and game-playing agents beyond Atari, including components of systems used in strategy games and simulated environments. Its off-policy nature is what makes it attractive whenever data collection and policy optimization must be decoupled — for instance, learning from a large historical log of user interactions gathered under an old, possibly suboptimal policy, without needing to re-run that old policy to compute corrections.

Ask the tutor: How exactly does Double Q-learning use two value tables to eliminate the maximization bias that Q-learning introduces?

Is Q-learning guaranteed to converge in a finite number of steps?

No. The convergence theorem is asymptotic: Qt→Q∗Q_t \to Q^* with probability 1 as t→∞t \to \infty, given infinite visitation of every state-action pair and a step-size schedule satisfying the Robbins-Monro conditions. There is no finite-time bound in the basic theorem, and in practice convergence speed depends heavily on the exploration schedule, reward scale, and step size. With function approximation (e.g., neural networks) the classical tabular convergence proof does not even apply, and empirical stabilization tricks (target networks, replay buffers) are used instead, with only weaker or no formal guarantees.

Why does Q-learning need exploration if it already learns the optimal policy's values?

The Bellman optimality equation defines Q∗(s,a)Q^*(s,a) in terms of transitions from every state-action pair, so the update needs to see samples from all of them to estimate each entry correctly. If the behavior policy stops visiting some pair permanently — for instance, becoming purely greedy too early — that entry's estimate can freeze at an incorrect value and never self-correct, even though the algorithm is mathematically designed to learn the greedy policy's values. Exploration is what supplies the data; the max operator in the update is what turns that data into optimal-policy values.

How does Q-learning relate to SARSA and Expected SARSA?

All three are one-step TD control methods sharing the same general update template: current estimate plus step size times TD error. They differ only in how the TD target's next-state value is computed. SARSA uses Q(S′,A′)Q(S',A') for the action actually sampled next (on-policy). Q-learning uses max⁡aQ(S′,a)\max_a Q(S',a) (off-policy, targets the greedy policy). Expected SARSA generalizes both by taking the expectation of Q(S′,a)Q(S',a) under the current behavior policy's action distribution, reducing variance relative to SARSA while remaining flexible about on- versus off-policy use depending on which policy the expectation is taken under.

Why does the max operator cause overestimation, precisely?

By Jensen's inequality, for any collection of random variables X1,…,XkX_1,\dots,X_k with true means μ1,…,μk\mu_1,\dots,\mu_k, E[max⁡iXi]≥max⁡iE[Xi]\mathbb{E}[\max_i X_i] \ge \max_i \mathbb{E}[X_i] whenever the XiX_i are noisy estimates rather than the true means themselves. In Q-learning, max⁡aQ^(s′,a)\max_a \hat Q(s',a) plays the role of max⁡iXi\max_i X_i: each Q^(s′,a)\hat Q(s',a) is a noisy sample-based estimate of the true Q∗(s′,a)Q^*(s',a), so taking the max preferentially picks out whichever action's estimate happens to be positively biased by sampling noise at that moment, systematically inflating the target above the true optimal value.

Can Q-learning be used with continuous action spaces?

Not directly in its tabular form, since max⁡aQ(s′,a)\max_a Q(s',a) requires an explicit search or optimization over actions, which is straightforward for small discrete action sets but intractable for continuous ones. Continuous-action extensions instead learn a separate policy network to approximate the arg-max (as in actor-critic methods such as DDPG and its successors), effectively replacing the exact max with a learned, differentiable approximation. The core off-policy TD idea — bootstrapping toward the value of the best available action — is preserved, but the "best action" is found via gradient ascent on a critic rather than exhaustive enumeration.

What role does the discount factor γ play in Q-learning's convergence proof?

The discount factor is what makes the Bellman optimality operator T\mathcal{T} a contraction with modulus γ<1\gamma < 1 in the sup-norm, which is the mathematical fact underlying both the existence of a unique fixed point Q∗Q^* and the convergence of iterative and stochastic approximations toward it. If γ=1\gamma = 1 in a task without a guaranteed terminal state, T\mathcal{T} may not be a contraction and value estimates can diverge; this is why undiscounted Q-learning is typically restricted to episodic tasks with guaranteed termination, where the effective contraction still holds through the finite horizon.

Before this

Where this leads