How Self-Healing Pipelines Cut Human Intervention in CI/CD

How self-healing CI/CD pipelines work: classify failures, bounded retries in GitLab and Jenkins, flaky test quarantine and automatic rollback.

Sep 1, 2025 - 14:11
Nov 10, 2026 - 22:27
 0  61
How Self-Healing Pipelines Cut Human Intervention in CI/CD

A self-healing CI/CD pipeline detects a known failure, applies a pre-approved fix, and records what it did, so people only handle failures that need judgment. In practice this means bounded retries, job timeouts, flaky-test handling, automatic rollback after a failed health check, and a clear page to a person for everything else.

This guide covers the pipeline itself: the build, test and deploy stages that engineers otherwise restart by hand. If you want the runtime side (restarting pods, replacing unhealthy instances), read 10 Ways to Implement Self-Healing in DevOps Systems and How Self-Healing Systems Reduce MTTR. The syntax and behaviour below were checked against the GitLab, Jenkins, GitHub, Kubernetes and Argo Rollouts documentation in November 2026.

Key takeaways

  • Self-healing for a pipeline means a small set of safe, repeatable reactions to failures you have already seen. It does not mean the pipeline fixes code.
  • Sort failures first. Lost runners, registry timeouts and hung jobs are safe to retry. A failing assertion or a failed security scan is information, and retrying it hides the problem.
  • GitLab CI/CD has a built-in retry keyword with a maximum of 2 retries. Jenkins has the retry and timeout steps. GitHub Actions documents manual re-runs and no automatic retry.
  • Kubernetes reports a stalled Deployment but takes no action on it. A pipeline step or a tool such as Argo Rollouts has to trigger the rollback.
  • Every automatic fix must leave a log line and a counter. A pipeline that quietly retries everything makes flaky infrastructure look healthy.
  • Measure success by the number of manual re-runs and manual rollbacks per week, alongside the DORA change fail rate and failed deployment recovery time.

What "self-healing" means inside a pipeline

A pipeline run is a chain of steps that touch many things outside your control: runners or agents, package registries, container registries, cloud APIs, test databases and the cluster you deploy to. Most red builds are not caused by the commit. They come from a runner that was reclaimed, a registry that answered slowly, or a test that fails one time in twenty.

Self-healing replaces the human reaction to those events with a rule. The loop has four parts: detect (an exit code, timeout or health metric), classify (is this a known, safe-to-repeat failure?), act (retry, reschedule, roll back, quarantine) and record (log it, count it, and page someone if the rule did not work). Skipping the classify and record parts is what turns automation into noise.

Classify failures before you automate anything

Failure classTypical signalSafe automatic responseWhen a person should be told
Runner or agent lostJob dies with no test output, agent disconnectsRetry on a fresh agent, up to 2 timesThe same pool loses jobs repeatedly
Transient network or registry errorTimeout or 5xx while pulling a base image or dependencyRetry with a short delay, or use a mirror or cacheThe mirror itself is down
Hung jobNo log output for a long periodCancel at a timeout, then retry onceIt hangs again on the retry
Flaky testSame test passes and fails on the same commitQuarantine it into a non-blocking job and open a ticketThe quarantine list grows past an agreed size
Bad deploymentRollout stalls, readiness fails, error rate rises after releaseAbort and return to the previous versionAlways, after the rollback has finished
Real defect or policy failureAssertion fails, scanner finds an issue, lint errorNone. Fail the build with a clear messageThe author of the change

The last row matters most. Teams that retry every non-zero exit code end up with pipelines that pass on the third try and nobody can say why.

Recipe 1: retry only the failures that deserve it

GitLab CI/CD

GitLab accepts retry values of 0, 1 or 2, and retries all failure types by default. Narrow it with retry:when or retry:exit_codes. The exit_codes option arrived in GitLab 16.10 and became generally available in 17.5.

build-image:
  script:
    - ./ci/build_and_push.sh
  retry:
    max: 2
    when:
      - runner_system_failure
      - api_failure
      - no_updates_running

integration-tests:
  script:
    - ./ci/run_integration_tests.sh
  retry:
    max: 1
    exit_codes: 137

Exit code 137 usually means the process was killed (often out of memory), which is an environment problem and fits a single retry. A test assertion failure uses a different exit code and is not retried. The when list is long and changes between releases (GitLab 19.1 deprecated stuck_or_timeout_failure in favour of the stuck_* and no_updates_* values), so check the current list before copying the example. For more GitLab patterns, see 15 GitLab CI/CD Pipeline Examples with YAML.

Jenkins

The retry step takes a count and optional conditions. With no conditions it retries on any exception except a user abort. The agent condition retries only when a node or step fails because of infrastructure, such as a broken agent connection, and it allocates a fresh agent. The timeout step cancels its block after the given time, and activity: true measures time since the last log output instead of total time.

pipeline {
  agent any
  options {
    timeout(time: 45, unit: 'MINUTES')
  }
  stages {
    stage('Build') {
      steps {
        retry(count: 2, conditions: [agent(), nonresumable()]) {
          sh './gradlew build'
        }
      }
    }
    stage('Integration tests') {
      steps {
        timeout(time: 10, unit: 'MINUTES', activity: true) {
          sh './gradlew integrationTest'
        }
      }
    }
  }
}

Avoid waitUntil as a retry loop. The documentation notes it has no retry limit, so a condition that never becomes true holds an executor until something else stops it. Pair it with an enclosing timeout. Common Jenkins mistakes of this kind are listed in 10 Jenkins Mistakes That Break Deployment Pipelines.

GitHub Actions

GitHub documents re-running a failed run from the web page or with gh run rerun RUN_ID --failed. A run can be re-run up to 30 days after it started and up to 50 times. The documentation describes these re-runs as manual, so automatic retries need either a retry action from the marketplace (review its source first) or a small wrapper script around the flaky command. Two native settings do help: timeout-minutes on a job, and concurrency to cancel runs that a newer commit has made redundant.

jobs:
  test:
    runs-on: ubuntu-latest
    timeout-minutes: 20
    concurrency:
      group: test-${{ github.ref }}
      cancel-in-progress: true
    steps:
      - uses: actions/checkout@v7
      - name: Download dependencies with a bounded retry
        run: |
          for attempt in 1 2 3; do
            ./scripts/fetch_deps.sh && exit 0
            echo "::warning::fetch_deps failed on attempt $attempt"
            sleep $((attempt * 10))
          done
          exit 1

The ::warning:: line is a workflow command that creates an annotation, so every retry shows up on the run summary instead of disappearing.

Recipe 2: handle flaky tests with a policy, not a retry loop

A flaky test is one that gives different results for the same code. Retrying inside the pipeline gives you a green build and tells you nothing. A workable policy has four rules:

  1. A test that fails and then passes on the same commit is recorded as flaky, with its name, job and date.
  2. After a set number of flaky results (choose one your team agrees on), the test moves to a non-blocking job and a ticket is opened automatically.
  3. The non-blocking job still runs on every commit so you can see whether it recovers.
  4. The quarantine list has an owner and a size limit. If it grows past the limit, new feature work stops until it shrinks.

Rule 4 is the one that makes the policy honest. Without it, quarantine becomes a place where tests go to be forgotten. Better test design also helps: stages and test types are covered in 10 Automated Testing Stages in DevOps Pipelines.

Recipe 3: roll back a bad deployment without waiting for a person

A Deployment in Kubernetes has a progress deadline. When it passes, the controller adds a Progressing condition with status False and reason ProgressDeadlineExceeded. The documentation states that Kubernetes takes no action on a stalled Deployment beyond reporting that condition, and that a higher-level orchestrator can act on it, for example by rolling back. Your pipeline is that orchestrator:

kubectl apply -f k8s/deployment.yaml
if ! kubectl rollout status deployment/web --timeout=5m; then
  echo "Rollout failed, reverting to the previous revision"
  kubectl rollout undo deployment/web
  kubectl rollout status deployment/web --timeout=5m
  exit 1
fi

kubectl rollout status returns a zero exit code when the rollout completes, so the if test works in any CI system. Note the final exit 1: the pipeline still fails after the rollback, because the release did not ship. Healing the production environment and reporting a failed release are two separate outcomes.

Readiness probes decide whether new pods receive traffic, so make sure they test something real. Our guide on liveness and readiness probes explains how to set them, and 10 Deployment Rollback Strategies compares other ways to go back.

Metric-driven rollback with Argo Rollouts

A readiness probe only says a pod started. To roll back on user-visible symptoms, a progressive delivery controller can query metrics during a canary. In Argo Rollouts an AnalysisTemplate defines the metric, a successCondition, the measurement interval and a failureLimit. The documentation says a failed analysis aborts the Rollout, sets the canary weight back to zero and marks the Rollout Degraded, with traffic returning to the stable version.

apiVersion: argoproj.io/v1alpha1
kind: AnalysisTemplate
metadata:
  name: success-rate
spec:
  metrics:
    - name: success-rate
      interval: 5m
      successCondition: result[0] >= 0.95
      failureLimit: 3
      provider:
        prometheus:
          address: http://prometheus.monitoring:9090
          query: |
            sum(rate(http_requests_total{app="web",status!~"5.."}[5m]))
            /
            sum(rate(http_requests_total{app="web"}[5m]))

The query and the 0.95 threshold are examples. Set them from your own service level objective. More strategies, including blue-green and canary, are in 12 Kubernetes Rollout Strategies with Examples.

Guardrails that keep self-healing safe

  • Retry only idempotent steps. Building an image or running a test twice is harmless. Publishing a package, sending a notification or running a database migration twice may not be.
  • Cap everything. Retries, wait time and total pipeline duration all need a ceiling. GitLab enforces a ceiling of 2 retries for you. In scripts you set it yourself.
  • Back off. Waiting a little longer after each failed attempt avoids hammering a registry that is already struggling.
  • Log and count each automatic action. A retry should leave an annotation, a log line or a metric. A weekly review of "jobs that passed only after a retry" shows where the real problems are.
  • Keep a human approval for production-changing fixes. Rolling back to a version that already ran in production is a safe automatic action. Applying a new corrective change is not.
  • Fail the pipeline even when you healed the environment. A rolled-back release is still a failed release.

How to measure whether human intervention is falling

Start with counts you can pull from your CI system: manual re-runs per week, manual rollbacks per week, and pages caused by pipeline problems. Then compare against the DORA metrics. DORA lists five software delivery performance measures: change lead time, deployment frequency, failed deployment recovery time, change fail rate and deployment rework rate. Failed deployment recovery time (formerly called MTTR) should drop when automatic rollback works, and the change fail rate should not rise because of hidden retries. If recovery time improves but change fail rate climbs, your automation is masking defects.

What you trackHealthy trendWarning sign
Manual re-runs per weekFallingFlat while automatic retries rise (the retries are hiding flaky infrastructure)
Jobs that pass only after retrySmall and shrinkingGrowing, or concentrated in one runner pool or test file
Manual rollbacks per weekFalling, replaced by automatic onesAutomatic rollbacks keep firing for the same service
Failed deployment recovery timeFallingFalling while change fail rate rises
Quarantined testsStable or shrinkingGrowing with no owner

A sensible order of adoption

  1. Add timeouts everywhere. A hung job that blocks a runner for hours is the cheapest problem to remove.
  2. Retry infrastructure failures only. Use runner and agent conditions or specific exit codes, not blanket retries.
  3. Cache or mirror dependencies. It removes a class of transient failures instead of retrying around it.
  4. Add flaky test tracking and quarantine. Do this once you can see which tests flip results.
  5. Automate rollback on rollout failure. Start with kubectl rollout status and undo, then move to metric analysis.
  6. Alert on the automation itself. Page when retries, rollbacks or quarantines cross the thresholds you set.

Teams working through this in a hands-on setting can practise the pipeline pieces in our Jenkins training in Pune and the DevOps training in Pune, with live online batches for learners outside the city. For a list of failures worth designing against, read 12 Common CI/CD Pipeline Failures and Fixes.

What not to automate

  • Changes to test expectations so a failing test passes.
  • Skipping a failed security or compliance scan.
  • Database restores and schema rollbacks, which can lose data and need a person's judgment.
  • Retrying a deployment to production more than once without anyone looking.
  • Silencing an alert because it fired often. Fix the cause or tune the threshold with the owning team.

Frequently asked questions

What is a self-healing pipeline in CI/CD?

It is a pipeline that reacts to known failures with pre-approved actions such as retrying a lost job, cancelling a hung one, quarantining a flaky test or rolling back a failed deployment. It logs each action and alerts a person when the action does not work.

Does GitHub Actions retry failed jobs automatically?

GitHub documents re-running failed jobs manually, from the web interface or with gh run rerun RUN_ID --failed. The documentation does not describe a built-in automatic retry, so use a bounded retry in your script, review any marketplace retry action before trusting it, or add your own automation.

How many times should a pipeline retry a failed job?

Once or twice is normal for infrastructure failures. GitLab allows at most 2 retries. If a job needs more, the cause is a problem worth fixing, not a delay worth waiting out.

Should flaky tests be retried until they pass?

No. Retrying hides the flakiness and teaches the team to ignore red builds. Record the flaky result, quarantine the test into a non-blocking job and open a ticket with an owner.

Does Kubernetes roll back a failed Deployment by itself?

No. Kubernetes sets the ProgressDeadlineExceeded condition and takes no further action. Your pipeline can run kubectl rollout undo, or a tool such as Argo Rollouts can abort a canary when an analysis fails.

How do I know the automation is helping?

Track manual re-runs, manual rollbacks and pipeline-related pages over time, and compare them with DORA's change fail rate and failed deployment recovery time. Fewer manual actions with a stable change fail rate means the automation is working.

Can machine learning make a pipeline self-healing?

It can help rank likely causes or spot unusual runs, but the reliable gains come from timeouts, classified retries, rollbacks and good observability. Start there before adding anything that needs training data.

Official references

What's Your Reaction?

Like Like 0
Dislike Dislike 0
Love Love 0
Funny Funny 0
Angry Angry 0
Sad Sad 0
Wow Wow 0
Mridul I am a passionate technology enthusiast with a strong focus on DevOps, Cloud Computing, and Cybersecurity. Through my blogs at DevOps Training Institute, I aim to simplify complex concepts and share practical insights for learners and professionals. My goal is to empower readers with knowledge, hands-on tips, and industry best practices to stay ahead in the ever-evolving world of DevOps.