SARSA: On-Policy TD Control

Imagine a robot learning to walk across a cliff-lined ledge. It receives a small penalty each step. A large penalty follows if it falls. It must learn a policy while still executing that same imperfect, exploring policy in the real world. There is no separate safe simulator to test "what if I had gone off the cliff." This is the central constraint that SARSA is built for. It learns a value function faithful to the policy you are actually running. Mistakes and exploration noise are included. SARSA (State-Action-Reward-State-Action) is the canonical on-policy temporal-difference control algorithm. It extends Temporal-Difference Learning: TD(0) from predicting state values to controlling behavior. It does this by estimating action-value function Q(s,a)Q(s,a). It updates that estimate using the action the agent actually takes next. This is not the best action it could have taken. This single design choice defines SARSA's core identity. It bootstraps from the realized next action rather than a hypothetical optimal one. This is what makes SARSA on-policy, in the taxonomy of On-Policy vs Off-Policy Learning. Why does this matter in real systems? Whenever exploration carries real risk, careful policies matter more. This includes physical robots, dialogue systems, and recommendation engines interacting with live users. It also includes autonomous vehicles in early testing. You often prefer a policy that learns to behave safely under its own exploration strategy. This is better than one that aggressively assumes optimal future behavior it might not actually execute. SARSA converges to the value function of the policy being followed, including its exploration. This tends to produce more conservative, exploration-aware behavior near danger. This contrasts with off-policy methods like Q-learning. This article builds SARSA from first principles. It covers the precise update rule and the full control loop with ε\varepsilon-greedy exploration. It includes a convergence argument grounded in stochastic approximation theory. A worked numerical trace follows, along with the classic pitfalls. These especially include the cliff-walking behavioral difference from Q-learning. It closes by pointing toward Expected SARSA and Q-learning as natural next steps.

Key takeaways
  • SARSA estimates Qπ(s,a)Q^\pi(s,a) using the transition quintuple (St,At,Rt+1,St+1,At+1)(S_t, A_t, R_{t+1}, S_{t+1}, A_{t+1}) — the next action actually taken.
  • It is on-policy: the target uses the same policy (e.g., ε\varepsilon-greedy) that generates behavior, unlike Q-learning's off-policy max.
  • The update is a bootstrapped TD rule: Q(St,At)←Q(St,At)+α[Rt+1+γQ(St+1,At+1)−Q(St,At)]Q(S_t,A_t) \leftarrow Q(S_t,A_t) + \alpha\big[R_{t+1} + \gamma Q(S_{t+1},A_{t+1}) - Q(S_t,A_t)\big].
  • Convergence to the optimal policy requires GLIE exploration (Greedy in the Limit with Infinite Exploration) plus Robbins-Monro step-size conditions.
  • SARSA tends to learn safer, more conservative policies than Q-learning when exploration carries risk (classic cliff-walking example).
  • It generalizes to nn-step SARSA and SARSA(λ\lambda), and motivates Expected SARSA as a variance-reduced on-policy alternative.
The core insight

SARSA learns the action-value function of the policy it is actually following, by bootstrapping from the next state-action pair it actually visits — making it on-policy by construction.

The idea

In reinforcement learning, control means finding a good policy, as opposed to prediction, which means evaluating a given policy's value function. SARSA solves the control problem by interleaving two ideas: (1) TD-style bootstrapped estimation of an action-value function Q(s,a)Q(s,a), and (2) generalized policy iteration, where the policy is improved greedily (or ε\varepsilon-greedily) with respect to the current QQ estimate while the estimate itself is being updated from experience generated by that same improving policy. Formally, the agent observes a stream of experience S0,A0,R1,S1,A1,R2,S2,A2,…S_0, A_0, R_1, S_1, A_1, R_2, S_2, A_2, \dots At each step it has a quintuple (St,At,Rt+1,St+1,At+1)(S_t, A_t, R_{t+1}, S_{t+1}, A_{t+1}) — this is the origin of the name SARSA. The update rule is

Q(St,At)←Q(St,At)+α[Rt+1+γ Q(St+1,At+1)−Q(St,At)]Q(S_t, A_t) \leftarrow Q(S_t, A_t) + \alpha \Big[ R_{t+1} + \gamma\, Q(S_{t+1}, A_{t+1}) - Q(S_t, A_t) \Big]

where α∈(0,1]\alpha \in (0,1] is the step size and γ∈[0,1]\gamma \in [0,1] is the discount factor. The bracketed term is the TD error δt\delta_t, measuring the discrepancy between the current estimate Q(St,At)Q(S_t,A_t) and the one-step bootstrapped target Rt+1+γQ(St+1,At+1)R_{t+1} + \gamma Q(S_{t+1}, A_{t+1}). The crucial detail is that At+1A_{t+1} is sampled from the agent's actual behavior policy (typically ε\varepsilon-greedy with respect to the current QQ), not chosen to maximize Q(St+1,⋅)Q(S_{t+1}, \cdot). This makes SARSA's update target an unbiased (in expectation, given the behavior policy) sample of the value of the policy being executed, so SARSA is evaluating and improving one and the same policy — the defining feature of on-policy learning. Contrast this with Q-learning's target Rt+1+γmax⁡aQ(St+1,a)R_{t+1} + \gamma \max_a Q(S_{t+1}, a), which estimates the value of the greedy policy regardless of what action is actually taken next; that decoupling of target-policy from behavior-policy is what makes Q-learning off-policy. Because the policy used to generate actions is derived from the same QQ that is being updated, and because that policy is continually improving (assuming ε\varepsilon-greedy or similar), SARSA performs a data-driven, sample-based version of generalized policy iteration: partial policy evaluation via the TD update, interleaved step-by-step with partial policy improvement via the greedy/ε\varepsilon-greedy action selection.

How it works

SARSA operates episode by episode (or continuously, for non-terminating tasks), maintaining a table (or function approximator) Q(s,a)Q(s,a) for all state-action pairs. At the start of each episode, an initial action is chosen from the initial state using the current policy; then, at every step, the next action is chosen before the update is applied, so that it can be plugged directly into the TD target. ``` Algorithm: SARSA (on-policy TD control), tabular version Input: step size α ∈ (0,1], exploration rate ε ∈ (0,1], discount γ ∈ [0,1] Initialize: Q(s, a) ← arbitrary values for all s, a # e.g. 0, or optimistic value Q(terminal, ·) ← 0 for each episode: S ← initial state of episode A ← action chosen from S using policy derived from Q (e.g. ε-greedy: with prob ε pick random action, else pick argmax_a Q(S,a)) loop for each step of episode: take action A, observe reward R and next state S' if S' is terminal: A' ← undefined target ← R else: A' ← action chosen from S' using policy derived from Q # ε-greedy target ← R + γ Q(S', A') δ ← target − Q(S, A) Q(S, A) ← Q(S, A) + α δ S ← S' A ← A' if S is terminal: break

# policy is implicitly improved every step since it is ε-greedy wrt current Q ``` Two implementation details deserve emphasis. First, the next action A′A' must be selected before the update, using the current (not-yet-updated) QQ, and it is this same A′A' that both gets plugged into the TD target and gets executed on the following iteration — there is no re-sampling. Second, terminal states are handled by defining Q(terminal,⋅)=0Q(\text{terminal}, \cdot) = 0, so the target collapses to just the reward RR, correctly terminating the bootstrap chain. The policy used for action selection is usually ε\varepsilon-greedy: with probability 1−ε1-\varepsilon pick arg⁡max⁡aQ(s,a)\arg\max_a Q(s,a), and with probability ε\varepsilon pick a uniformly random action. This guarantees continual exploration, which is essential both to visit all state-action pairs infinitely often (needed for convergence) and to make the on-policy target actually reflect exploratory behavior.

Figure
SARSA's on-policy update: the next action is sampled, not maximized
S_t A_t S_t+1 R_t+1, transition A_t+1 sampled from ε-greedy(Q) TD target (on-policy) R_t+1 + γ · Q(S_t+1, A_t+1) uses the ACTION ACTUALLY TAKEN not max_a Q(S_t+1, a) Update rule Q(S_t,A_t) += α[target − Q(S_t,A_t)] applied to the pair visited at time t

Complexity & correctness

Time and space complexity. In the tabular setting with ∣S∣|\mathcal{S}| states and ∣A∣|\mathcal{A}| actions, SARSA stores a QQ-table of size O(∣S∣⋅∣A∣)O(|\mathcal{S}| \cdot |\mathcal{A}|). Each step performs O(1)O(1) work: one table lookup for Q(St+1,At+1)Q(S_{t+1}, A_{t+1}), one arithmetic update, and one ε\varepsilon-greedy action selection, which costs O(∣A∣)O(|\mathcal{A}|) to find the greedy action by scanning (or O(1)O(1) amortized with a cached max). Over an episode of length TT, total work is O(T⋅∣A∣)O(T \cdot |\mathcal{A}|); over NN episodes, O(N⋅T⋅∣A∣)O(N \cdot T \cdot |\mathcal{A}|). This is asymptotically identical to Q-learning and to TD(0) prediction — SARSA adds no algorithmic overhead over plain TD, only the bookkeeping of carrying At+1A_{t+1} forward as AtA_t for the next iteration. With function approximation (e.g., a neural network estimating Qθ(s,a)Q_\theta(s,a)), each update costs one forward and backward pass, O(∣θ∣)O(|\theta|), replacing the table lookup — this is the basis of SARSA-style deep RL variants, though Q-learning-style off-policy methods (DQN and successors) are far more common in that regime because they permit experience replay, which is explored in Q-Learning: Off-Policy TD Control.

Correctness (convergence argument). SARSA is proven to converge to the optimal action-value function Q∗Q^* (and hence an optimal policy) under the following conditions, established by Singh, Jaakkola, Littman, and Szepesvári (1999-2000) building on stochastic approximation theory: 1. Every state-action pair is visited infinitely often. This ensures the estimate Q(s,a)Q(s,a) receives infinitely many updates for every pair, which is necessary for any sample-based estimate to converge. 2. The policy converges to the greedy policy in the limit (GLIE — Greedy in the Limit with Infinite Exploration). A standard way to satisfy both (1) and (2) is ε\varepsilon-greedy with εt→0\varepsilon_t \to 0, e.g. εt=1/t\varepsilon_t = 1/t, which explores infinitely often early on but eventually acts greedily. 3. Robbins-Monro step-size conditions: ∑tαt(s,a)=∞\sum_t \alpha_t(s,a) = \infty and ∑tαt(s,a)2<∞\sum_t \alpha_t(s,a)^2 < \infty for every state-action pair, ensuring updates are large enough to overcome any initialization but small enough to eventually stabilize (a constant α\alpha violates the second condition and yields convergence only to a neighborhood of Q∗Q^*, useful for non-stationary problems but not exact convergence). Under these conditions, the sequence of (Qt,πt)(Q_t, \pi_t) pairs performs a stochastic approximation of policy iteration: because the policy is GLIE, the TD target's expectation converges to the Bellman optimality operator's action, i.e.

EAt+1∼πt[Rt+1+γQt(St+1,At+1)∣St+1]  ⟶  Rt+1+γmax⁡aQ∗(St+1,a)\mathbb{E}_{A_{t+1}\sim \pi_t}\big[R_{t+1} + \gamma Q_t(S_{t+1},A_{t+1}) \mid S_{t+1}\big] \;\longrightarrow\; R_{t+1} + \gamma \max_{a} Q^*(S_{t+1}, a)

as t→∞t \to \infty, since πt\pi_t becomes greedy with respect to QtQ_t and Qt→Q∗Q_t \to Q^*. Intuitively: SARSA is always evaluating the current policy πt\pi_t (an on-policy fixed point for whatever πt\pi_t currently is), but because πt\pi_t is simultaneously being pulled toward greedy-in-QtQ_t, the moving target and the moving estimate co-converge to the fixed point of the Bellman optimality equation, Q∗=T∗Q∗Q^* = \mathcal{T}^* Q^*. This is a genuinely different proof structure from Q-learning, where convergence follows more directly from T∗\mathcal{T}^* being a contraction under any behavior policy that guarantees sufficient exploration — SARSA's proof must additionally track the policy's convergence to greediness.

Honest tradeoffs. SARSA's convergence guarantee is asymptotic and requires ε→0\varepsilon \to 0; in practice with fixed small ε\varepsilon, SARSA converges to the value function of the ε\varepsilon-greedy policy, not the fully optimal deterministic policy — it is evaluating the policy it runs, exploration included, which is exactly the point but means its "optimal" policy is optimal-subject-to-continued-exploration. This makes SARSA naturally more risk-aware near catastrophic states, at the cost of typically slower and sometimes lower asymptotic performance if the environment truly permits a risk-free optimal policy.

Worked example

Consider a minimized cliff-walking-style corridor: states {S0,S1,S2,SG}\{S_0, S_1, S_2, S_G\} in a line, with SGS_G terminal (goal, reward +10+10 then episode ends), and a cliff action from S1S_1 that leads to SfallS_{\text{fall}} (terminal, reward −10-10). From each non-terminal state the agent picks between action R (move right, safely, reward −1-1) and action C (only available at S1S_1: attempt a risky cliff shortcut, reward −10-10 if it falls, but let's say with probability governed by exploration it's occasionally chosen). We use α=0.5\alpha = 0.5, γ=1\gamma = 1, ε=0.1\varepsilon = 0.1, and initialize all Q(s,⋅)=0Q(s,\cdot) = 0. Suppose one training episode produces this trajectory (actions chosen ε\varepsilon-greedily, with the shown random draws having selected the risky action once for illustration):

ttStS_tAtA_tRt+1R_{t+1}St+1S_{t+1}At+1A_{t+1} (chosen next, on-policy)
0S0S_0R−1-1S1S_1C (exploration draw)
1S1S_1C−10-10SfallS_{\text{fall}} (terminal)—

Update at t=1t=1 (terminal next state, so target is just the reward):

Q(S1,C)←0+0.5[−10+1⋅0−0]=−5Q(S_1, C) \leftarrow 0 + 0.5\big[-10 + 1\cdot 0 - 0\big] = -5

Update at t=0t=0 uses the actual next action A1=CA_1 = C, even though it turned out to be the risky one:

Q(S0,R)←0+0.5[−1+1⋅Q(S1,C)−0]=0.5[−1+(−5)]=−3.0Q(S_0, R) \leftarrow 0 + 0.5\big[-1 + 1\cdot Q(S_1, C) - 0\big] = 0.5\big[-1 + (-5)\big] = -3.0

Note the crucial contrast: Q-learning, observing the same transition from S0S_0, would have used max⁡aQ(S1,a)\max_a Q(S_1,a) instead of Q(S1,C)Q(S_1, C). If the safe action's value Q(S1,R)Q(S_1,R) were already, say, −1-1 from earlier learning, Q-learning's update would be 0.5[−1+max⁡(−1,0)]=0.5[−1+0]=−0.50.5[-1 + \max(-1, 0)] = 0.5[-1+0]=-0.5 — much less pessimistic, because Q-learning assumes the agent will not actually take the risky action next time, even though during training it sometimes will. SARSA's estimate at S0S_0 is dragged down because it correctly accounts for the fact that, under the current ε\varepsilon-greedy policy, sometimes the agent really does wander into the cliff action next. Over many episodes this systematically teaches SARSA to prefer routes that stay farther from the cliff, while Q-learning's greedy-target learns the objectively shortest path and can appear reckless during training (frequently falling off) even though its final greedy policy, once exploration is turned off, would be optimal.

Common pitfalls & traps

PitfallWhy it happensFix
Sampling At+1A_{t+1} after computing the update, or re-sampling it independently at the next stepBreaks the on-policy guarantee; the executed action no longer matches the one used in the targetSample At+1A_{t+1} once, use it both in the target and as the next executed action
Forgetting Q(terminal,⋅)=0Q(\text{terminal}, \cdot) = 0Bootstrapping off an undefined or stale value for terminal states corrupts the last update of every episodeExplicitly zero-initialize and never update terminal-state entries
Fixed, non-decaying ε\varepsilon and expecting exact convergence to π∗\pi^*GLIE requires ε→0\varepsilon \to 0; constant ε\varepsilon converges to the ε\varepsilon-greedy policy's value, a biased approximation of optimalDecay ε\varepsilon (e.g. 1/t1/t) if true optimality is required, or accept the near-optimal ε\varepsilon-soft policy
Using a large constant step size α\alpha and expecting stable convergenceViolates ∑αt2<∞\sum \alpha_t^2 < \infty; the estimate oscillates around Q∗Q^* rather than settlingDecay α\alpha over visits per pair, or use small constant α\alpha only for non-stationary/tracking settings
Confusing SARSA's target with Q-learning's during implementation (using max⁡aQ(S′,a)\max_a Q(S', a) by habit)The two algorithms differ by exactly one line and are easy to mix upExplicitly assert that A′A', not arg⁡max⁡\arg\max, is plugged into the target; unit-test on a known MDP
Ignoring that "optimal" SARSA policy is optimal subject to the exploration policyMisinterpreting SARSA's asymptotic optimality as identical to Q-learning'sRemember: with ε\varepsilon fixed, SARSA's fixed point is QπεQ^{\pi_\varepsilon}, not Q∗Q^*

:::warning[Silently swapping SARSA's target for Q-learning's target is the single most common implementation bug — and it changes the algorithm's fundamental behavioral character, not just a minor detail. Writing `max(Q[S_next])` where the algorithm calls for `Q[S_next][A_next]` turns an on-policy, exploration-aware learner into an off-policy one, which can make an agent appear to work fine in simulation yet behave far more recklessly than expected once deployed with real exploration noise, exactly the cliff-walking discrepancy shown above.]

Pioneers & history

SARSA's name and tabular convergence analysis were popularized in the classic reinforcement learning textbook tradition associated with Richard Sutton, though the algorithm itself was first described by Gavin Rummery and Mahesan Niranjan in a 1994 technical report on "online Q-learning using connectionist systems" — where it was originally called "Modified Connectionist Q-Learning" before the SARSA acronym, coined by Rich Sutton, took hold.

Origins · 1 minRichard S. Sutton and how this was discovered
RS
Richard S. Sutton
born 1957 · Co-developer of temporal-difference learning and reinforcement learning theory

Sutton's work throughout the 1980s and 1990s established temporal-difference methods as the computational backbone of modern reinforcement learning, unifying dynamic programming, Monte Carlo estimation, and online learning into a single coherent framework, of which SARSA is a direct control-theoretic descendant.

History
1988
— Sutton introduces TD(λ\lambda) and temporal-difference prediction.
1994
— Rummery and Niranjan describe online Q-learning with function approximation, the algorithm later renamed SARSA.
1996
— Rummery's PhD thesis formalizes SARSA and SARSA(λ\lambda) with eligibility traces.
1999-2000
— Singh, Jaakkola, Littman, and Szepesvári prove convergence of SARSA under GLIE and Robbins-Monro conditions.
2018
— Sutton and Barto's second edition of Reinforcement Learning: An Introduction cements SARSA and the cliff-walking comparison with Q-learning as a standard teaching example.

Where this matters

SARSA and its on-policy philosophy underpin systems where the deployed policy's exploration behavior has real consequences during learning, not just at test time. In robotics, on-policy TD control (and its policy-gradient cousins) is preferred for physical systems where an off-policy method's assumption of eventual pure-greedy behavior can be dangerously optimistic mid-training. In classic control benchmarks — grid worlds, cliff-walking, mountain car — SARSA remains the standard teaching baseline for demonstrating the behavioral gap between on-policy and off-policy TD control. Its extensions, SARSA(λ\lambda) with eligibility traces and Expected SARSA (which replaces the sampled Q(St+1,At+1)Q(S_{t+1},A_{t+1}) with an expectation over the policy's action distribution to reduce variance), are used in production-grade RL libraries as lower-variance alternatives when full off-policy correction is unnecessary or undesirable. The on-policy vs. off-policy distinction that SARSA crystallizes also directly informs the design of modern deep-RL algorithms, including why methods like PPO and A2C (on-policy) and DQN/SAC (off-policy) trade off differently between sample efficiency, stability, and safety — a lineage traceable back to the SARSA-versus-Q-learning contrast.

Ask the tutor: How would the SARSA update rule and its convergence guarantees change if we used a fixed constant step size instead of a decaying one, and why might that be a deliberate design choice in non-stationary environments?

Is SARSA guaranteed to find the optimal policy?

Yes, but only under specific asymptotic conditions: every state-action pair must be visited infinitely often, the policy must be GLIE (greedy in the limit with infinite exploration, e.g. εt→0\varepsilon_t \to 0), and step sizes must satisfy the Robbins-Monro conditions (∑αt=∞\sum\alpha_t = \infty, ∑αt2<∞\sum \alpha_t^2 <\infty). Under a fixed, non-vanishing ε\varepsilon, SARSA instead converges to the value function of that ε\varepsilon-greedy policy, which is close to but not identical to the fully optimal policy. In practice, many implementations use a fixed small ε\varepsilon and accept this near-optimal fixed point in exchange for simplicity and continued exploration.

How does SARSA differ from Expected SARSA?

SARSA's update bootstraps from Q(St+1,At+1)Q(S_{t+1}, A_{t+1}) using the single action At+1A_{t+1} actually sampled from the policy. Expected SARSA instead replaces that single sample with the full expectation ∑aπ(a∣St+1)Q(St+1,a)\sum_a \pi(a\mid S_{t+1}) Q(S_{t+1}, a), averaging over all possible next actions weighted by their probability under the current policy. This removes the variance introduced by which particular action happened to be sampled, generally giving a lower-variance, often more sample-efficient update, at the cost of O(∣A∣)O(|\mathcal{A}|) extra work per step. Expected SARSA remains on-policy (or can be made off-policy by decoupling the averaging policy from behavior) and is often used as a strict improvement over vanilla SARSA when the action space is small.

Why does SARSA need the next action before computing the update, rather than after?

The entire on-policy property hinges on using the same action both in the TD target and as the action actually executed next. If you computed the update first and only afterward sampled a fresh action, the target might correspond to a different action distribution than the one truly executed, effectively decoupling target-policy from behavior-policy — which is precisely the off-policy structure SARSA is designed to avoid. Implementations therefore always sample At+1A_{t+1} immediately after observing St+1S_{t+1}, use it in the target, apply the update, and then execute that same At+1A_{t+1} on the following step, forming an unbroken causal chain.

Can SARSA be used with function approximation, like neural networks?

Yes — SARSA generalizes directly by treating Q(s,a)Q(s,a) as Qθ(s,a)Q_\theta(s,a), a parametric function, and updating θ\theta via semi-gradient descent on the TD error: θ←θ+αδt∇θQθ(St,At)\theta \leftarrow \theta + \alpha \delta_t \nabla_\theta Q_\theta(S_t, A_t). This is called semi-gradient SARSA because the target itself depends on θ\theta but that dependency is not differentiated through. It is used less often than Q-learning-style methods in deep RL because on-policy TD updates are harder to combine with experience replay (replayed transitions used the policy from an old, stale time step), though on-policy deep-RL families like A2C/PPO share its foundational philosophy at the policy-gradient level.

Does SARSA require a model of the environment's transition probabilities?

No. SARSA is fully model-free: it only requires the ability to sample transitions (St,At,Rt+1,St+1)(S_t, A_t, R_{t+1}, S_{t+1}) by interacting with the environment (or a simulator), and it never needs explicit transition probabilities P(s′∣s,a)P(s'\mid s,a) or a reward function in closed form. This distinguishes it from dynamic-programming methods like policy iteration, which require a full model, and places it alongside Monte Carlo control and Q-learning in the family of sample-based, model-free control algorithms.

What happens if the exploration rate ε is set to zero from the start?

With ε=0\varepsilon = 0, the agent always acts greedily with respect to its current QQ-estimates, so it may never visit certain state-action pairs, especially ones that initially look bad due to noisy or pessimistic initialization. Since convergence guarantees require every pair to be visited infinitely often, pure greedy SARSA can get permanently stuck exploiting a suboptimal policy discovered early, a classic exploration-exploitation failure. This is why SARSA (and TD control generally) is almost always paired with some persistent exploration mechanism, at least during training.

How does SARSA relate to generalized policy iteration?

SARSA is a sample-based, fully online instantiation of generalized policy iteration (GPI). The TD update Q(St,At)←Q(St,At)+αδtQ(S_t,A_t)\leftarrow Q(S_t,A_t)+\alpha\delta_t performs a small step of policy evaluation for the current behavior policy, while the ε\varepsilon-greedy action-selection step performs a small step of policy improvement with respect to the just-updated QQ. Unlike classical policy iteration, which alternates between complete evaluation and complete improvement sweeps, SARSA interleaves both at the finest possible granularity — after every single transition — which is what allows it to learn online from a continuous stream of experience rather than requiring a model or batches of complete episodes.

Before this

Where this leads