
Essay CI/CD Pipelines
Automated Rollback Strategy After a Failed Kubernetes Deployment
Kubernetes won't undo a bad release, so wire up recovery yourself.
Automated rollback after a failed Kubernetes deployment needs more than a command that restores an older version. Kubernetes detects failure but leaves recovery to something else. A reliable strategy connects health signals to release decisions, restores a known artifact, and keeps Git and the database compatible with that recovery. The goal is to act before a bad release becomes a user-facing incident, without making the recovery itself another source of failure.
Why Kubernetes stops short of reverting a failed deployment
When progressDeadlineSeconds expires, the Deployment controller marks the Progressing condition as False with the reason ProgressDeadlineExceeded. It does not stop or reverse the rollout. The broken ReplicaSet stays in place, and crashlooping pods can continue until something external acts.
The deadline also measures time without progress. A slow deployment that keeps advancing never trips it. Meanwhile, kubectl rollout undo can re-promote a previous ReplicaSet without rebuilding the application, but someone or something still has to issue that command. Users remain at risk while a person notices failing checks, looks into them, and takes action. Closing that gap requires three connected layers, which are native health signals, post-deploy metric gates, and progressive delivery analysis.
How Kubernetes revision history works and why it must be configured explicitly
Every change to spec.template creates a new ReplicaSet. That can be a new image tag, environment variable, or resource limit. The old ReplicaSet remains at zero replicas, and retaining that object gives rollback a concrete target. A revision captures only the pod template, leaving configuration objects changed outside it, external secrets, and other cluster state outside its scope.
The default revisionHistoryLimit is 10, which can be too restrictive for teams shipping multiple times a day. Teams should set it explicitly in the manifest to control the recovery window otherwise determined by the default. Once older ReplicaSets are pruned, those rollback targets disappear.
Annotating every apply with kubernetes.io/change-cause at deploy time gives kubectl rollout history more than unexplained revision numbers. The artifact needs an equally clear identity. Mutable image references such as :latest or :v1.2 create ambiguity, so deployment manifests and CI metadata should store SHA-pinned image references. A retained revision is useful only if it points to the exact application artifact the team intends to restore.
The three-layer signal hierarchy that decides when to trigger a rollback

The first layer is Kubernetes health probes. Readiness probes remove an unhealthy pod from service endpoints without restarting it, while liveness probes restart a deadlocked or unrecoverable container. Startup probes give slow-boot workloads, including JVM services and model-serving containers, time to initialize without premature restarts. These checks have different jobs. None supplies the release-level decision to revert.
To turn those signals into basic rollback protection, the pipeline must define what counts as unhealthy, how long to wait, and which failure threshold triggers recovery. It should gate deployment success on the exit code of kubectl rollout status following kubectl apply. Acceptance is not evidence of a healthy application. The apply command returns 0 when the API server accepts the manifest, regardless of whether the resulting pods can serve traffic.
The second layer adds post-deploy metric gates. A release can pass its probes yet cause elevated error rates, worse latency, or crash loops that appear only under load. Monitoring must keep running after deployment is done so that real traffic can reveal failures that startup checks missed.
An error rate above 5% for two minutes triggers rollback, as does P99 latency above its defined threshold for two minutes. Crash loops beyond a defined count in a short window also trigger rollback, while an error rate in a warning band pages on-call without automatically reverting. Cooldown logic belongs in the same system. Otherwise, a rollback followed immediately by redeployment of the same broken version creates a loop.
The third layer makes analysis part of the release gate through progressive delivery. Flagger works on top of existing Deployments, driving canaries through a service mesh or ingress controller. The tooling choice depends on the existing GitOps stack, including Argo CD or Flux, and whether a new workload CRD is acceptable. Without meaningful success-rate and latency queries, canary automation adds complexity without adding protection.
Keeping rollbacks in sync with Git state
An automatic kubectl rollout undo changes the live cluster without changing Git. The cluster may be healthy while its declared configuration still points to the failed release. Recovery can then be undone by reconciliation.
With automated sync enabled but selfHeal off, which is the default for that setting, Argo CD leaves an imperatively rolled-back application OutOfSync. An unrelated merge can trigger a sync and reapply the broken version. Flux corrects Kustomization drift by default. Its next reconciliation can therefore overwrite an imperative undo unless the offending Git commit is also reverted.
The durable practice is to revert or amend the commit that caused the failure and let the GitOps operator apply the change. An imperative undo remains useful when reconciliation is too slow for the incident’s reach, but it needs a corresponding manifest repository update. Git then records the recovery with the same traceability as the release.
This also requires separating build and deploy pipelines. The build produces an image tagged with the commit SHA, while the deploy pipeline updates manifests in the GitOps repository. Build and deploy can fail in different ways. A broken build must never stop the team from restoring a production artifact that has already been built.
Meanwhile, kubectl rollout undo can re-promote a previous ReplicaSet without rebuilding the application, but someone or something still has to issue that command.
Why database migrations break the assumption that rollback is safe
Bringing back an old application version does not bring back its database schema. If a migration removed something the old code needs, the application can revert cleanly and still fail against its own data store. This is rollback’s sharpest edge. Database backups address disaster recovery because restoring an earlier point discards valid writes made after deployment. A destructive down migration can also cause a second incident while the team is trying to recover.
Teams can use expand-and-contract across multiple releases. During expansion, the migration adds columns or tables and keeps the structures that old code needs. The new application writes to both structures but still reads from the old one. Both versions can use the database during this phase. If deployment fails, the old code ignores the added structure and keeps using what is still intact.
The migration phase backfills existing data into the new structure as a background job outside the deployment transaction. The contract phase then deploys code that reads from the new structure. Old fields are dropped only after stability is established and the rollback window has closed.
Removing old fields too early takes away the previous application’s footing. Teams treating rollback as a one-command operation without expand-and-contract are relying on a false sense of safety.
Extra rollback complexity for GPU workloads and model-serving deployments
A model can send back successful HTTP responses and still get its predictions wrong, a functional failure. Standard probes and error-rate gates cannot detect it on their own, and a standard rolling deployment does not provide the controlled exposure needed for model regressions. Accuracy, latency, and prediction drift need their own attention. Metrics such as token cost and task completion rate help show how well the service did beyond whether it answered.
Canaries through Argo Rollouts or Istio traffic splitting limit exposure to a new model version. However, stable and canary pods can compete for GPU memory. Without resource limits and node affinity that separates canaries onto dedicated GPU nodes, OOM kills and latency spikes can affect the whole service. Running two model versions also costs more and takes more work, so teams must plan for that capacity before an incident.
Sessions introduce another constraint on recovery. Requests midway through a session cannot transparently switch between model versions without risking user-visible inconsistency, so session stickiness needs explicit handling. Automated kill switches should use error rate, P99 latency, and semantic drift signals as well as HTTP status codes. GPU node pools need tightly configured Pod Disruption Budgets as well. Those budgets must prevent all GPU pods from draining together, because rescheduling GPU pods is slower and more expensive than rescheduling CPU pods.
Rollback as a compliance and audit event, not just an operational one
A technically successful rollback can still leave a compliance gap if no durable record explains what changed. Auditability has to exist before the incident. API-server audit logs should be enabled, shipped to durable storage, and retained for the required audit period. EKS and AKS disable audit logging by default, while GKE enables Admin Activity audit logs by default. The platform choice therefore does not remove the need to understand the logging configuration.
Relevant controls include SOC 2 CC7.2 and related criteria CC4.1 and CC6.1, ISO A.8.15, and PCI Requirement 10. HIPAA 164.312(b) covers how activity is recorded and examined, while the rules for how long records must be kept come from 164.316(b)(2)(i). These distinctions affect how the audit trail is designed. A Git revert adds authorship, timestamp, and a diff to version history, but an imperative undo does not appear there. For regulated workloads, that emergency action needs an immediate manifest repository commit, or recovery should use Git reconciliation instead.
Dedicated ServiceAccounts should have only the permissions they need, avoiding cluster-admin and wildcard RBAC rules that can unintentionally grant permissions such as delete or escalate. Recovery should not require unrestricted cluster access. Policy as code through tools such as OPA Gatekeeper adds version-controlled enforcement that prevents non-compliant configurations from reaching the cluster.
What small teams actually need to operate this system without a dedicated DevOps function
A small team has less time to spare for manual recovery but needs it just as much. A hung rollout at 2 a.m. otherwise depends on someone who can read events, describe pods, and reason about the scheduler. That person may be the CTO or a dedicated DevOps hire. Automation means that person no longer has to carry out every routine revert, though someone still needs to look into what went wrong.
Start with health probes and progressDeadlineSeconds, wired into pipeline logic that actually acts on failure. Add metric gates that use monitoring to check error rates and latency and catch failures under real traffic. Progressive delivery comes when release cadence and risk tolerance justify canary analysis and its operational cost. The stages build on one another, rather than presenting a choice between doing nothing and operating the entire system immediately.
Build and deploy separation is non-negotiable even at this size. SHA-tagged images must be kept so the team can deploy retained revisions without a rebuild. Unknown interactions, real-world data, edge cases, and timing will still defeat some tests. The goal is not to predict every failure, but to make recovery independent of a fresh build and an awake engineer.


