Controllers and rollouts: reconciliation, ReplicaSets, and how a Deployment actually rolls

A rollout is a ReplicaSet dance: create the new, scale up under maxSurge, scale down under maxUnavailable, stop when readiness fails. Nothing rolls back on its own.

Read the briefing
About 8 min to read 7 drills

What to remember

  1. Deployment → ReplicaSet → Pod, by ownerReference. Debug at the level that has the events; the Deployment just shows counts.
  2. maxSurge and maxUnavailable set the blast radius. They decide how much of the fleet a bad version can reach before readiness stops it.
  3. A stuck rollout is usually readiness never going true. kubectl rollout status waits; describe the new ReplicaSet's pods to see why.
  4. Rollback is a redeploy of the previous spec. Which only works if the old build still runs against today's schema — expand, migrate, contract.
  5. Deleting a pod does not fix a controller's opinion. It will be recreated. Change the spec, not the symptom.

The big picture

Controllers are the loops that turn a declared object into running reality: they watch the API server, compare desired with actual state, and act to close the gap, forever. The Deployment controller is the one every interview reaches for, because a rolling update exposes the whole model in one place: two ReplicaSets scaled in opposite directions, bounded by maxSurge and maxUnavailable, paced by readiness, and undone by re-scaling a ReplicaSet that history kept around. Stuck rollouts, orphaned pods, and "why did nothing roll" questions all come back to these mechanics.

The mental model

Picture a thermostat, not a script. The Deployment says "3 replicas of template T"; a controller reads the room (which pods exist, which are Ready), nudges it toward the setpoint, and reads again. A rollout is two thermostats: the new ReplicaSet's setpoint climbs while the old one's falls, and the rules for how far each may move at a time are maxSurge and maxUnavailable. Readiness is the thermometer; ownerReferences are the wiring that says which thermostat owns which pod.

In depth

The reconcile loop, and why it is level-triggered

A controller is a loop, not a callback. It uses an informer to keep a local cache of the objects it owns, and every change to a watched object pushes the object's key (namespace/name) onto a work queue. A worker pops the key, reads the current desired state from the cache, reads the actual state (pods that exist, endpoints, a cloud load balancer), computes the difference, and issues the minimum API calls to close it. On error the key is requeued with exponential backoff; on success it is dropped. A periodic resync re-enqueues everything so nothing is forgotten.

That design is what "level-triggered" means: the reconcile acts on the level (the present state), not on the edge (the event that woke it). A missed event is harmless because the next reconcile of that key sees the same truth; a duplicated event just causes an extra no-op pass. The price is that every reconcile must be idempotent and must not assume it is the only writer: writes carry resourceVersion, and the API server rejects a stale update with 409 Conflict ("the object has been modified; please apply your changes to the latest version"), at which point the controller re-reads and tries again rather than clobbering someone else's change.

The built-in controllers (ReplicaSet, Deployment, Job, EndpointSlice, node lifecycle, garbage collector, and more) live in kube-controller-manager, which runs one active instance per cluster chosen by leader election on a Lease. When that process is unhealthy, writes still succeed but nothing converges: a deleted pod is not replaced, a scaled Deployment creates nothing. Check kubectl -n kube-system get lease kube-controller-manager (who holds it, when it was renewed), the component's logs, and the workqueue_depth and workqueue_queue_duration_seconds metrics when reconciliation feels slow rather than stopped.

Deployment, ReplicaSet, Pod: what actually rolls

A Deployment does not manage pods. It manages ReplicaSets, and each ReplicaSet manages pods that match its selector. The Deployment controller hashes the pod template (spec.template) and writes the hash into the ReplicaSet's name and into a pod-template-hash label on it and on its pods, so api-7c9d5f6b8 is "the ReplicaSet for template 7c9d5f6b8". A rollout is therefore two ReplicaSets being scaled in opposite directions: the new one up, the old one down, until the new one holds spec.replicas and the old one holds zero. Old ReplicaSets are kept at zero replicas, up to revisionHistoryLimit, and each carries a deployment.kubernetes.io/revision annotation.

The consequence people miss: only a change to the pod template creates a new ReplicaSet. Image, env, template labels, resources, probes, volumes: all roll. replicas, paused, revisionHistoryLimit, progressDeadlineSeconds, and the strategy itself do not; they change how the existing ReplicaSets are managed. That is why kubectl scale never shows up in kubectl rollout history, and why an HPA writing replicas and a manifest that also hard-codes replicas fight each other on every apply. Applying an unchanged manifest rolls nothing either, because the hash is the same.

What to look at: kubectl get rs -l app=<name> shows both ReplicaSets with DESIRED, CURRENT, and READY, which is the truthful view of a rollout; kubectl describe deployment lists OldReplicaSets and NewReplicaSet and the Progressing and Available conditions; kubectl rollout history deployment/<name> lists revisions (annotate changes with kubernetes.io/change-cause to make it useful). If two ReplicaSets both hold non-zero replicas after a rollout should have finished, the rollout is stuck or paused, not done.

How a rolling update advances, and what stops it

With strategy.type: RollingUpdate the controller is bounded by two numbers. maxSurge is how many pods may exist above replicas; maxUnavailable is how many may be unavailable below it. Both accept an integer or a percentage; surge rounds up and unavailable rounds down. For 10 replicas with maxSurge: 25% and maxUnavailable: 0, at most 13 pods exist and at least 10 must be available at every moment. The defaults are 25% and 25%, which means a default Deployment will take a quarter of its capacity down during a rollout.

What moves the rollout forward is readiness. The controller scales the new ReplicaSet up as far as surge allows, waits for those pods to become Ready (plus minReadySeconds if set), and only then scales the old ReplicaSet down by the amount the unavailability bound permits. A new pod that never becomes Ready therefore freezes the rollout at the bound. With maxUnavailable: 0 that freeze is a non-event for users: the old ReplicaSet still serves full capacity. With maxUnavailable: 100% and maxSurge: 0 the same bad image is a total outage, because the controller is allowed to delete everything first.

progressDeadlineSeconds (default 600) is a reporting knob, not a control knob. When the Deployment makes no progress for that long, the controller sets the Progressing condition to False with reason ProgressDeadlineExceeded, and kubectl rollout status exits non-zero with exceeded its progress deadline. Nothing is rolled back and the crashing pods keep crashing; a human or a CI gate has to act. strategy.type: Recreate is the other option: delete all, then create all, acceptable only for singletons that cannot run two versions at once.

Rollback, history, pause, and restart

kubectl rollout undo deployment/<name> (optionally --to-revision=N) copies the chosen old ReplicaSet's pod template back into the Deployment. Because that is a template change, it is itself a new rollout: the old ReplicaSet is scaled up under the normal surge and unavailability bounds, the current one is scaled down, and the revision counter moves forward. The rollback is only possible while that ReplicaSet still exists, which is what revisionHistoryLimit (default 10) controls; setting it to 0 deletes old ReplicaSets immediately and turns undo into error: no rollout history found.

kubectl rollout pause stops the controller from acting on template changes so you can apply several edits (image plus env plus resources) and resume them as one rollout instead of three. kubectl rollout restart stamps kubectl.kubernetes.io/restartedAt into the template annotations, which changes the hash and produces a fresh ReplicaSet with the same image: a controlled way to recycle pods that respects the strategy, unlike deleting pods by hand.

Two operational caveats. First, in a GitOps setup (Argo CD, Flux) undo edits the live object, and the reconciler will revert it to what git says within minutes; the durable rollback is a git revert of the image tag, and undo is at most a stopgap. Second, undo restores the template, not the world around it: a ConfigMap or Secret edited in place is not versioned by the Deployment, so a rollback of the image can still run against the new config. Immutable, hash-suffixed ConfigMaps fix that by making config part of the template, so config and image roll and roll back together.

Ownership, garbage collection, and orphans

Every pod created by a ReplicaSet carries metadata.ownerReferences pointing at the ReplicaSet's UID with controller: true; the ReplicaSet in turn points at the Deployment. This chain is what the garbage collector walks: delete the owner and the dependents are deleted too. kubectl delete defaults to background cascading (owner goes first, the GC removes dependents), --cascade=foreground deletes dependents first and holds the owner with a foregroundDeletion finalizer until they are gone, and --cascade=orphan removes the owner and strips the ownerReferences, leaving the dependents alive with nobody watching them.

Orphaned pods are the failure mode. They keep serving, so nothing looks wrong, until a node drain, an eviction, or a crash removes one and no controller replaces it. Two weeks later there are pods with mixed images that no rollout can touch. Find them with kubectl get pods -A -o json | jq -r '.items[] | select(.metadata.ownerReferences == null) | .metadata.namespace + "/" + .metadata.name' and alert on the count in production namespaces.

Recovery uses the same mechanism in reverse. A ReplicaSet adopts any pod that matches its selector and has no controller owner, so recreating the Deployment with the original selector reclaims the orphans and then rolls the ones whose template hash differs, at the configured pace. Two rules keep adoption safe: spec.selector on an apps/v1 Deployment is immutable, so pick it once; and two controllers with overlapping selectors will fight over the same pods, creating and deleting endlessly, which is why a selector should be as specific as the labels you put on the template.

Myths and facts

Myth: Any change to a Deployment creates a new ReplicaSet and a rollout.

Fact: Only a change to spec.template does. Scaling, pausing, and history or deadline edits act on the existing ReplicaSets, and an unchanged manifest rolls nothing because the template hash is identical.

Myth: When progressDeadlineSeconds is exceeded, Kubernetes rolls the Deployment back.

Fact: It only sets Progressing=False with reason ProgressDeadlineExceeded and makes rollout status exit non-zero. The rollback is a human or CI decision.

Myth: A failed rollout means the service is down.

Fact: With maxUnavailable 0 the old ReplicaSet keeps serving at full capacity while the new one is stuck; the outage only happens if the unavailability bound allowed old pods to be removed first.

Myth: Controllers react to events, so a missed event means a missed action.

Fact: Reconciliation is level-triggered: each pass reads current state, so a missed or duplicated event is corrected by the next reconcile or the periodic resync. That is also why reconcilers must be idempotent.

Myth: kubectl rollout undo returns you to the previous revision number.

Fact: It copies the old template into the Deployment, which creates a new revision. The pods come from the old ReplicaSet, but history moves forward, and a GitOps reconciler will revert the undo unless git changes too.

Myth: Deleting a Deployment with --cascade=orphan is a safe way to keep pods running during an incident.

Fact: It strips ownerReferences, so nothing replaces a pod that dies or is drained, and no rollout can reach them. Pause or scale instead.

How pros do it

  • Serve traffic with maxUnavailable: 0 and a modest maxSurge, and confirm the cluster has surge headroom (requests, quotas) or the rollout will stall Pending instead of rolling.
  • Alert on Deployments with Progressing=False and fail CI on a non-zero kubectl rollout status; a stuck rollout is silent otherwise.
  • Keep revisionHistoryLimit small but never zero (3 to 5); it is the only thing that makes rollout undo possible.
  • When an HPA owns replicas, do not set replicas in the manifest (or have your GitOps tool ignore that field), so applies do not fight the autoscaler.
  • Never orphan a controller in production; use kubectl rollout pause, scale, or undo, and alert on pods without ownerReferences.
  • Make configuration part of the template (immutable, hash-suffixed ConfigMaps) so a rollback of the image is also a rollback of its config.
  • Annotate rollouts with kubernetes.io/change-cause or drive them from git so rollout history says what changed and why.

Questions people ask

My rollout has said 'Waiting for deployment rollout to finish: 1 out of 4 new replicas have been updated' for ten minutes. Am I down?

Answer with the ReplicaSets: not if maxUnavailable is 0, because the old ReplicaSet still has its pods Ready and serving. Say you would run kubectl get rs -l app=; if the old one shows full READY you have time to read the new pod's logs, then decide between rollout undo and a fix. Looking at ReplicaSets before pods is the habit they are checking for.

Does progressDeadlineSeconds roll back for me?

Say no, clearly: it flips the Progressing condition to False and makes rollout status exit non-zero, and Kubernetes itself never rolls back. Then say what you do with that: a CI pipeline keys an undo off the exit code, and you alert on Progressing=False.

I applied the same manifest and nothing rolled. How do I force new pods?

Say kubectl rollout restart deployment/: it adds a restartedAt annotation to the template, so the hash changes and a normal bounded rollout replaces the pods. Then say why not the alternative: deleting pods by hand bypasses the surge and unavailability bounds.

Why did kubectl rollout history not change after I scaled the Deployment?

Say that scaling does not touch the pod template, and revisions are keyed on the template hash, so the same ReplicaSet was scaled and no rollout happened. Point at the evidence: kubectl get rs shows one ReplicaSet with a new DESIRED count. The rule to state is 'only template changes roll'.

Why does my controller get the object has been modified; please apply your changes to the latest version?

Name it: a 409 Conflict from optimistic concurrency; the object's resourceVersion changed between your read and your write. Then say the right response: re-read and retry, because it is the mechanism that stops two writers from clobbering each other, and a well-written reconciler expects it.

Why do I see pods with no controller after an incident?

Say someone deleted a Deployment or ReplicaSet with --cascade=orphan, or changed a selector so the pods no longer match. Then give the recovery: recreate the Deployment with the original selector and it adopts them by label match. Mention that you alert on unowned pods in production namespaces.

How many old ReplicaSets are kept, and can I have too many?

revisionHistoryLimit, default 10, kept at zero replicas, and they cost almost nothing. Then say where the danger actually is: setting it to 0 and losing the ability to undo. 3 to 5 is a common choice, and saying why is better than saying the number.

Further reading

Drills · 7

Answer in your head, or out loud, before you reveal. Mark each one: "Again" brings it back, "Got it" counts on your desk.

1 Pick the strongest answer

Walk me through a rolling update of a 10-replica Deployment with maxSurge: 25% and maxUnavailable: 0. How many pods can exist at any moment, and what actually moves the rollout forward?

  1. The rollout advances on a fixed timer regardless of readiness. Readiness is the signal; progressDeadlineSeconds only reports a stuck rollout, it does not drive it.
  2. At most 10 plus 25% (rounded up) pods exist and never fewer than 10 are available; the rollout advances only as new pods pass their readiness probes. maxSurge caps extra pods, maxUnavailable: 0 forbids dropping below desired, and readiness is the gate that lets the old ReplicaSet scale down.
  3. Old pods are deleted first, then new pods created, 25% at a time. With maxUnavailable 0 the controller must create and wait for readiness before removing anything.
  4. maxSurge applies to nodes, so 25% more nodes are provisioned. Surge is about pods in the Deployment, not cluster nodes.
In short

At most 25% extra pods exist, none of the desired pods may be unavailable, and the rollout moves only as new pods become Ready.

Why

Rollouts are a dance between two ReplicaSets bounded by surge and unavailability, paced by readiness. A pod that never becomes Ready freezes the rollout at the bound, which is the safe failure: capacity is preserved and the operator sees progressDeadlineSeconds exceeded rather than an outage.

The common mistake

Saying the rollout advances on a timer, or that progressDeadlineSeconds rolls it back. Readiness drives it and nothing rolls back on its own; the deadline only flips a condition.

Read the docs

2 Answer out loud

What is a Kubernetes controller, really? Why do we say it is level-triggered rather than edge-triggered, and what does that force you to do when you write one? Three to five sentences.

In short

A strong answer says a controller acts on the current state, not on the event, so it must be idempotent and tolerate missed or repeated events.

What a strong answer does
  • mechanism: Reconciles on the current state, not on the event that woke it; missed or duplicated events are harmless because the next reconcile sees the same truth; uses informers/caches and re-queues on error.
  • implications: Idempotent, tolerant of stale caches (compare resourceVersion or use optimistic concurrency), rate-limited requeue with backoff, and never assumes it was the only actor.
  • communication: Definition, the level/edge distinction in one crisp sentence, three concrete implications.
Why

This question separates people who have used controllers from people who have written or debugged them. The level-triggered property is why Kubernetes survives missed events, and idempotency is its price.

The common mistake

Describing a controller as a callback that reacts to events. A missed event must be harmless, which is only true if each pass acts on the current state rather than on the event that woke it.

3 Pick the strongest answer

You run kubectl scale deployment api --replicas=5 on a Deployment at 3. Is that a rollout? Does a new ReplicaSet appear?

  1. No, because scaling is handled by the HorizontalPodAutoscaler. Manual scaling writes replicas directly; HPA is optional and would fight a manual value.
  2. No. Replica count is not part of the pod template, so the existing ReplicaSet is scaled to 5; no rollout happens. A new ReplicaSet is created only when the pod template hash changes (image, env, labels, resources); replicas is a Deployment-level knob passed down.
  3. Yes, every spec change creates a new ReplicaSet and a rollout. Only template changes roll; scaling, paused, and revisionHistoryLimit edits do not.
  4. Yes, but the old ReplicaSet is deleted immediately. Old ReplicaSets are retained (scaled to 0) up to revisionHistoryLimit so you can roll back.
In short

No, scaling does not change the pod template, so the same ReplicaSet is scaled to 5 and no rollout happens.

Why

The Deployment controller hashes the pod template into the ReplicaSet name and label; the same template means the same ReplicaSet. That is why kubectl rollout history does not change on scaling and why an HPA and a hard-coded replicas field can fight each other.

Read the docs

4 Read the output

The rollout is stuck. Is the service down right now, and what is your safest immediate move?

$ kubectl rollout status deployment/api
Waiting for deployment "api" rollout to finish: 1 out of 4 new replicas have been updated...
error: deployment "api" exceeded its progress deadline

$ kubectl get rs -l app=api
NAME             DESIRED   CURRENT   READY   AGE
api-7c9d5f6b8    4         4         4       9d
api-8f6d4c9b2    1         1         0       11m

$ kubectl get pods -l app=api,pod-template-hash=8f6d4c9b2
NAME                   READY   STATUS             RESTARTS      AGE
api-8f6d4c9b2-p9x2m    0/1     CrashLoopBackOff   6 (65s ago)   11m
  1. Scale the Deployment to 8 to make room for the new pods. More replicas of a crashing template do not become Ready either.
  2. The service is down because the rollout failed. The old ReplicaSet shows 4/4 ready; traffic is served.
  3. All four old pods are still serving; the new revision is stuck at one crashing pod. kubectl rollout undo deployment/api returns to the old ReplicaSet with no capacity loss. maxUnavailable protected capacity: the old ReplicaSet still has 4 ready. Undo scales the previous ReplicaSet back and the crashing one to zero.
  4. Delete the crashing pod so the controller retries the rollout. The ReplicaSet will recreate an identical crashing pod; the template is the problem.
In short

The old pods still serve, the new pod is crashing, and kubectl rollout undo restores the old ReplicaSet with no capacity loss.

Why

Read the two ReplicaSets: the old one still holds capacity, the new one cannot get a pod Ready. A stuck rollout with maxUnavailable: 0 is a non-outage by design; the right move is to undo, then debug the new image with the pod's logs. Interviewers check that you look at ReplicaSets, not just pods.

Read the docs

5 Find what's broken

This rolled out a broken image last week and the team could neither avoid the outage nor roll back. Which two lines made that so?

apiVersion: apps/v1
kind: Deployment
metadata:
  name: payments
spec:
  replicas: 6
  revisionHistoryLimit: 0
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 0
      maxUnavailable: 100%
  selector:
    matchLabels: { app: payments }
  template:
    metadata:
      labels: { app: payments }
    spec:
      containers:
        - name: payments
          image: registry.example.com/payments:4.2.0
          readinessProbe:
            httpGet: { path: /ready, port: 8080 }
In short

revisionHistoryLimit 0 removes the rollback history, and maxUnavailable 100% lets every pod go down at once.

What's broken
  • Line 7: revisionHistoryLimit: 0 deletes old ReplicaSets immediately, so kubectl rollout undo has nothing to roll back to.
  • Line 12: maxUnavailable: 100% with maxSurge: 0 lets the controller take every pod down at once before the new ones are Ready: a guaranteed outage on any bad image.
Why

Two settings that look like optimizations and are actually removals of safety: history is what makes undo possible, and the unavailability bound is what makes a rollout a rollout rather than a restart. Interviewers like this because both defaults are safe and someone had to change them on purpose.

Read the docs

6 Quick recall

What makes kubectl rollout undo possible after a bad deploy: which Deployment field keeps the old ReplicaSets around?

In short

revisionHistoryLimit controls how many old ReplicaSets are kept for rollback.

Accepted

revisionHistoryLimit · revision history limit · spec.revisionHistoryLimit

Why

revisionHistoryLimit (default 10) keeps old ReplicaSets at zero replicas so kubectl rollout undo can re-scale one.

7 Scenario: what do you do next?

A team deleted a Deployment with kubectl delete deployment web --cascade=orphan during an incident "to keep the pods running". Two weeks later there are 14 web-* pods with mixed image versions, nothing manages them, and a node drain just took several down with no replacement.

Step 1. What exactly is the state, and how do you confirm it?

  1. The pods and probably the old ReplicaSet have no live owner: check kubectl get rs -l app=web and the pods' ownerReferences; nothing will recreate or roll them. Orphaning removes the ownerReferences chain; confirming what still exists tells you what you can adopt versus recreate.
  2. Delete all web pods to clean up. That is the outage; nothing recreates them.
  3. Roll the nodes to force the pods elsewhere. Orphaned pods are not rescheduled anywhere; they just die.
  4. Restart kube-controller-manager to make it re-adopt them. Controllers adopt pods only when a ReplicaSet with a matching selector exists; restarting nothing changes ownership.

Step 2. The ReplicaSet was deleted too; only the 14 pods remain with label app=web. What is the safe path back to a managed state?

  1. Convert the pods to a StatefulSet. Wrong controller for a stateless web tier; and StatefulSets do not adopt arbitrary pods.
  2. Re-create the Deployment with the same selector and the desired template; the new ReplicaSet adopts matching pods (their labels match) and the controller then rolls the mismatched ones to the declared image at the configured pace. Adoption via selector match is by design; it converts chaos back into declared state without a hard cut, and the rollout bounds protect capacity.
  3. Create a new Deployment with a different label and delete the old pods after. Works but doubles capacity briefly and loses the graceful adoption; acceptable, not preferred.
  4. Manually pin each pod to the right image with kubectl edit. Pod images are mostly immutable (except via kubectl set image on the pod, which does not fix ownership), and it leaves them unmanaged.

Step 3. For the postmortem: what prevents the next 'orphan during an incident'?

  1. A runbook step that says how to pause a rollout (kubectl rollout pause) or scale instead of orphaning, plus an alert on pods without an owner in production namespaces. Gives people the safe tool for the moment they reached for the unsafe one, and detects the failure mode if it recurs.
  2. Document that orphaning is bad. A reminder, not a mechanism.
  3. Remove kubectl access from the team. Blame-shaped; it removes the ability to respond to incidents.
In short

Check what is left and its ownerReferences, recreate the Deployment with the same selector so it adopts the pods, then alert on unowned pods.

Why

ownerReferences are the spine of reconciliation and garbage collection; cutting them leaves pods that nothing watches. Recovery uses the same mechanism in reverse: a controller adopts pods that match its selector and are unowned. Interviewers like this because the fix is understanding, not a command.

Read the docs

Next lesson Pods: phases, probes, and graceful termination
Drill · Controllers and rollouts
0:00

Loading…