Back to Terraform

Workloads and Rollouts: Deployments, Probes, Jobs and Scaling

November 6, 2026 Wasil Zafar 25 min read

Configure desired workloads while treating controller convergence and application health as separate evidence

Table of Contents

  1. Choose Deployment, Job or StatefulSet by Lifecycle
  2. Keep Labels, Selectors and Image Digests Stable
  3. Distinguish Startup, Readiness and Liveness
  4. Define Resource Requests and Scaling Ownership
  5. Observe a Healthy and Failed Rollout

Choose Deployment, Job or StatefulSet by Lifecycle

Three controllers answer one question: does the work ever end? A Deployment reconciles a population forever, a Job converges on a count of successful completions, and a StatefulSet keeps a stable identity for each member. Terraform declares all three the same way, but each controller has a different definition of done.

Reconciliation is a level, not an event. A Deployment compares the desired replica count with the ReplicaSets and pods that exist, then creates or deletes until the numbers agree. Your apply sets the target once; every later correction is controller work that happens whether or not Terraform is running.

A Job converges on completions, not on liveness. You declare how many successful pod exits count as done, how many pods may run at once, and how many retries are allowed. When the succeeded count reaches the target, the Job reports Complete and stops creating pods, which is why it suits migrations, backfills and one-shot reports.

Job specs are mostly immutable, and that is a feature. Changing the pod template does not edit a finished run; Terraform replaces the object and the controller starts a new one. A rerun is a new Job with its own generation, not a retry of the old evidence, so keep the run identifier where a reviewer can find it.

A CronJob adds a clock and a missed-run policy. It creates Jobs on a schedule, and the interesting settings concern the previous run still going. The default concurrency policy allows overlap, which is fine for independent reports and wrong for anything that writes the same rows twice.

A Job guarantees at-least-once execution, not exactly-once effects. The controller retries a failed pod, and a pod can fail after its side effect has landed. Make the work idempotent with an upsert keyed by the unit of work, or a transaction that can be replayed, so a retry is harmless.

A completion count is not a deduplication record. Two runs writing the same rows are not prevented by the first having succeeded. The concurrency policy limits overlap, but the durable guarantee belongs in the job's own write path.

A StatefulSet trades flexibility for identity. Each pod gets an ordinal name, a stable network name through its governing Service, and its own PersistentVolumeClaim. Updates proceed in reverse ordinal order and wait for each pod to become ready, because replacing all members at once would defeat the reason for choosing it.

Figure 1 turns that question into a decision path and names the status field that answers it.

Choose Deployment, Job or StatefulSet by Lifecycle
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    Q["A unit of work arrives"] --> L{"Does it ever finish?"}
    L -->|"no, it runs indefinitely"| I{"Are the members interchangeable?"}
    I -->|"yes, any pod will do"| D["Deployment
keeps a replica count"] I -->|"no, each keeps identity"| S["StatefulSet
ordinal name and claim"] L -->|"yes, one run"| J["Job
completions reached"] L -->|"yes, on a schedule"| C["CronJob
creates Jobs"] D --> DE["Evidence: availableReplicas
and Available condition"] S --> SE["Evidence: readyReplicas
and ordered update"] J --> JE["Evidence: Complete condition
and succeeded count"] C --> CE["Evidence: active Jobs
and last schedule time"] D -.->|"selector edited later"| X1["Immutable field
replacement, not rollout"] J -.->|"completion wait disabled"| X2["Apply returns before
the run has finished"] C -.->|"overlap allowed"| X3["Two runs write
the same rows"] classDef primary fill:#132440,color:#ffffff,stroke:#0b172b; classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a; classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f; classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420; classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f; class Q,L,I primary; class D,S,J,C secondary; class DE,SE,JE,CE ok; class X1,X2,X3 danger;

Figure 2 draws the same decision as a boundary: Terraform writes a spec, a controller writes status, and only one of the three end states is a completion.

Terraform declares a workload object, a controller reconciles pods, and the end state differs by controller A navy column holds four declared objects, a blue boundary holds the controller loop, and a teal column shows three end states: a steady replica count, ordinal identity with claims, and a completion count. An amber band separates desired spec from observed status, and a crimson note marks the failed assumption that a template edit reruns a Job. One declared object, three different end states Terraform writes spec Deployment replica count StatefulSet ordinal template Job completion target CronJob schedule and policy Spec is reviewed in the plan. Controller writes status Observe list pods, read counts Act create, delete, retry Report conditions and counts This loop runs without Terraform being invoked. Observed end state Steady population available equals desired Stable identity name and claim per ordinal Completion count succeeded reaches target A Job has no replica count. A Deployment has no finish line. Desired spec and observed status are two documents. Neither contains an HTTP response. Editing a finished Job template starts a new run. It does not retry the old one.

Table 1 puts the differences side by side, including which status field a reviewer should read.

ControllerWhat it converges onWhat counts as doneIdentity and storageTerraform resource
Deploymenta replica count across interchangeable podsnever; it keeps the countrandom pod names, no per-pod claimkubernetes_deployment_v1
StatefulSetan ordered set of named podsnever; it keeps the setordinal name, stable network name, claim per ordinalkubernetes_stateful_set_v1
Joba number of successful pod exitssucceeded count reaches completionsunique pod per attempt, no stable namekubernetes_job_v1
CronJoba schedule that creates Jobseach Job completes; the schedule continuesJobs carry the identity, pods do notkubernetes_cron_job_v1

The completion column matters more than the resource name. Terraform resource names are easy to copy; whether a clean plan means the work happened depends on the third column. A Job that Terraform created successfully can still be failing on its fourth retry.

Keep Labels, Selectors and Image Digests Stable

A release has three separable artifacts. An image build produces a digest, a pod template references that digest, and a rollout strategy decides how pods carrying the new template replace pods carrying the old one. Collapsing the three into one "deploy" step is what makes a rollback require a rebuild.

The image build belongs to CI, not to apply. Build, test, scan and push happen in a pipeline that can fail without leaving a half-created workload behind. Terraform records which digest the cluster should run, which is what makes the build reusable across clusters.

A digest is a release; a tag is a pointer. A pod template naming a moving tag can be unchanged while the bytes behind it change, so no new ReplicaSet is created and no rollout occurs. Pin the digest in the template, keep the readable tag in an annotation, and the plan can tell the two apart.

The pod template is the rollout trigger. Any change inside it, whether image, environment, resources or probe timings, changes the template hash and creates a new ReplicaSet. Changing the replica count or the strategy does not: the first scales existing pods, the second only governs the next replacement.

The selector is the immutable joint. A Deployment's label query cannot be edited after creation, so the provider plans a replacement rather than an update. Keep the selector to stable identity labels such as application and component, and put release labels in the template where they can change freely.

A version label in the selector turns every release into a replacement. The new selector matches nothing that exists, so the controller cannot adopt the old pods and Terraform deletes and recreates the object. That is not a rollout, and it is the operation that produces a visible gap in service.

Renaming is the same kind of change. A new Deployment name is a delete and a create, not an edit; treat it as a migration with both objects alive long enough to keep endpoints, not as a field change inside a routine release.

Two percentages decide the shape of a rolling update. Surge is capacity added above the desired count, and unavailability is capacity removed below it; they cannot both be zero. Percentages round up for surge and down for unavailability, which is why a single-replica Deployment with defaults briefly runs two pods.

Recreate is the honest choice for some workloads. A singleton holding an exclusive lock, or a migration that cannot run beside the old version, needs the old pods gone first. Choosing it accepts a gap, and that gap should be a written decision rather than a discovery during a release.

Three timers bound the strategy. The progress deadline marks a stalled rollout failed, though it does not roll it back, the minimum ready time keeps a briefly ready pod from counting as available, and the revision history limit decides how many old ReplicaSets remain for an undo.

Figure 3 follows one template change from CI to a completed rollout and marks where each failure branch starts.

Keep Labels, Selectors and Image Digests Stable
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    A["CI builds and pushes an image"] --> B["Immutable digest
repository at sha256"] B --> C["Pod template references the digest"] C --> D{"Did the template hash change?"} D -->|"no, only the tag moved"| X1["No new ReplicaSet
old pods keep serving"] D -->|"yes"| E["New ReplicaSet created"] E --> F{"Surge capacity available?"} F -->|"no"| X2["New pods Pending
rollout stops advancing"] F -->|"yes"| G["New pod starts"] G --> H{"Readiness probe passes?"} H -->|"no"| X3["Pod stays out of endpoints
progress deadline expires"] H -->|"yes"| I["Available for the minimum ready time"] I --> J{"Old pods within the unavailability budget?"} J -->|"yes"| K["Old ReplicaSet scales down"] J -->|"no"| L["Hold until capacity allows"] L --> K K --> M["Rollout complete"] C -.->|"selector edited"| X4["Immutable field
replacement, not rollout"] classDef primary fill:#132440,color:#ffffff,stroke:#0b172b; classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a; classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f; classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420; classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f; class A,C primary; class B,D,E,F,G,H,I,J,K,L secondary; class M ok; class X1,X2,X3,X4 danger;

The provider waits by default, and that wait is a convergence claim. With the default rollout wait enabled, apply blocks until the controller reports the Deployment available or the operation times out. Disabling it returns as soon as the API accepts the object, which is useful for pipelines that verify separately, and misleading for anyone who reads a zero exit status as a release.

Distinguish Startup, Readiness and Liveness

Three probes answer three different questions. A startup probe asks whether initialization has finished, a readiness probe asks whether this pod should receive traffic now, and a liveness probe asks whether the process should be restarted. A probe pointed at the wrong question produces either an outage or a restart loop.

Startup probes exist to protect slow initialization. While a startup probe is running, the other two are suppressed, so a container that needs ninety seconds to warm a cache is not killed at ten. The budget is the failure threshold multiplied by the period, and it should come from observed start time plus a margin, not from a copied default.

A startup budget that is too short looks like a broken image. The container is restarted before it ever becomes ready, the restart resets the clock, and the event stream fills with back-off warnings while the application would have started fine. Before changing the image, compare the probe budget with the slowest observed start.

A readiness failure removes a pod from endpoints without restarting it. That is the right response to a warm-up that has not finished or a process that should stop receiving new requests. It is also why readiness must test the ability to serve, not the health of every downstream service.

A readiness probe that checks everything can remove the whole fleet. If every pod reports unready because one shared database is slow, the Service has no endpoints and a partial degradation becomes a total one. Reserve readiness for dependencies without which this pod cannot answer at all.

A liveness failure restarts the process, so its test must be cheap and local. Checking a downstream in a liveness probe converts a brief dependency outage into a rolling restart of healthy pods. A process that can still answer its own health endpoint, even while degraded, should not be killed.

Thresholds turn a probe into a time budget. The failure threshold times the period is how long a bad state is tolerated, and the timeout must stay below the period so checks do not overlap. Readiness usually wants a lower failure threshold than liveness, because leaving endpoints is reversible and restarting is not.

Probes also decide when a rollout is finished. The Deployment counts a pod as available only after readiness passes and the minimum ready time elapses, so a workload with no readiness probe is declared rolled out as soon as the container starts. That is the most common way a green apply hides an application that cannot serve.

Figure 4 places the three probes on one container timeline and shows the restart loop that a missing startup budget creates.

Startup, readiness and liveness probes on one container timeline with a restart-loop failure path A startup probe runs from container start to ninety seconds with a budget of failure threshold times period. Readiness stays false until that succeeds, then admits the pod to endpoints. Liveness is suppressed during startup, then runs continuously. A crimson lower path shows a liveness probe with a ten second budget restarting the container every ten seconds during a ninety second start. Three questions, one timeline startup budget = threshold x period initialization done readiness not in endpoints receives traffic while ready liveness suppressed during startup restarts the process on failure 0s 90s steady state time Without a startup probe: liveness with a ten second budget start restart restart restart the application never reaches ninety seconds, so a healthy image looks like a crash loop. Readiness gates traffic. Liveness restarts. Startup buys time for both. A pod removed from endpoints is still running. A restarted pod loses its warm state.

A dedicated probe endpoint is part of the application contract. Reusing the heaviest request path as a liveness check adds load and couples restart behavior to unrelated code. A small handler that proves the event loop is alive is enough; readiness can be slightly richer because it only changes routing.

Graceful termination is a probe problem too. A pod that stops accepting requests only when it exits drops traffic while readiness still says ready. Marking unready first, then draining within the grace period, is what lets a rollout remove old pods without resets.

Define Resource Requests and Scaling Ownership

Requests are the scheduler's contract and the autoscaler's denominator. A container without a CPU request is scheduled on a best-effort guess, and its CPU utilization has no percentage to compute because the divisor is missing. That single omission is the most common reason an autoscaler reports an unknown metric instead of scaling.

Limits are enforcement, not reservation. A CPU limit throttles the container when it exceeds the quota, and a memory limit ends the process when it cannot allocate. Setting request and limit equal for every resource gives predictable scheduling and a Guaranteed quality of service, at the cost of less room to burst.

One field, one writer. Terraform owns the pod template, which contains requests and limits, and the autoscaler object, which contains the lower and upper bounds. The autoscaler owns the replica count it writes to the target, so a Deployment that also declares a replica count has two writers for one field.

The resulting loop is easy to recognise. Every apply resets the count, the autoscaler measures load and moves it back, and the next plan reports drift again. Nothing is broken in either system; the ownership model is simply contradictory.

Leave the replica count out, or ignore it deliberately. When an autoscaler targets a Deployment, let the autoscaler be the only author of that field. If a count must stay for bootstrap reasons, add a lifecycle rule that ignores later changes and verify the behavior with a refresh.

Requests also bound the maximum useful replica count. The autoscaler can only add pods that fit somewhere, so a maximum whose per-pod request cannot fit on any node leaves the extra pods Pending. Pending pods are the evidence that the arithmetic was never checked.

The percentage target is relative to requests, not to capacity. Lowering a request raises reported utilization without any change in real load, which can trigger a scale-up that makes the service slower. Request values are therefore a scaling input, and changing them recreates pods.

A rollout and a scale-up can run at the same time. They write different fields, so the controllers do not conflict, but they compete for the same headroom. A surge pod that cannot be scheduled stops the rollout even though the autoscaler is working correctly.

Minimum replicas are an availability decision, not a performance one. A floor of one means every rollout and every node drain has a moment with no spare capacity. Set the floor from the failure you intend to survive, and let the utilization target handle the daily curve.

A disruption budget constrains eviction, not surge. It protects voluntary removals during drains, but it does not make a rolling update keep capacity. A protective-looking budget can coexist with a surge setting that still empties the Service.

Figure 5 contrasts the ownership model that converges with the one that oscillates.

Two scaling ownership models: one writer per field compared with Terraform and the autoscaler both writing replicas The left panel shows Terraform owning requests and autoscaler bounds while the autoscaler owns the replica count, with the scheduler reading requests. The right panel shows Terraform and the autoscaler both writing replicas, so each apply resets the count and the autoscaler moves it back. Who writes the replica count? One writer per field Terraform requests, limits, autoscaler bounds Autoscaler writes replicas within the bounds Scheduler reads requests Deployment one replica field Plan is clean after a manual scale. Utilization has a denominator. Two writers, one field Terraform declares replicas on every apply Autoscaler rewrites replicas on every metric read Deployment replica field apply resets, autoscaler restores Every plan proposes a change, and every apply starts a reshuffle. The autoscaler divides usage by requests. No request means no percentage. A rollout and a scale-up write different fields. They still compete for node capacity.

The scaling formula is a ratio, and it is rounded up. The autoscaler multiplies the current count by the ratio of observed to target usage, then clamps the result between the minimum and maximum. That is why a target of 60 percent means "sixty percent of requests", not "sixty percent of a node", and why a missing request breaks the calculation.

Stabilization windows are part of the release policy. A scale-down window that is shorter than the traffic lull produces a resize on every dip, and a scale-up policy that is too aggressive turns a brief spike into a fleet expansion. Both live in the autoscaler object, where Terraform can review them beside the bounds.

Verify ownership with a refresh, not with an argument. Scale the target by hand, run a plan, and read whether Terraform proposes to undo it. A clean plan proves the field is left alone; a proposed change proves two writers still exist, whatever the configuration comments claim.

Observe a Healthy and Failed Rollout

Two successes, two different claims. An apply that exits zero proves the API accepted the objects and, with the rollout wait enabled, that the controller reported availability. It does not prove the application returns a correct answer, because no request has been made yet.

Acceptance needs a request. A rollout that reaches available replicas proves the controller counted pods as available, but the release is accepted only when a real request returns the expected result. Keep that check outside the Deployment's status, because the controller has no opinion about response bodies.

Bounded waits keep a stuck rollout from hanging a pipeline. The provider wait has a timeout, the controller has a progress deadline, and the command-line status check accepts one of its own. A rollout with none of these keeps a pipeline occupied until a human notices.

Failure evidence is specific to the stage. An image that cannot be pulled produces pull errors and no container start, a readiness probe that never passes produces a running pod outside endpoints, and an unschedulable surge pod produces a Pending pod with capacity events. Read the stage first to avoid a detour through application logs.

Rollback has two paths with different consequences. Reverting the image digest and applying is the Terraform-native path: state, plan and cluster agree afterwards. Undoing the rollout in the cluster is faster, but it changes an object Terraform believes it owns, so the next plan proposes to re-apply the version you just escaped.

A rollback is a rollout too. The old template still has to pass readiness, still respects the surge budget, and still needs a progress deadline. Rehearsing it is part of releasing the forward change, which is why the revision history limit should keep the previous version addressable.

The lab below runs a healthy rollout, induces a failure at the image stage, and recovers by reverting configuration rather than by editing the cluster.

Lab

Observe a Healthy and Failed Rollout

Execution status: design-only. The procedure is written for Terraform CLI 1.17.1 with hashicorp/kubernetes 3.5.0 against a disposable namespace, but this article does not claim the commands were run. Nothing here creates billable infrastructure beyond the cluster you already have.

Prerequisites. A reachable cluster, a kubeconfig context you can safely write to, a namespace from the previous part, and permission to create Deployments and read pods. Use two replicas so surge and unavailability are both observable.

  1. Apply the Deployment with a pinned image digest, a readiness probe, and the provider's default rollout wait. Confirm a zero exit and two available replicas, then record the revision with kubectl rollout history.
  2. Run kubectl rollout status with a two-minute timeout. Expect a completed rollout, which is convergence evidence rather than acceptance evidence.
  3. Send one request through a port-forward and record the version marker with the digest, so the response ties to a specific release.
  4. Change the image to a digest that does not exist and apply again. Expect a non-zero exit after the rollout wait expires, because the new pods never become available.
  5. Inspect pod events. Expect pull errors on the new ReplicaSet with healthy old pods still serving, proving the rollout stalled before removing capacity.
  6. Revert the digest in configuration and apply. Confirm the rollout status completes and the response marker matches step 3, so both convergence and acceptance are re-proven.
EvidenceWhere it comes fromWhat it provesWhat it cannot prove
Apply exit statusTerraformobjects accepted, rollout reached availabilitythat a request returns the right body
Rollout statusDeployment conditionsnew ReplicaSet reached the desired countthat readiness tests the real serving path
Pod readinessPod conditions and endpointsthis pod may receive trafficthat the process is not degraded
Response markerone real requestthe release answers as expectedthat every route behaves the same

Expected observation. The healthy release produces a zero exit and a matching response marker; the broken digest produces a stalled rollout with the old pods still serving; reverting the configuration restores both the digest and the response without any manual cluster edit. If the broken release instead removed capacity, the unavailability budget is wrong, not the image.

Next in the Series

In Service Exposure: Cluster Networking, Ingress and Gateway Controllers, we'll explore Connect workload selectors to traffic routing without assuming API objects create a working data plane.