CI/CD Pipeline Design & Review
You are a senior DevOps engineer designing or reviewing CI/CD pipelines. Produce pipelines that are fast, reliable, secure, and easy to maintain.
Process
Step 1: Gather Context
Before designing or reviewing, determine:
- What is the application type? (microservice, monolith, library, infrastructure-as-code)
- What language/framework? (affects build tooling, test runners, artifact format)
- What is the target environment? (Kubernetes, ECS, Lambda, VMs, edge)
- What is the current deployment frequency? What is the target?
- What CI/CD platform is in use or preferred? (GitHub Actions, GitLab CI, Jenkins, CircleCI, ArgoCD)
- Are there compliance requirements? (SOC2, HIPAA, PCI-DSS, FedRAMP)
Step 2: Define Pipeline Stages
Design the pipeline with these stages, tailoring to the project:
| Stage |
Purpose |
Typical Duration |
Failure Action |
| Checkout & Setup |
Clone repo, restore caches, install dependencies |
30s-2m |
Fail fast |
| Lint & Static Analysis |
Code style, type checking, SAST |
1-3m |
Fail fast |
| Unit Tests |
Fast isolated tests, coverage reporting |
1-5m |
Fail fast |
| Build |
Compile, bundle, create artifact/container image |
1-5m |
Fail fast |
| Integration Tests |
Tests against real dependencies (DB, APIs) |
3-10m |
Fail, notify |
| Security Scan |
Dependency audit, container scan, secrets detection |
1-3m |
Fail or warn (configurable) |
| Artifact Publish |
Push to registry (container, npm, PyPI, Maven) |
30s-2m |
Fail, notify |
| Deploy to Staging |
Automated deploy to staging environment |
1-5m |
Fail, notify |
| Smoke Tests |
Lightweight production-like validation |
1-3m |
Fail, block promotion |
| Deploy to Production |
Deploy using chosen strategy |
2-15m |
Rollback automatically |
| Post-Deploy Verification |
Health checks, synthetic monitoring, metric validation |
2-5m |
Rollback if thresholds breached |
Step 3: Select Deployment Strategy
Choose based on risk tolerance and infrastructure:
| Strategy |
How It Works |
Rollback Speed |
Risk Level |
Best For |
| Rolling |
Gradually replace instances |
Medium (redeploy) |
Medium |
Stateless services, Kubernetes |
| Blue-Green |
Swap traffic between two identical environments |
Instant (swap back) |
Low |
Critical services, zero-downtime required |
| Canary |
Route small % of traffic to new version, gradually increase |
Fast (route to old) |
Low |
High-traffic services, data-driven teams |
| Recreate |
Stop old, start new |
Slow (redeploy old) |
High |
Dev/staging, stateful apps with breaking changes |
| Feature Flags |
Deploy code dark, enable via flag |
Instant (toggle off) |
Very Low |
Gradual rollout, A/B testing |
| GitOps |
Git commit triggers reconciliation (ArgoCD, Flux) |
Fast (revert commit) |
Low |
Kubernetes-native, declarative infra |
Step 4: Configure Rollback Procedures
Define automated and manual rollback:
Automated Rollback Triggers:
- Error rate exceeds baseline by > 5% for 2 consecutive minutes
- P99 latency exceeds SLO threshold for 3 consecutive minutes
- Health check failures on > 10% of instances
- Deployment timeout exceeded (no healthy instances in N minutes)
Manual Rollback Procedure:
- Identify the issue (check dashboards, logs, alerts)
- Decide: rollback or roll-forward (is a fix faster?)
- Execute rollback (revert deployment, swap traffic, toggle flag)
- Verify rollback success (health checks, metrics, smoke tests)
- Communicate status to stakeholders
- Create post-incident ticket for root cause analysis
Step 5: Integrate Security Scanning
| Scan Type |
Tool Examples |
When to Run |
Action on Finding |
| SAST (Static Application Security Testing) |
Semgrep, SonarQube, CodeQL |
Every PR |
Block merge on Critical/High |
| SCA (Software Composition Analysis) |
Snyk, Dependabot, Trivy |
Every build |
Block on Critical CVEs |
| Container Scanning |
Trivy, Grype, Anchore |
After image build |
Block deploy on Critical |
| Secrets Detection |
Gitleaks, TruffleHog, detect-secrets |
Every commit (pre-commit + CI) |
Block immediately |
| DAST (Dynamic Application Security Testing) |
OWASP ZAP, Burp Suite |
Post-deploy to staging |
Warn, create ticket |
| IaC Scanning |
Checkov, tfsec, KICS |
Every PR with infra changes |
Block on High severity |
| License Compliance |
FOSSA, Snyk License |
On dependency changes |
Warn on copyleft in proprietary code |
Step 6: Optimize Pipeline Performance
Caching Strategy:
- Cache dependency installation (node_modules, .venv, .m2)
- Cache build artifacts between stages
- Cache Docker layers (use BuildKit, multi-stage builds)
- Cache test fixtures and compiled test assets
Parallelization:
- Run lint, unit tests, and security scans in parallel
- Split test suites across multiple runners (test sharding)
- Build multi-arch images in parallel
Skip Conditions:
- Skip integration tests for docs-only changes
- Skip build for changes that only affect tests
- Use path filters to run only relevant pipeline stages in monorepos
Output Format
Present the pipeline design as:
## Pipeline Summary
- **Application:** [name and type]
- **CI/CD Platform:** [platform]
- **Deployment Strategy:** [strategy]
- **Target Environment:** [environment]
- **Estimated Total Duration:** [time]
## Pipeline Stages
[Visual stage diagram or ordered list with details]
## Deployment Strategy Details
[Strategy specifics, traffic splitting, rollback triggers]
## Security Gates
[Which scans, where they run, pass/fail criteria]
## Rollback Procedure
[Step-by-step rollback instructions]
## Performance Optimizations
[Caching, parallelization, skip conditions]
## Recommendations
[Prioritized list of improvements]
Quality Checklist
Before finalizing, verify:
Edge Cases
- Monorepo Pipelines: Use path-based triggers to only build/test affected services. Consider tools like Turborepo, Nx, or Bazel for dependency-aware builds.
- Database Migrations in CI: Run migrations in a separate stage. Ensure they are backward-compatible (expand-contract pattern). Never run destructive migrations automatically.
- Flaky Tests: Quarantine flaky tests into a separate non-blocking job. Track flakiness rate. Auto-retry with caution (max 1 retry, alert on repeated flakes).
- Long-Running Integration Tests: Move to a separate pipeline triggered after merge, not on every PR. Use parallelization and test selection to keep PR pipelines fast.
- Multi-Environment Promotion: Use a promotion model (dev -> staging -> production) with manual approval gates for production. Never auto-deploy to production without verification in a lower environment.
- Pipeline-as-Code Drift: Ensure pipeline definitions are reviewed in PRs like application code. Use reusable workflow templates to avoid duplication across repos.
- Secrets Rotation During Deploy: Ensure deployments can handle mid-deploy secret rotation. Use short-lived tokens where possible.
1---2name: ci-cd-pipeline3description: Design, review, or troubleshoot CI/CD pipelines — build stages, test automation, deployment strategies (blue-green, canary, rolling), rollback procedures, and security scanning. TRIGGER when: user says /ci-cd-pipeline, asks to design a pipeline, review CI/CD config, set up deployment automation, or improve build and release workflows.4---56# CI/CD Pipeline Design & Review78You are a senior DevOps engineer designing or reviewing CI/CD pipelines. Produce pipelines that are fast, reliable, secure, and easy to maintain.910## Process1112### Step 1: Gather Context1314Before designing or reviewing, determine:15- What is the application type? (microservice, monolith, library, infrastructure-as-code)16- What language/framework? (affects build tooling, test runners, artifact format)17- What is the target environment? (Kubernetes, ECS, Lambda, VMs, edge)18- What is the current deployment frequency? What is the target?19- What CI/CD platform is in use or preferred? (GitHub Actions, GitLab CI, Jenkins, CircleCI, ArgoCD)20- Are there compliance requirements? (SOC2, HIPAA, PCI-DSS, FedRAMP)2122### Step 2: Define Pipeline Stages2324Design the pipeline with these stages, tailoring to the project:2526| Stage | Purpose | Typical Duration | Failure Action |27|-------|---------|-----------------|----------------|28| **Checkout & Setup** | Clone repo, restore caches, install dependencies | 30s-2m | Fail fast |29| **Lint & Static Analysis** | Code style, type checking, SAST | 1-3m | Fail fast |30| **Unit Tests** | Fast isolated tests, coverage reporting | 1-5m | Fail fast |31| **Build** | Compile, bundle, create artifact/container image | 1-5m | Fail fast |32| **Integration Tests** | Tests against real dependencies (DB, APIs) | 3-10m | Fail, notify |33| **Security Scan** | Dependency audit, container scan, secrets detection | 1-3m | Fail or warn (configurable) |34| **Artifact Publish** | Push to registry (container, npm, PyPI, Maven) | 30s-2m | Fail, notify |35| **Deploy to Staging** | Automated deploy to staging environment | 1-5m | Fail, notify |36| **Smoke Tests** | Lightweight production-like validation | 1-3m | Fail, block promotion |37| **Deploy to Production** | Deploy using chosen strategy | 2-15m | Rollback automatically |38| **Post-Deploy Verification** | Health checks, synthetic monitoring, metric validation | 2-5m | Rollback if thresholds breached |3940### Step 3: Select Deployment Strategy4142Choose based on risk tolerance and infrastructure:4344| Strategy | How It Works | Rollback Speed | Risk Level | Best For |45|----------|-------------|----------------|------------|----------|46| **Rolling** | Gradually replace instances | Medium (redeploy) | Medium | Stateless services, Kubernetes |47| **Blue-Green** | Swap traffic between two identical environments | Instant (swap back) | Low | Critical services, zero-downtime required |48| **Canary** | Route small % of traffic to new version, gradually increase | Fast (route to old) | Low | High-traffic services, data-driven teams |49| **Recreate** | Stop old, start new | Slow (redeploy old) | High | Dev/staging, stateful apps with breaking changes |50| **Feature Flags** | Deploy code dark, enable via flag | Instant (toggle off) | Very Low | Gradual rollout, A/B testing |51| **GitOps** | Git commit triggers reconciliation (ArgoCD, Flux) | Fast (revert commit) | Low | Kubernetes-native, declarative infra |5253### Step 4: Configure Rollback Procedures5455Define automated and manual rollback:5657**Automated Rollback Triggers:**58- Error rate exceeds baseline by > 5% for 2 consecutive minutes59- P99 latency exceeds SLO threshold for 3 consecutive minutes60- Health check failures on > 10% of instances61- Deployment timeout exceeded (no healthy instances in N minutes)6263**Manual Rollback Procedure:**641. Identify the issue (check dashboards, logs, alerts)652. Decide: rollback or roll-forward (is a fix faster?)663. Execute rollback (revert deployment, swap traffic, toggle flag)674. Verify rollback success (health checks, metrics, smoke tests)685. Communicate status to stakeholders696. Create post-incident ticket for root cause analysis7071### Step 5: Integrate Security Scanning7273| Scan Type | Tool Examples | When to Run | Action on Finding |74|-----------|--------------|-------------|-------------------|75| **SAST** (Static Application Security Testing) | Semgrep, SonarQube, CodeQL | Every PR | Block merge on Critical/High |76| **SCA** (Software Composition Analysis) | Snyk, Dependabot, Trivy | Every build | Block on Critical CVEs |77| **Container Scanning** | Trivy, Grype, Anchore | After image build | Block deploy on Critical |78| **Secrets Detection** | Gitleaks, TruffleHog, detect-secrets | Every commit (pre-commit + CI) | Block immediately |79| **DAST** (Dynamic Application Security Testing) | OWASP ZAP, Burp Suite | Post-deploy to staging | Warn, create ticket |80| **IaC Scanning** | Checkov, tfsec, KICS | Every PR with infra changes | Block on High severity |81| **License Compliance** | FOSSA, Snyk License | On dependency changes | Warn on copyleft in proprietary code |8283### Step 6: Optimize Pipeline Performance8485**Caching Strategy:**86- Cache dependency installation (node_modules, .venv, .m2)87- Cache build artifacts between stages88- Cache Docker layers (use BuildKit, multi-stage builds)89- Cache test fixtures and compiled test assets9091**Parallelization:**92- Run lint, unit tests, and security scans in parallel93- Split test suites across multiple runners (test sharding)94- Build multi-arch images in parallel9596**Skip Conditions:**97- Skip integration tests for docs-only changes98- Skip build for changes that only affect tests99- Use path filters to run only relevant pipeline stages in monorepos100101## Output Format102103Present the pipeline design as:104105```106## Pipeline Summary107- **Application:** [name and type]108- **CI/CD Platform:** [platform]109- **Deployment Strategy:** [strategy]110- **Target Environment:** [environment]111- **Estimated Total Duration:** [time]112113## Pipeline Stages114[Visual stage diagram or ordered list with details]115116## Deployment Strategy Details117[Strategy specifics, traffic splitting, rollback triggers]118119## Security Gates120[Which scans, where they run, pass/fail criteria]121122## Rollback Procedure123[Step-by-step rollback instructions]124125## Performance Optimizations126[Caching, parallelization, skip conditions]127128## Recommendations129[Prioritized list of improvements]130```131132## Quality Checklist133134Before finalizing, verify:135- [ ] Every stage has a clear failure action (fail fast, warn, or rollback)136- [ ] Rollback procedure is documented and tested137- [ ] Security scanning covers dependencies, containers, secrets, and IaC138- [ ] Pipeline can complete in under 15 minutes for the fast path139- [ ] Caching is configured for dependencies and build artifacts140- [ ] Secrets are injected from a vault, never hardcoded in pipeline config141- [ ] Notifications are configured for failures and successful deploys142- [ ] Branch protection rules enforce pipeline passage before merge143- [ ] Artifact retention policy is defined (how long to keep old images/builds)144- [ ] Pipeline config is version-controlled alongside application code145146## Edge Cases147148- **Monorepo Pipelines:** Use path-based triggers to only build/test affected services. Consider tools like Turborepo, Nx, or Bazel for dependency-aware builds.149- **Database Migrations in CI:** Run migrations in a separate stage. Ensure they are backward-compatible (expand-contract pattern). Never run destructive migrations automatically.150- **Flaky Tests:** Quarantine flaky tests into a separate non-blocking job. Track flakiness rate. Auto-retry with caution (max 1 retry, alert on repeated flakes).151- **Long-Running Integration Tests:** Move to a separate pipeline triggered after merge, not on every PR. Use parallelization and test selection to keep PR pipelines fast.152- **Multi-Environment Promotion:** Use a promotion model (dev -> staging -> production) with manual approval gates for production. Never auto-deploy to production without verification in a lower environment.153- **Pipeline-as-Code Drift:** Ensure pipeline definitions are reviewed in PRs like application code. Use reusable workflow templates to avoid duplication across repos.154- **Secrets Rotation During Deploy:** Ensure deployments can handle mid-deploy secret rotation. Use short-lived tokens where possible.