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 -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.
- Q-learning learns the optimal action-value function while following any exploratory behavior policy, using the update .
- It is off-policy: the target uses , 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 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 for the max, space is for the table — both linear and practical, though the table itself does not scale to large state spaces without function approximation.
Q-learning learns the value of acting optimally by bootstrapping toward the best next action's value, letting it learn off-policy while behaving exploratorily.
The idea
Q-learning estimates the optimal action-value function , defined as the expected return from taking action in state and then behaving optimally forever after. Formally, satisfies the Bellman optimality equation:
Q-learning turns this equation into a sample-based, incremental update rule. After observing a transition , the agent updates its current estimate toward a TD target built from the observed reward plus the discounted value of the best action in the next state:
The quantity in brackets is the TD error, . This is a genuine TD method: it bootstraps (uses an existing estimate, , rather than a full Monte Carlo return) and it updates online from single steps. The crucial design choice is the . The action actually executed at time , call it , is chosen by the behavior policy — usually -greedy with respect to the current , to ensure exploration. But the target used in the update ignores entirely and instead asks: whatever the best action available in turns out to be, what is its value? This means Q-learning is evaluating and improving a target policy (the greedy policy ) 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 — 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 , 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 / 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 table, so it always reflects the latest estimate, never a stale cached value. Third, must be fixed at , since there is no future return after termination — omitting this base case is a common bug that inflates values near episode ends. Fourth, exploration () must persist throughout learning (or decay slowly enough) so that every state-action pair continues to be visited; without this, some estimates never get corrected. The diagram below shows the backup structure: the algorithm updates using the actual reward received, but the best possible* continuation value from , drawn from a branching set of candidate next actions rather than the one truly taken.
Complexity & correctness
Per-step time complexity. Each update requires computing , a scan over entries, so the per-step cost is (or 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 -greedy is also . An entire episode of length costs .
Space complexity. The tabular representation stores one value per state-action pair: . 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 . The convergence argument rests on treating Q-learning as a stochastic approximation algorithm for solving the Bellman optimality equation. Define the operator
is a contraction in the sup-norm with modulus : for any two Q-functions ,
because the max operator is non-expansive () and expectation only averages, never amplifies, differences. By the Banach fixed-point theorem, has a unique fixed point, and that fixed point is exactly by definition of the Bellman optimality equation. Q-learning's update is a stochastic version of the fixed-point iteration : instead of the exact expectation, it uses a single sampled transition, so the update has the form
which is a Robbins-Monro stochastic approximation to 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
then with probability 1, for any behavior policy that guarantees infinite visitation of every pair (it need not be greedy, or even related to 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 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 , introduces a statistical bias: because is generally an overestimate of when 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 has actions {left, right}; going right transitions to terminal state with a stochastic reward that is half the time and half the time (mean ); going left transitions to state , which has a single action leading to terminal with reward deterministically. The true optimal value is and , so the optimal action is left. Suppose after some early noisy episodes, due to sampling variance, the agent has observed the outcome from right more often than the outcome (pure chance), so its current estimate is and (not yet converged). Trace one further transition, taken via -greedy with , :
| step | S | A (behavior, ε-greedy) | R observed | S' | max_a Q(S',a) | target | δ | new Q(S,A) |
|---|---|---|---|---|---|---|---|---|
| 1 | A | right (greedy, since 4 > 0.9) | −10 (unlucky draw) | T | 0 | −10 + 1·0 = −10 | −10 − 4 = −14 | 4 + 0.5·(−14) = −3 |
| 2 | A | right (exploratory ε-pick, unlucky again) | +10 | T | 0 | 10 | 10 − (−3) = 13 | −3 + 0.5·13 = 3.5 |
| 3 | A | left (exploratory ε-pick) | — (transition, not terminal) | B | Q(B,·) = 1 (already converged) | 0 + 1·1 = 1 | 1 − 0.9 = 0.1 | 0.9 + 0.5·0.1 = 0.95 |
Even though a single unlucky sample violently swings , and a following swings it back up, the left branch's estimate steadily tightens toward the true value because its reward has zero variance. Over many episodes the law of large numbers averages out the noise on the right branch toward its true mean of , and — because the algorithm keeps exploring both actions with probability — eventually settles near while settles at , 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 above its true value of before enough data accumulates to correct it.
Common pitfalls & traps
| Pitfall | What goes wrong | Fix |
|---|---|---|
| Forgetting | Bootstrapping past episode end inflates or corrupts values near terminal states | Explicitly zero terminal-state values and never bootstrap through them |
| Letting too fast | Some state-action pairs stop being visited, violating the infinite-visitation condition, so estimates for rarely-tried actions never converge | Decay slowly, or keep a floor during learning |
| Confusing Q-learning with SARSA's target | Accidentally plugging in for the actual next action instead of turns Q-learning into SARSA, changing its risk profile and convergence guarantees | Keep the max explicit in code; do not pre-sample before computing the target |
| Ignoring maximization bias in stochastic-reward tasks | Learned values are systematically optimistic, and the greedy policy may prefer actions with high reward variance over the truly best action | Use Double Q-learning, or diagnose by comparing learned to Monte Carlo estimates |
| Step size too large or non-decaying | Updates overshoot and oscillates instead of converging, especially in stochastic-reward environments | Use a schedule satisfying Robbins-Monro conditions, or a small constant if the environment is non-stationary by design |
| Treating tabular guarantees as automatic under function approximation | Q-learning with neural networks (DQN-style) can diverge; the contraction argument does not carry over | Use 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
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 is guaranteed with probability 1.
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 , 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: with probability 1 as , 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 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 for the action actually sampled next (on-policy). Q-learning uses (off-policy, targets the greedy policy). Expected SARSA generalizes both by taking the expectation of 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 with true means , whenever the are noisy estimates rather than the true means themselves. In Q-learning, plays the role of : each is a noisy sample-based estimate of the true , 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 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 a contraction with modulus in the sup-norm, which is the mathematical fact underlying both the existence of a unique fixed point and the convergence of iterative and stochastic approximations toward it. If in a task without a guaranteed terminal state, 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.