Skip to main content

Designing Multi-Stage CI/CD Pipelines

Design multi-stage CI/CD pipelines with parallel jobs, a blocking security scan, build-once promotion, caching, and an approval gate for production.

22 Terms

Overview and What You Will Learn

A multi-stage pipeline splits delivery into stages with one job each, runs independent jobs in parallel, and puts a gate between every stage so a failure stops everything downstream. Build the image once, scan and test that same image, and promote its digest through the environments.

In this lab, you will:

  • Design the stages on paper before writing any YAML
  • Run lint, unit tests and the image build in parallel
  • Run a blocking vulnerability scan and integration tests with real services
  • Add caching, an approval gate for production, and failure notifications
  • Measure job durations to prove the pipeline is actually faster

Why This Matters in Production

Picture a payments company like Razorpay. The pipeline has to ship fixes quickly, but no known vulnerability or regression can reach production. Meeting both demands is a design problem, not a matter of bolting steps on after each incident. When every stage has one job, a defined input and output, and a rule for what happens on failure, engineers can read the pipeline at a glance and trust a green run.

Core Principles

How the Stages Fit Together

Cheap checks should fail fast, and independent work should run side by side. Lint and unit tests do not need the image, so they run in parallel with the build rather than after it. Only the scan needs the image, and integration tests run beside it.

flowchart TD T([Push or PR]) --> L[Lint] T --> U[Unit tests] T --> B[Build and push image] B --> S[Security scan] L --> I[Integration tests] U --> I B --> I S --> D[Deploy staging] I --> D D --> P{{Approval gate}} P --> X[Deploy production] classDef start fill:#475569,color:#FFFFFF classDef job fill:#326CE5,color:#FFFFFF classDef gate fill:#F59E0B,color:#111827 classDef prod fill:#10B981,color:#FFFFFF class T start class L,U,B,S,I,D job class P gate class X prod

In GitHub Actions, needs builds this dependency graph. Jobs that share the same needs run in parallel, and a job waits for every job it lists. Draw the graph before writing the YAML.

Build Once, Promote the Digest

The image that was tested must be the image that runs in production, so build it a single time and pass its digest downstream.

Approach Result
Rebuild per environment Staging tests a different image than production runs
Build once, promote the digest What was tested is exactly what runs

Gates Must Block

A scan that only reports does not protect anything. Set the scan to fail the job on HIGH and CRITICAL findings, and make the deploy jobs depend on it.

Security

Pin third-party actions to a release tag, and ideally a full commit SHA, instead of @master. A moving reference means code you never reviewed can run in a job that holds cloud credentials.

Detailed Step-by-Step Practical Lab

This lab uses GitHub Actions, AWS ECR and EKS with OIDC role assumption. Replace the account ID, role names and cluster names with your own.

  1. Design each stage first. For every stage, write down its single job, inputs, outputs, failure behaviour and a time budget. The budgets are illustrative and should come from your own measurements:
TEXT
Stage 1 (parallel): lint, unit tests, build
Inputs: source code
Outputs: test results, image digest
On failure: block everything downstream
Budget: under 4 minutes
Stage 2 (parallel): security scan, integration tests
Inputs: image digest, source code
Outputs: scan report, test results
On failure: block deploys
Budget: under 8 minutes
Stage 3: deploy staging, then production
Inputs: the same image digest
Outputs: running service per environment
On failure: roll back, notify
Budget: under 3 minutes per environment
  1. Create the workflow with Stage 1. Lint, unit tests and the build all start at once, and the build exposes the image digest:
YAML
name: CI and Deploy
on:
push:
branches: [main]
pull_request:
permissions:
id-token: write
contents: read
env:
ECR_REGISTRY: 123456789012.dkr.ecr.ap-south-1.amazonaws.com
jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with: { node-version: '20', cache: 'npm' }
- run: npm ci
- run: npm run lint && npm run format:check
unit-test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with: { node-version: '20', cache: 'npm' }
- run: npm ci
- run: npm test
- uses: actions/upload-artifact@v4
if: always()
with: { name: junit-results, path: junit.xml }
build:
runs-on: ubuntu-latest
outputs:
digest: ${{ steps.push.outputs.digest }}
steps:
- uses: actions/checkout@v4
- uses: docker/setup-buildx-action@v3
- uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: ${{ vars.AWS_BUILD_ROLE }}
aws-region: ap-south-1
- uses: aws-actions/amazon-ecr-login@v2
- id: push
uses: docker/build-push-action@v5
with:
push: true
tags: ${{ env.ECR_REGISTRY }}/payment-api:${{ github.sha }}
cache-from: type=gha
cache-to: type=gha,mode=max
  1. Add Stage 2. The scan logs in to ECR and scans the exact digest that was built, failing the job on HIGH or CRITICAL. Integration tests run against real PostgreSQL and Redis service containers:
YAML
security-scan:
needs: build
runs-on: ubuntu-latest
steps:
- uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: ${{ vars.AWS_BUILD_ROLE }}
aws-region: ap-south-1
- uses: aws-actions/amazon-ecr-login@v2
- name: Scan the built image
uses: aquasecurity/trivy-action@0.28.0 # Pin to a current release or commit SHA
with:
image-ref: ${{ env.ECR_REGISTRY }}/payment-api@${{ needs.build.outputs.digest }}
severity: HIGH,CRITICAL
exit-code: '1'
ignore-unfixed: true
integration-test:
needs: [lint, unit-test, build]
runs-on: ubuntu-latest
services:
postgres:
image: postgres:15
env:
POSTGRES_DB: payment_test
POSTGRES_USER: testuser
POSTGRES_PASSWORD: testpass # Throwaway CI database only
ports: ['5432:5432']
options: >-
--health-cmd pg_isready
--health-interval 10s
--health-timeout 5s
--health-retries 5
redis:
image: redis:7-alpine
ports: ['6379:6379']
options: >-
--health-cmd "redis-cli ping"
--health-interval 10s
--health-retries 5
env:
DATABASE_URL: postgresql://testuser:testpass@localhost:5432/payment_test
REDIS_URL: redis://localhost:6379
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with: { node-version: '20', cache: 'npm' }
- run: npm ci
- run: npm run db:migrate
- run: npm run test:integration
  1. Add Stage 3. Staging deploys after both Stage 2 jobs pass, and production waits on the production environment, which must have required reviewers in GitHub settings. Both deploy only from main, and the chart must template image.digest:
YAML
deploy-staging:
needs: [security-scan, integration-test, build]
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
environment:
name: staging
url: https://staging.payment.devops.in
steps:
- uses: actions/checkout@v4
- uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: ${{ vars.AWS_STAGING_ROLE }}
aws-region: ap-south-1
- run: aws eks update-kubeconfig --name mumbai-staging-cluster --region ap-south-1
- name: Helm deploy
run: |
helm upgrade --install payment-api ./charts/payment-api \
--namespace payment-api-staging \
--values ./charts/values-staging.yaml \
--set image.digest=${{ needs.build.outputs.digest }} \
--atomic --timeout 5m --wait
- name: Smoke test with retries
run: curl -sf --retry 10 --retry-delay 5 --retry-connrefused https://staging.payment.devops.in/health
deploy-production:
needs: [deploy-staging, build]
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
environment:
name: production # Pauses here until a reviewer approves
url: https://api.payment.devops.in
steps:
- uses: actions/checkout@v4
- uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: ${{ vars.AWS_PROD_ROLE }}
aws-region: ap-south-1
- run: aws eks update-kubeconfig --name mumbai-prod-cluster --region ap-south-1
- name: Helm deploy
run: |
helm upgrade --install payment-api ./charts/payment-api \
--namespace payment-api-production \
--values ./charts/values-production.yaml \
--set image.digest=${{ needs.build.outputs.digest }} \
--atomic --timeout 10m --wait
  1. Add a notification job that always runs and reports the outcome. It uses v1 of the Slack action, and v2 uses different inputs:
YAML
notify:
needs: [deploy-staging, deploy-production]
if: always() && github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
steps:
- name: Work out the status
id: status
run: |
if [[ "${{ needs.deploy-production.result }}" == "success" ]]; then
echo "label=SUCCESS" >> $GITHUB_OUTPUT
elif [[ "${{ needs.deploy-staging.result }}" == "success" ]]; then
echo "label=STAGING ONLY" >> $GITHUB_OUTPUT
else
echo "label=FAILED" >> $GITHUB_OUTPUT
fi
- uses: slackapi/slack-github-action@v1
with:
payload: |
{"text": "payment-api ${{ steps.status.outputs.label }} for ${{ github.sha }} by ${{ github.actor }}"}
env:
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }}
SLACK_WEBHOOK_TYPE: INCOMING_WEBHOOK
  1. Lint the workflow locally before pushing, so syntax and needs mistakes are caught in seconds:
Bash
bash <(curl -s https://raw.githubusercontent.com/rhysd/actionlint/main/scripts/download-actionlint.bash)
./actionlint .github/workflows/ci.yaml
  1. Push and measure. Compare each job's duration, then check the same numbers after the cache is warm. Caches mostly pay off on the second run:
Bash
gh run watch
export RUN_ID=$(gh run list --workflow ci.yaml --limit 1 --json databaseId --jq '.[0].databaseId')
gh run view $RUN_ID --json jobs \
--jq '.jobs[] | {name, started: .startedAt, finished: .completedAt}'

Production Best Practices & Common Pitfalls

Common Mistake

Listing every earlier job in a deploy job's needs. If staging already depends on the tests, production only needs to depend on staging. Listing extra jobs makes the graph harder to read, and it hides which gate really matters.

Tip

Cancel stale runs on pull requests with concurrency: { group: ${{ github.workflow }}-${{ github.ref }}, cancel-in-progress: ${{ github.event_name == 'pull_request' }} }. Only cancel on pull requests, because cancelling a deploy on main halfway can leave an environment half-updated.

Remember

if: always() on the notify job makes it run even when upstream jobs fail, which is exactly when you need the alert.

  • Put fast checks first. Lint and unit tests should fail within a couple of minutes, before slow integration tests start.
  • Run independent jobs in parallel. Total time becomes the slowest stage, not the sum of all jobs.
  • Pass the digest, not a rebuild. Every environment deploys the exact image the scan and tests saw.
  • Cache dependencies and Docker layers. Measure before and after, since the gain depends on how often your dependencies change.
  • Keep the scan blocking. Use exit-code: '1', and use ignore rules only for reviewed, documented exceptions.
  • Use a reusable workflow once environments multiply. A shared deploy workflow keeps staging and production logic identical.

Quick Reference & Troubleshooting Commands

Command Description
actionlint .github/workflows/ci.yaml Lint workflow syntax and needs
gh run watch Follow the current run
gh run view ID --json jobs Read per-job timings
gh run rerun ID --failed Re-run only the failed jobs
gh workflow view ci.yaml Show a workflow's definition
Problem Likely cause Fix
Scan cannot pull the image Job missing ECR login Add the AWS credentials and ECR login steps
Deploy runs on pull requests No branch condition Add if: github.ref == 'refs/heads/main'
Smoke test fails right after deploy Service not ready yet Use curl retries instead of a fixed sleep
Pipeline is slow Jobs run in sequence or cache misses Check needs and cache keys
Notification never arrives Notify job lacks if: always() Add the condition

Resources

Explore More in CI/CD Fundamentals and Pipeline Design

All 3 Topics

Frequently Asked Questions

Is Designing Multi-Stage CI/CD Pipelines free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Designing Multi-Stage CI/CD Pipelines topic cover?

Design multi-stage CI/CD pipelines with parallel jobs, a blocking security scan, build-once promotion, caching, and an approval gate for production.

Found a mistake, an outdated step or a broken link?