TExcelTAD
Home › Kubernetes › Rolling Updates & Rollbacks

Rolling Updates & Rollbacks

A rolling update replaces the Pods of a Deployment gradually, so the application keeps serving traffic while the new version comes up. Two settings in spec.strategy.rollingUpdate control the pace:

Setting Meaning Default
maxSurge How many Pods above replicas may exist during the update 25%
maxUnavailable How many Pods below replicas may be unavailable 25%

Both accept an absolute number or a percentage. Percentages are converted using replicas: maxSurge rounds up, maxUnavailable rounds down. They can't both be 0.

python · try it yourself
import math

def resolve(value, replicas, round_up):
    if isinstance(value, str) and value.endswith("%"):
        exact = int(value[:-1]) * replicas / 100
        return math.ceil(exact) if round_up else math.floor(exact)
    return value

for replicas in [1, 3, 4, 10]:
    surge = resolve("25%", replicas, round_up=True)
    unavail = resolve("25%", replicas, round_up=False)
    print(f"replicas={replicas:2}: maxSurge={surge} maxUnavailable={unavail} "
          f"-> at most {replicas + surge} Pods, at least {replicas - unavail} available")
replicas= 1: maxSurge=1 maxUnavailable=0 -> at most 2 Pods, at least 1 available
replicas= 3: maxSurge=1 maxUnavailable=0 -> at most 4 Pods, at least 3 available
replicas= 4: maxSurge=1 maxUnavailable=1 -> at most 5 Pods, at least 3 available
replicas=10: maxSurge=3 maxUnavailable=2 -> at most 13 Pods, at least 8 available

With defaults and 3 replicas you get maxSurge=1, maxUnavailable=0: Kubernetes adds one new Pod, waits until it is Ready, removes one old Pod, and repeats.

Watching it happen

bash
kubectl set image deploy/web nginx=nginx:1.28
kubectl annotate deploy/web kubernetes.io/change-cause="nginx 1.28 security fix"
kubectl rollout status deploy/web
kubectl get rs -l app=web

Sample output:

text
Waiting for deployment "web" rollout to finish: 1 out of 3 new replicas have been updated...
Waiting for deployment "web" rollout to finish: 2 out of 3 new replicas have been updated...
Waiting for deployment "web" rollout to finish: 1 old replicas are pending termination...
deployment "web" successfully rolled out
NAME             DESIRED   CURRENT   READY   AGE
web-6d8f9c7b5d   0         0         0       12m
web-7c5ddbdf54   3         3         3       45s

Simulating the steps

The model below follows the controller's two rules on each step:

  1. Scale up the new ReplicaSet as far as replicas + maxSurge total Pods allows.
  2. Scale down old Pods as far as keeping replicas - maxUnavailable available allows.

New Pods become Ready one step after they're created (as if their readiness probe takes a moment).

python · try it yourself
def rolling_update(replicas, max_surge, max_unavailable):
    old_ready, new_ready, new_starting = replicas, 0, 0
    step = 0
    print(f"step {step}: old={old_ready} new={new_ready}+{new_starting}(starting)")
    while old_ready > 0 or new_starting > 0:
        step += 1
        new_ready += new_starting            # Pods created last step are now Ready
        new_starting = 0
        # scale down old while keeping minimum availability
        min_available = replicas - max_unavailable
        can_remove = max(0, old_ready + new_ready - min_available)
        removed = min(can_remove, old_ready)
        old_ready -= removed
        # scale up new within the surge budget
        total = old_ready + new_ready
        can_add = min(replicas + max_surge - total, replicas - new_ready)
        new_starting = max(0, can_add)
        print(f"step {step}: -{removed} old, +{new_starting} new -> "
              f"old={old_ready} new={new_ready}+{new_starting}(starting) available={old_ready + new_ready}")

print("maxSurge=1, maxUnavailable=0 (default for 3 replicas)")
rolling_update(3, 1, 0)
print()
print("maxSurge=0, maxUnavailable=1 (no extra capacity needed)")
rolling_update(3, 0, 1)
maxSurge=1, maxUnavailable=0 (default for 3 replicas)
step 0: old=3 new=0+0(starting)
step 1: -0 old, +1 new -> old=3 new=0+1(starting) available=3
step 2: -1 old, +1 new -> old=2 new=1+1(starting) available=3
step 3: -1 old, +1 new -> old=1 new=2+1(starting) available=3
step 4: -1 old, +0 new -> old=0 new=3+0(starting) available=3

maxSurge=0, maxUnavailable=1 (no extra capacity needed)
step 0: old=3 new=0+0(starting)
step 1: -1 old, +1 new -> old=2 new=0+1(starting) available=2
step 2: -1 old, +1 new -> old=1 new=1+1(starting) available=2
step 3: -1 old, +1 new -> old=0 new=2+1(starting) available=2
step 4: -0 old, +0 new -> old=0 new=3+0(starting) available=3

Compare the two runs: with a surge you never drop below 3 available Pods but briefly need room for 4; with maxSurge: 0 you never exceed 3 Pods but temporarily serve with 2.

Note: Readiness probes are what make rolling updates safe. Without one, a Pod counts as Ready as soon as its container starts, even if the app inside isn't listening yet.

Rollout history and rollback

Every template change is a numbered revision. Old ReplicaSets (up to revisionHistoryLimit) are kept at 0 replicas.

bash
kubectl rollout history deploy/web
kubectl rollout undo deploy/web                  # back to the previous revision
kubectl rollout undo deploy/web --to-revision=1
kubectl rollout pause deploy/web                 # batch several edits, then
kubectl rollout resume deploy/web

Sample output:

text
deployment.apps/web
REVISION  CHANGE-CAUSE
1         <none>
2         nginx 1.28 security fix
3         nginx 1.29 (broken)

A rollback is just another rollout: the controller copies the old ReplicaSet's template back into the Deployment, and that template becomes the newest revision (its old revision number disappears from the history). This model keeps the history the same way:

python · try it yourself
history = {}          # revision -> template (image)
current = None
next_rev = 1

def rollout(image):
    global current, next_rev
    for rev, img in list(history.items()):
        if img == image:              # reusing an old template moves it to a new revision
            del history[rev]
    history[next_rev] = image
    current = next_rev
    next_rev += 1

def undo(to_revision=None):
    if to_revision is None:
        to_revision = sorted(history)[-2]          # the previous revision
    if to_revision not in history:
        print(f"error: unable to find specified revision {to_revision} in history")
        return
    rollout(history[to_revision])

for image in ["nginx:1.27", "nginx:1.28", "nginx:1.29"]:
    rollout(image)
print("history:", history, "current:", current)
undo()
print("after undo:", history, "current:", current)
undo(to_revision=2)                     # revision 2 was renumbered to 4
undo(to_revision=1)
print("after undo --to-revision=1:", history, "current:", current)
history: {1: 'nginx:1.27', 2: 'nginx:1.28', 3: 'nginx:1.29'} current: 3
after undo: {1: 'nginx:1.27', 3: 'nginx:1.29', 4: 'nginx:1.28'} current: 4
error: unable to find specified revision 2 in history
after undo --to-revision=1: {3: 'nginx:1.29', 4: 'nginx:1.28', 5: 'nginx:1.27'} current: 5

Failed rollouts

If new Pods never become Ready (bad image, crashing app), the rollout stalls. After progressDeadlineSeconds (default 600) the Deployment gets the condition Progressing=False with reason ProgressDeadlineExceeded. Kubernetes does not roll back automatically: you (or your CD tool) run kubectl rollout undo. Because of maxUnavailable, the old Pods keep serving in the meantime.

Test yourself

With 10 replicas and maxUnavailable: 25%, how many Pods may be unavailable?

  1. 2
  2. 3
  3. 2.5
  4. 25

Which setting lets an update proceed without ever running more than replicas Pods?

  1. maxSurge: 0
  2. maxUnavailable: 0
  3. replicas: 0
  4. revisionHistoryLimit: 0

A new version keeps crashing during a rollout. What does Kubernetes do by default?

  1. Rolls back automatically
  2. Stalls and reports ProgressDeadlineExceeded; you roll back
  3. Deletes the Deployment
  4. Replaces all Pods at once