Skip to content
Tech Interview Prep
Technical interview guide

CI/CD Pipeline Design

Continuous integration and continuous delivery: automating the path from commit to a shippable build.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v5
Editorial status
Reviewed

Scope: GitHub Actions, GitLab CI/CD, NIST SSDF, SLSA v1.2, Sigstore, OCI, Kubernetes, Argo CD, and DORA guidance current 2026-08-31.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-24

Design a pipeline that builds an artifact once and promotes that identical artifact through staging and production. How is it identified as it moves, where does environment-specific configuration get injected, and how do promotion gates attach?

Answer

First 90 seconds. The guarantee you're buying is that the bytes that passed staging are the bytes that run in production. That only holds if identity is content-addressed (the OCI digest, sha256:... computed over the manifest) and if nothing downstream rebuilds. Tags are mutable pointers: app:v1.4.2 can be re-pushed and prod will pull different bytes under the same name. So the unit of promotion is the digest, and every stage pins it.

The build job checks out, builds, pushes, signs and attests, then emits the digest as an output. Staging and production jobs consume that digest as an input and never run docker build.

StageWhat runsPinned toGate
buildbuild, push, sign, attestcommit SHA → digestrequired checks on PR
stagingdeploy onlydigestauto on merge
productiondeploy onlysame digestrequired reviewers on the production environment

yaml jobs: build: runs-on: ubuntu-latest outputs: digest: ${{ steps.push.outputs.digest }} steps: - uses: actions/checkout@v4 - id: push run: | docker build -t $REGISTRY/app:$GITHUB_SHA . docker push $REGISTRY/app:$GITHUB_SHA echo "digest=$(docker inspect --format='{{index .RepoDigests 0}}' $REGISTRY/app:$GITHUB_SHA)" >> "$GITHUB_OUTPUT" deploy-staging: needs: build environment: staging steps: - run: ./deploy.sh --image ${{ needs.build.outputs.digest }} deploy-prod: needs: deploy-staging environment: production # required reviewers attach here steps: - run: ./deploy.sh --image ${{ needs.build.outputs.digest }}

Configuration. Injected at deploy time, never baked. ConfigMaps and Secrets, Helm values per environment, env vars: the image stays byte-identical. In Kubernetes the Deployment references registry/app@sha256:...; changing the digest is what triggers a rollout, and the pod's imageID reports the digest that actually ran. Argo CD syncs the pinned digest from Git, with sync windows or manual sync as the production gate.

Failure modes.

  • A rebuild inside the deploy job "just to add config". Detect by comparing digests across environments: they must be equal.
  • Tag re-push. Detect by comparing kubectl get pod -o jsonpath='{.status.containerStatuses[0].imageID}' against the promoted digest and alerting on drift.
  • Config compiled in (NODE_ENV=production baked at build), so the staging artifact is not the production artifact.
  • Base image drift: rebuilding the same commit a week later picks up a re-pushed python:3.12-slim and produces a different digest. Two builds of one commit are not the same release.
  • Secrets written into layers, which then travel to every environment.

Gates. They attach to the digest, not to a branch. GitHub environment protection rules with required reviewers, Argo CD sync windows, and deployment records linking digest → approver → timestamp. SLSA provenance ties the digest back to the source commit and builder, so the approval is provably about the artifact that shipped.

When not to. Genuinely environment-specific builds (native compilation, different CPU architecture, licensed binaries) should be separate artifacts, labelled honestly rather than claimed as parity. And if config differs between staging and production, staging did not test production's behaviour: validate config against a schema and keep the staging config shape identical to production's.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

Design a fast but trustworthy CI job graph.

Answer

Assumptions I'd state first: trunk-based, PRs land through a merge queue, GitHub Actions as the runner (GitLab rules:changes and Buildkite are equivalent), monorepo where a full cold run is ~25 min. If any of those is false the graph changes, so I'd confirm before drawing it.

Core answer

Three tiers, ordered by how cheap the signal is, with one build artifact feeding everything downstream.

  • Tier 0: every push, target <2 min. Format, lint, typecheck, unit, secret scan, license policy. Fully parallel, no edges between them.
  • Tier 1: after Tier 0, on PR. Build once, then fan out integration, migration, e2e, perf, a11y against that artifact.
  • Tier 2: gated on Tier 1 evidence. Attest/sign/publish. Release consumes the same digest.
stageillustrative wall timeruns on
lint + typecheck90 severy push
unit (sharded 4×)3 min → 50 severy push
build + upload artifact2 minPR, once
integration / migration8 minPR, after build
e2e / perf / a11y12 minPR, after build

Critical path is build + longest downstream, not the sum. Sharding unit 4× moves the PR path from ~25 min to ~14 min; sharding integration is the next lever, and adding runners only helps once queue wait exceeds execution time.

Why one artifact

If each stage rebuilds, the bytes you tested and the bytes you ship diverge: different lockfile resolution, different toolchain patch, different env. Upload once (actions/upload-artifact v4 artifacts are immutable and carry a digest), pin downstream jobs to that digest, and attest that digest with actions/attest-build-provenance (Sigstore). "Works in build, fails in e2e" then means a real environment difference, not a rebuild.

Cache trust boundaries

Key caches on content, e.g. hashFiles('**/package-lock.json') plus toolchain version. GitHub scopes caches per branch, lets the default branch's cache be read by all branches, and blocks fork PRs from writing, but a same-repo branch can still write a key a later default-branch job reads. So: never cache anything that feeds attestation, and treat a cache miss as slow but correct, never as a different result. Default limits are 10 GB per repo with entries evicted after 7 days unused; a cold-cache run is the test that the graph is still correct.

Path rules and the merge queue

paths: filters are the classic trap. A required check that is skipped reports as not-success, and the merge queue (which tests the merged result on gh-readonly-queue/..., not your PR head) will sit blocked. Required checks must always run; put the path decision inside the job (dorny/paths-filter output) so it exits 0 with a clear "not applicable" rather than never starting.

Trade-offs

More parallelism when the critical path is one long stage. Fewer gates when a check's historical catch rate is near zero and a later stage catches the same defect class. The criterion: a check earns its slot if it catches a defect no later stage catches, or catches it materially cheaper.

Failure modes and detection

  • Flaky test. Detect from JUnit XML across runs, not from vibes. At a 2% flake rate on a 500-test suite you get ~10 spurious failures per run; devs start rerunning reflexively and real failures get waved through.
  • Silently skipped path. A nightly job runs the full graph ignoring path filters and diffs the result set.
  • Stale or poisoned cache. Periodic cold-cache run; any divergence is a cache bug.
  • Queue saturation. Track p95 queue wait separately from execution; if queue dominates, add runners, don't shard.

What would change my answer: a repo whose full suite is under 2 minutes gets one job, no graph. A high-blast-radius release (payments, auth) gets more gates, not fewer: the speed/trust dial moves with the cost of a bad ship, not with developer patience.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Optimize a slow pipeline responsibly.

Answer

Core answer (first 90 seconds)

Clarify three things before touching anything: which pipeline, what target metric, and what safety budget. Assume a monorepo on GitHub Actions with p95 wall-clock of 40 minutes, and a hard constraint that escaped defects must not rise. The responsible order is: measure the critical path, cut it, then make every speedup reversible and backed by evidence.

Measure first, from the CI API rather than memory. A worked breakdown:

stagep50p95
setup + checkout + install4 min6 min
build6 min9 min
unit + integration tests18 min25 min
lint / typecheck2 min3 min
e2e8 min12 min

The critical path is tests. Amdahl's law bites: if tests are 25 of 40 minutes and you halve them, you land at 27.5 minutes. A 31% cut, not 50%. Optimize the biggest stage, not the easiest one.

Cutting the path

Parallelize the test stage across N shards. 25 min / 8 shards ≈ 3.1 min plus ~30 s scheduling overhead. But each shard re-runs setup, so 8 × 6 min = 48 min of runner time: you traded wall-clock for cost. Cap concurrency to what the runner pool actually allows.

Cache content-addressed, keyed on the lockfile hash, never a mutable tag:

YAML
- uses: actions/cache@v4
  with:
    path: ~/.npm
    key: npm-${{ hashFiles('**/package-lock.json') }}

A lockfile-hash key means a hit is provably the same dependency set; a latest tag can serve a stale or poisoned tree. Bazel's remote cache and Nx's computation cache work the same way: outputs keyed on inputs.

Test selection only from a validated dependency graph (Bazel target graph, Nx affected, pytest-testmon). If the graph cannot prove a change is isolated (generated code, config, a shared schema) fall back to the full suite. Selection without fallback is exactly how escaped defects rise.

Trade-offs and deciding criteria

Sharding costs runner minutes linearly and needs balanced shards. Caching carries cold-start and poisoning risk. Selection risks missed transitive dependencies. Choose by where the time actually is and what the safety budget tolerates: if tests dominate, shard; if install dominates, cache; if the suite is huge and changes are usually isolated, select with fallback.

Failure modes and detection

  • Cache key collision serving wrong artifacts: detect via build failures immediately after a cache hit, or a checksum mismatch.
  • Shard imbalance leaving one 20-minute straggler: detect via a per-shard duration histogram.
  • Selection missing a transitive dep: detect via escaped-defect rate broken down by change type.
  • Resource caps causing OOM kills: watch runner exit codes, not just pass/fail.

Close on the deciding condition: if escaped defects rise after enabling selection, revert selection first. It is the least reversible win. Sharding and caching are cheap to undo; a missed test is not.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-8

Design safe pipeline caching.

Answer

Clarify first: caching what? Dependency downloads, compiled outputs, and test results have different threat models. Package caches are mostly self-verifying; build outputs are not. I'll assume a shared cache store, a release job holding a write token, and PR code that must not influence it, with GitHub Actions as the concrete case.

Core answer: a cache is an untrusted input. Key it on everything that determines the bytes, scope it by trust tier, and verify anything you execute.

Mechanism. Two properties of the Actions cache drive the design:

  1. Entries are immutable: a second save with an existing key fails, so an attacker cannot overwrite a key you already wrote.
  2. restore-keys is a prefix match and returns the most recently created entry matching that prefix.

The attack is (2), not (1). Trace it. Cache entries in the repo:

keycreatedwriter
Linux-build-9f2c1aMar 1release job on main
Linux-build-pr-4471Mar 5PR job

Release job:

YAML
- uses: actions/cache@v4
  with:
    path: dist
    key: ${{ runner.os }}-build-${{ github.sha }}
    restore-keys: ${{ runner.os }}-build-

The exact key Linux-build-<new sha> misses. The prefix Linux-build- matches both entries; the most recent wins, so the job restores Linux-build-pr-4471. It then builds on top of, or publishes, attacker-controlled dist/. Same story for a restored node_modules/.bin (executed) or a restored test binary (runs with the release token).

The writer has to be able to write into a scope the release job reads. Fork PR caches are scoped to the PR's merge ref and are not readable from the default branch, so the realistic writers are a same-repo branch, a pull_request_target or workflow_run job running in base-repo context, or a self-hosted runner whose cache directory is shared across repos.

Rules.

  • Key on content, not time. hashFiles('**/package-lock.json') plus runner.os plus the toolchain version. A key containing github.sha never hits, so you pay upload cost for nothing.
  • Scope by trust tier. Separate prefixes per tier, and split restore from save so a PR job can restore but never write into the release namespace:
YAML
- uses: actions/cache/restore@v4
  with:
    path: dist
    key: main-${{ hashFiles('**/package-lock.json') }}
    restore-keys: main-
- run: npm ci && npm run build
- uses: actions/cache/save@v4
  if: github.ref == 'refs/heads/main'
  with:
    path: dist
    key: main-${{ hashFiles('**/package-lock.json') }}

PR jobs use a pr- prefix; the release job only ever restores main-.

  • Never cache secrets or anything derived from them: .npmrc with a token, ~/.aws, a signed URL. Caches are readable by anyone who can read the branch.
  • Verify what you execute. npm checks tarball integrity against the lockfile's sha512, so caching ~/.npm is low risk. node_modules and dist/ are not: verify with sha256sum -c against a manifest, or cosign verify for artifacts, or don't cache them.

Failure modes.

  • Prefix collision: the release job restores a PR's artifact. Detect by logging the restored key and its writer, and by diffing the restored digest against a clean rebuild nightly. Cost: one poisoned release.
  • Stale cache: the key omits the compiler version, so you restore objects built by an older toolchain. Symptom: link errors or subtly wrong binaries. Detect with a canary job that builds clean and compares test results.
  • Eviction churn: GitHub caps a repo at 10 GB and evicts entries unused for 7 days. Per-package caches in a monorepo thrash; hit rate drops and build time climbs. Fix with one coarse key, not twenty fine ones.

Trade-off: caching wins when restore is much cheaper than rebuild. A 12-minute monorepo build versus a 40-second restore. It loses when install is under ~20 seconds, when the key changes every commit, or when verification costs more than the rebuild.

What would change my answer: a content-addressed store like Bazel's remote cache, where poisoning needs a hash collision, makes the trust-tier machinery far less important.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Reduce pipeline flakiness without hiding failures.

Answer

Core answer (the first two minutes)

"Flaky" means the same commit with the same inputs produces different verdicts. Three things look identical in CI, and separating them is the first move:

  • Nondeterministic test: fails, then passes on a rerun of the identical build.
  • Real intermittent product bug: a race in the service under test. The test is doing its job; it stays red and gets a bug ticket.
  • Infrastructure: node OOM, registry timeout, container eviction.

Only the first is a test defect, and only the first is eligible for quarantine.

Assumptions I would state out loud: per-test results (JUnit XML) are ingested into a queryable store; CI runs in ephemeral containers; roughly 12,000 tests, 20 min p50 suite, sharded across parallel nodes.

The answer: treat flakiness as a defect class with a metric, a budget and an owner, exactly like a production defect. Define flake rate per test as (runs that failed and then passed on a rerun of the same commit) / (total runs) over a 7-day window. Set a suite budget, for example no test above 0.1% and no more than 0.5% of tests flaky in a week, and show it on the CI dashboard. Then fix by root cause in frequency order, and keep quarantine as a time-boxed, owned state rather than a bin.

Failing at the mechanism is what makes it recur

Four buckets cause nearly all of it, and each fix removes one variance source, which is why "fix isolation" on its own is not a plan:

  1. Nondeterminism inside the test process. Unseeded RNG; iteration order (Go deliberately randomizes map iteration; Python randomizes str hashing unless PYTHONHASHSEED is pinned); default locale/timezone; wall-clock reads. Fix by seeding and by injecting a clock so "now" is an argument, not a global.
  2. Shared state. Singleton objects, database rows never cleaned, a hard-coded port 8080, a fixed test user ID, a warm build cache. Fix by binding to port 0 and letting the OS assign, and by giving each worker its own schema or a rolled-back transaction: leaked rows then cannot cross tests.
  3. Ordering and parallelism. A test that passes alone and fails in a shard because a sibling left data behind, or xdist/Jest workers racing one fixture. Reproduce by running the whole shard, not the single test.
  4. Environment. Third-party sandbox calls, rate limits, and CPU throttling when eight shards land on one 4-core node. Reproduce with a small load test at real shard density before blaming the test.

The arithmetic that decides the policy

At 12,000 tests with an independent 0.5% flake probability each, expected flaky failures per run = 12,000 * 0.005 = 60. That is why "the suite is always red", not one bad test, 60 coin flips. Retrying the suite until green hides exactly those 60 signals.

Detection: take the top 20 tests by flake rate and run each 10 times on the same commit in the same container. 0/10 failures means environment-sensitive; any failure in 10 gives a reproduction worth debugging.

What the failure modes cost: each false red costs 10-15 minutes of engineer triage, and the real damage is trust decay. A suite people rerun reflexively is how a genuine failure ships. Infrastructure saturation is detected by correlating failures with node CPU steal and shard density, not by reading test code; it is fixed by lowering shard density and is never evidence that the test is bad.

Quarantine versus fix now: the deciding rule

signaturedetectionfix
passes alone, fails in shardrun alone versus full shardper-worker schema, port 0
fails only around 02:00group failing runs by time-of-day and nodeinjected clock, TZ=UTC pinned
fails as shard density risescorrelate with node CPU stealfewer shards per node
fails on third-party callgrep the run's HTTP logrecord/replay or sandbox stub

Quarantine when the failure is not reproducible in 10 attempts, the owner is unknown, and the test is not the only guard for money, auth or data integrity. Annotate it, give it an owner, a ticket and a 10-working-day deadline, and make CI print the count: "38 quarantined of 12,000 tests, 13% of the payments module." That second figure decides the case. Thirty-eight tests spread thinly is cheap; thirty-eight concentrated in payments is a coverage hole to close this sprint or replace immediately with a deterministic test.

Never retry until green. If retries exist at all, confine them to one retry on a network-error class and record first failure and retried pass as a separate flake metric. Reintroduce a quarantined test only after repeated green runs on unchanged code, and watch escaped defects by tracking incidents in modules that hold quarantined tests.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Secure pipeline secrets and logs.

Answer

Assumptions: GitHub Actions on GitHub-hosted runners, deploying to AWS, repo accepts fork PRs. The same three boundaries apply on GitLab or Jenkins; only the names change.

Core answer. A secret is only as safe as the least-trusted code that runs in the same job as it. So the first move is not a vault, it is a job split: untrusted code (build, test, anything derived from a PR) runs with no secrets and a read-only token; trusted code (deploy) runs in a separate job, gated by an environment with required reviewers, and fetches a short-lived credential. The second move is to stop having long-lived secrets at all: federate.

Federation. GitHub mints an OIDC JWT per job when you set permissions: id-token: write. AWS exchanges it via AssumeRoleWithWebIdentity for STS credentials. Default session is 3600 s, capped by the role's max session duration (1 h default, configurable to 12 h). Nothing is stored in the repo, and the blast radius is one hour instead of "until someone remembers to rotate".

The trust policy is where this goes wrong. It has to pin the sub claim:

JSON
"Condition": {
  "StringEquals": {
    "token.actions.githubusercontent.com:aud": "sts.amazonaws.com",
    "token.actions.githubusercontent.com:sub": "repo:acme/api:environment:prod"
  }
}

Without the sub condition, any GitHub repository on the planet can assume the role. That is the single most common OIDC misconfiguration.

YAML
jobs:
  deploy:
    runs-on: ubuntu-latest
    environment: prod          # required reviewers gate this
    permissions:
      id-token: write
      contents: read           # everything else denied
    steps:
      - uses: actions/checkout@v4
      - uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: arn:aws:iam::111122223333:role/gha-deploy-prod
          aws-region: eu-west-1
      - run: ./deploy.sh

Logs. Masking is a filter on the log stream, not a boundary on what the job can read. GitHub replaces occurrences of a secret's literal value; anything derived from it passes straight through:

set -x
TOKEN=$(vault kv get -field=token secret/deploy)
echo "$TOKEN" | base64

The base64 line prints in full. Same for jq -c, URL-encoding, or splitting the value across two echoes. Practical rules: never set -x in a step that touches a credential, use ::add-mask:: on derived values, and do not set ACTIONS_STEP_DEBUG in a repo that handles secrets. It turns on verbose logging for every step.

Other exfiltration channels.

ChannelWhy it leaksControl
Artifactsdownloadable by anyone with repo read; world-readable on a public repoupload explicit paths, never **
Cachebranch-scoped; PR caches are isolated, but a cache written on a shared branch is inherited downstreamkey on lockfile hash; never cache credentials
Job summary / annotationsattacker-controlled text rendered in the UItreat as untrusted, escape it
Fork PRno secrets and a read-only GITHUB_TOKEN by default: pull_request_target restores bothnever check out PR head under pull_request_target

Failure modes and detection.

  • Trust policy missing sub: detect with CloudTrail AssumeRoleWithWebIdentity events whose sub claim does not match repo:acme/*. Cost: full role access from a throwaway repo.
  • pull_request_target plus actions/checkout of github.event.pull_request.head.sha: PR code runs with secrets and a write token. Detect by grepping workflows; actionlint catches syntax, not this.
  • Masking bypass: plant a canary secret, then grep the archived logs and their base64 for it after the run. If it shows up, a transform leaked it.
  • On suspicion: revoke the trust policy or rotate the static key. The STS session dies within the hour.

When the vault is the wrong answer. If untrusted code runs in the same job, a vault just hands the secret to the attacker: it buys audit and rotation, not isolation. Isolation is the job split plus the environment gate. And if the target genuinely has no OIDC (a SaaS that only issues static API keys), you have to store it: scope it to one environment with required reviewers, rotate on a schedule, and pin it to a single job.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Design runner isolation across trust levels.

Answer

What I'd say first

Assume three trust levels: untrusted (fork PRs, external contributors), internal (merged code, trusted employees), deploy (holds production credentials). The goal is that a compromise at one level cannot persist, reach production, or escalate into another level. I'd answer with the isolation boundary per level, then the controls that make the boundary real.

Boundaries

TierBoundaryWhy
UntrustedmicroVM or gVisor sandbox, no host socket, no IMDSKernel exploit in build code must not reach the host
Internalcontainer on an ephemeral VM, per-job identityTrusted code, but still no prod credentials
Deployseparate account/project, OIDC to short-lived credentials, immutable artifact onlyBlast radius is production

GitHub-hosted runners are fresh VMs per job; self-hosted runners are not, so ephemerality is something you build. GitLab's docker executor reuses the host kernel: that is the boundary you are accepting.

Why the classic escapes work

Two controls matter more than the rest. First, the instance metadata endpoint at 169.254.169.254. A build step that can reach it can fetch the instance role's credentials: the standard SSRF-to-cloud-account path. IMDSv2 requires a PUT to obtain a session token and a hop limit of 1, which stops the request from a container whose network adds a hop. Second, /var/run/docker.sock. Mounting it gives the job root-equivalent control of the host daemon: docker run -v /:/host --privileged and the host filesystem is yours. Neither is exotic; both are one line in a CI config.

Egress

Default-deny, allowlist by destination. A runner that can reach the internet can exfiltrate a token or pull a malicious dependency mid-build. Example policy (addresses illustrative):

# untrusted tier: allow registry + package mirror, drop everything else
iptables -A OUTPUT -d 10.0.1.10 -p tcp --dport 443 -j ACCEPT   # internal registry
iptables -A OUTPUT -d 169.254.169.254 -j DROP
iptables -A OUTPUT -j DROP

Resource caps: Docker's --cpus=2 --memory=4g per job, backed by cgroups v2, plus a wall-clock timeout. Without a cap, one job starves the pool.

Failure modes and how you see them

  • Pool exhaustion: untrusted jobs queue behind a long build. Detect with queue depth and p99 wait time per tier; alert when untrusted wait exceeds the SLO. The cost is developer latency, not correctness.
  • Cache poisoning across tiers: a shared layer cache lets an untrusted job write a layer the deploy job later pulls. Detect by scoping cache keys per trust level and diffing image digests before deploy.
  • Cleanup failure: a reused runner keeps a workspace with a token in it. Detect by checking disk usage and file count before each job, and by rotating runner instances on a schedule.
  • Credential leakage: a long-lived token in the environment. Detect with secret scanning on logs and an audit of token TTLs.

Trade-offs

Container isolation is cheapest and fastest but shares the kernel. gVisor adds a user-space kernel and syscall interception: good for untrusted code, and it costs on syscall-heavy builds. Firecracker microVMs give a hardware boundary; AWS's launch material claims boot in as little as 125 ms with roughly 5 MiB per-microVM overhead. Full VMs are the strongest and slowest. Use the lightest boundary that matches the trust level: containers for internal, microVM or gVisor for untrusted, a separate account for deploy.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

Secure CI for untrusted pull requests.

Answer

The 90-second answer. GitHub already hands you the safe default: a pull_request event from a fork runs with a read-only GITHUB_TOKEN and no secrets. The job is not to invent isolation: it's to avoid undoing that default, and to make sure nothing the PR runner produced gets promoted on its word alone. Three layers: give untrusted code nothing worth stealing, let it persist nothing, and promote only what a trusted context rebuilt or verified.

Why each control exists.

The biggest footgun is pull_request_target. It runs in the base repo's context (secrets available, token writable) which is what you want for labelling a PR and exactly what you must never combine with actions/checkout of github.event.pull_request.head.sha. That pairing hands write credentials and secrets to attacker-controlled code. The event name is the entire difference between safe and owned.

Read-only token: fork PRs get contents: read and no secrets by default. The failure is widening it (permissions: write-all, or secrets: inherit) so a bot can comment. Comment from a separate workflow_run job instead.

Why a trusted-branch rebuild closes the artifact gap: the PR build's output is attacker-controlled end to end. They can edit the Dockerfile, the build script, the compiled binary. A digest proves the bytes didn't change in transit; it says nothing about where they came from. Rebuilding the merged SHA in a trusted context and comparing digests makes the merge commit the provenance, not the PR's runner. Provenance attestation (SLSA, actions/attest-build-provenance) is the cheaper substitute: it signs a statement binding digest → repo → commit → workflow, and you verify signature and source fields at deploy. It's weaker, it trusts the build environment, but it's the only option when you can't rebuild.

Trade-off. Rebuild doubles CI cost and adds minutes of latency. At 200 PRs/day, rebuilding every artifact is waste. Rebuild what ships: release binaries, container images; use provenance for the rest; skip both for artifacts that never leave CI (test reports, coverage). The stricter option isn't worth it when the artifact has no path to production.

Failure modes and how you'd catch them.

  • Fork PR exfiltrating a scoped token. A build step handed a cloud credential, or a PR job with id-token: write. Detection: policy check that no job checking out PR code references secrets.*; alert on it. Cost: one leaked token is account access until rotation.
  • Cache poisoning. GitHub scopes caches per branch/merge ref, so a fork PR can't write the base branch's cache, but a self-hosted runner with a persistent workspace, or a shared package proxy, carries state across jobs. Detection: run untrusted jobs on ephemeral runners with no persistent volume; diff cache keys between PR and base.
  • Resource exhaustion. Default job timeout is 360 minutes; a fork PR that loops or mines burns runner minutes. Detection: timeout-minutes: 15, concurrency caps, alert on queue depth.
  • pull_request_target plus head checkout. Detection: a lint rule over workflow files matching both strings.
YAML
# untrusted build — fork PRs: read-only token, no secrets
on: pull_request
permissions:
  contents: read
jobs:
  build:
    runs-on: ubuntu-24.04      # GitHub-hosted, ephemeral
    timeout-minutes: 15
    steps:
      - uses: actions/checkout@v4
        with: { persist-credentials: false }
      - run: npm ci --ignore-scripts
      - run: npm test
      - uses: actions/upload-artifact@v4
        with: { name: dist, path: dist/ }

The promote job runs on workflow_run, in base context, with id-token: write for OIDC to the registry, and treats the downloaded artifact as data, never as code to execute.

triggerGITHUB_TOKENsecretsrun PR code?
pull_request (fork)read-onlynot passedyes
pull_request_targetper permissions:passednever checkout head
workflow_runper permissions:passedno: artifact is data

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Govern third-party pipeline actions and tools.

Answer

Assume GitHub Actions, an org with a few hundred repos, and third-party actions pulled from the Marketplace. The core answer: every third-party action is untrusted code that runs with your job's token, so you control three things. What code runs, what it is allowed to do, and how it changes. Inventory is the prerequisite, not the answer.

What code runs. uses: actions/checkout@v4 does not pin v4. The runner resolves the tag to a commit at run time, so a maintainer, or anyone who takes over the maintainer's account, can force-push v4 and your next run executes different code with your token. A full commit SHA is content-addressed: uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2. The comment keeps it readable; Dependabot's github-actions ecosystem opens a PR when the SHA moves, so you get the update as a reviewable diff instead of silently.

What it can do. The GITHUB_TOKEN is minted per job and expires when the job ends. Its scopes come from permissions. Repos created after February 2023 default to read-only contents and packages and none elsewhere; older repos may still default to write on many scopes, so set it explicitly:

YAML
name: build
on: [push]
permissions: {}            # all scopes none at workflow level
jobs:
  build:
    runs-on: ubuntu-24.04
    permissions:
      contents: read       # only what checkout needs
    steps:
      - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
      - run: make test

A compromised action in that job can read the repo and nothing else. Give it contents: write and the same action can push to main and cut a release. For cloud access, use OIDC (id-token: write) so the job exchanges a short-lived token instead of holding a stored secret: there is no long-lived credential to exfiltrate.

How it changes. Compare the options honestly:

approachinjection resistanceupdate costwhen it wins
floating tag @v4none: tag is mutablezerofirst-party action, job holds no secrets
SHA pin + Dependabothighlow, automated PRthe default for third-party
vendored forkhigh, you own patcheshighupstream abandoned, action is critical
internal mirror with digest checkhigh if verifiedmediumair-gapped, or registry outage tolerance

The deciding criterion is how much write scope the job holds and how fast you can review an update. A job with contents: write or cloud credentials justifies SHA pinning and a mirror; a lint job with permissions: {} does not.

Failure modes and how you see them.

  • Tag re-point or compromised maintainer: the resolved SHA changes without a version bump. Detect by diffing resolved SHAs between runs; Dependabot surfaces it as a PR.
  • Typosquat (action/checkout for actions/checkout): detect with an allowlist of trusted orgs and a required review on any new uses: line.
  • pull_request_target plus a checkout of the PR head: fork code runs with base-repo secrets. Detect by grepping workflows for pull_request_target and auditing what they check out.
  • Cache poisoning: PR-created caches are scoped to the PR merge ref and are not readable by the base branch, but jobs inside the same PR can poison each other. Key caches on a hash of the lockfile.
  • Persistent self-hosted runners: state and credentials survive between jobs. Use ephemeral runners that are torn down per job.

What changes the decision: if the action is first-party and the job holds no secrets, a floating tag is fine. The moment a job can write or reach a cloud account, pin the SHA, drop the token to the minimum scope, and route updates through review.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

Migrate from long-lived deployment keys to OIDC.

Answer

Assumptions: GitHub Actions as CI, AWS as the cloud (GCP/Azure have the same shape), and the keys being replaced are IAM user access keys sitting in repo secrets.

The 60-second answer. Stop storing a credential. The workflow asks GitHub for a signed JWT that describes what is running (repo, ref, environment) and the cloud exchanges that JWT for temporary credentials through a trust policy you control. Nothing long-lived exists to leak, and the credential is bound to the job: the JWT is short-lived, and the session it buys is bounded by a duration you set.

Mechanism. The job needs permissions: id-token: write. The runner then exposes ACTIONS_ID_TOKEN_REQUEST_URL and ACTIONS_ID_TOKEN_REQUEST_TOKEN; core.getIDToken('sts.amazonaws.com') POSTs to that URL and returns a JWT signed by issuer https://token.actions.githubusercontent.com. The claims that matter: aud (the audience you asked for), sub (e.g. repo:acme/api:ref:refs/heads/main, or repo:acme/api:environment:prod), plus repository, ref, environment, job_workflow_ref. The workflow calls sts:AssumeRoleWithWebIdentity with that JWT; AWS validates the signature against GitHub's JWKS, checks aud == sts.amazonaws.com, checks sub against the trust policy condition, and returns credentials with DurationSeconds you set: default 3600, max 43200.

JSON
"Condition": {
  "StringEquals": {
    "token.actions.githubusercontent.com:aud": "sts.amazonaws.com",
    "token.actions.githubusercontent.com:sub": "repo:acme/api:environment:prod"
  }
}

Trade-offs. OIDC is not free. Per-repo, per-environment trust policies are N objects to maintain and they drift; one shared role with a sub condition is fewer objects but a wider blast radius, because the role's IAM permissions are still the real limit: OIDC fixes who can assume it, not what it can do. If the deploy target can't validate OIDC (an on-prem box with no route to the token endpoint, a legacy CI), a GitHub App installation token (1 hour) or a fine-grained PAT (max 1 year, orgs can cap shorter) is a legitimate intermediate: shorter-lived than a static key, but still a bearer secret you store and rotate.

Failure modes. A pull_request from a fork gets sub: repo:acme/api:pull_request and a read-only token, but if your trust policy matches repo:acme/api:*, that fork PR can assume the role. pull_request_target plus a checkout of the PR head is the classic escalation. Audience mismatch, asking for https://example.com while the policy expects sts.amazonaws.com, fails with AccessDenied and reads like a broken policy, not a bug. Renaming or transferring the repo changes sub, so every deploy breaks at once; matching only repository_owner means a brand-new repo in the org silently inherits deploy rights.

Migration. Inventory keys and their real permissions, pilot on non-prod, log both the exchange and the denials, then canary prod. Delete the static key only after the OIDC path has run clean through a full deploy cycle and you've confirmed the rollback.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

Design artifact provenance and verification.

Answer

Assumptions I'd state first: builds run on a hosted CI (GitHub Actions), artifacts are OCI images deployed to Kubernetes, and I own the build platform. If any of those is false (air-gapped, self-hosted runners, VM artifacts) the signing and verification choices change, so I'd confirm before designing.

The design has three stages: produce signed provenance at build, store it immutably, verify it at admission.

Producing provenance. The build emits an in-toto attestation with an SLSA provenance predicate (buildDefinition, runDetails) wrapped in a DSSE envelope. Signing is keyless via Sigstore:

  1. The CI job requests an OIDC token (id-token: write); claims include iss=https://token.actions.githubusercontent.com and sub=repo:acme/api:ref:refs/heads/main.
  2. cosign exchanges that token at Fulcio, which verifies the OIDC identity and issues a short-lived X.509 cert (10-minute validity) with the identity in the SAN.
  3. cosign signs the DSSE envelope with the ephemeral key and uploads it to Rekor, which returns a Signed Entry Timestamp and a Merkle inclusion proof.
  4. The private key is discarded.

That gives non-forgeable provenance without a long-lived signing key to steal.

Storing it. Attestations live alongside the image in the registry (OCI referrers) and in Rekor. Rekor is append-only, so retention is a matter of keeping the log and its signed tree heads; the transparency log is the evidence that a signature existed at a point in time.

Verifying at admission. A policy-controller or Kyverno webhook checks, before granting the pod its environment credentials:

CheckWhat it binds
Signature valid against Fulcio rootIntegrity
Cert SAN + issuer match expected identityWho built it
Rekor inclusion proof vs signed tree headIt was logged, not replayed
buildType / builder id match policyHow it was built
subject[].digest.sha256 == image digestThis attestation is for this artifact

The last row is the one people skip. Without binding the subject digest to the artifact being deployed, an attacker replays a valid attestation for a different image and provenance becomes decorative.

Trade-offs. SLSA build levels are the deciding axis: L1 is unsigned provenance (tamper-evident only), L2 is signed by a hosted platform, L3 is hardened so even someone with build access can't forge it. L3 costs you isolated, ephemeral builders and no user-controlled steps in the signing path. Keyless signing needs OIDC plus network reach to Fulcio and Rekor; air-gapped or self-hosted setups need a self-hosted log or long-lived KMS/HSM keys with rotation. For throwaway dev clusters, the webhook latency (tens of ms per admission) and the Fulcio/Rekor dependency usually aren't worth it.

Failure modes. Key compromise: keyless caps exposure at the 10-minute cert window; long-lived keys belong in an HSM/KMS with an offline root. Detect misuse by monitoring Rekor for entries under your identity you didn't create and alerting on unexpected SANs. Replay: caught by the digest-binding check above. Verification failure: the webhook fails closed and denies, emitting an event you alert on; the break-glass path is a signed, expiring exception, never disabling the webhook. And provenance proves claims and integrity, not correctness: keep tests and runtime verification running.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Respond to suspected CI runner compromise.

Answer

Assumptions I'd state first: self-hosted GitHub Actions runners in a shared pool, org-level OIDC into AWS, artifacts promoted to prod by digest. If any of those is false the plan changes, and I'll say where.

Treat this as a supply-chain incident, not a host incident. A runner is a trusted execution environment holding credentials for your cloud, registry and signing. Assume everything it could reach is compromised until you can show otherwise. Order: contain, preserve, scope, re-establish.

Contain (first 15 minutes). Stop the runner service or set the runners offline: don't delete them, deletion destroys the evidence and the registration token. Freeze promotion: block any artifact built after the last known-good commit from reaching prod. On revocation there's a real trade-off: revoking immediately is safe but tips off the attacker and ends your chance to watch what they do with the credentials. If you have egress logging on the runner, watch for an hour first; if you don't, revoke now.

Preserve. Snapshot the VM disk, not just logs. On GitHub self-hosted runners that's _diag/ (runner logs), _work/ (checkouts, _temp scripts) and the live environment of any running job: ACTIONS_ID_TOKEN_REQUEST_TOKEN and ACTIONS_RUNTIME_TOKEN sit in there. On GitLab, journalctl -u gitlab-runner plus config.toml, which holds the runner token.

Scope: what could it mint? Enumerate, don't guess: GITHUB_TOKEN (job-scoped, expires when the job ends or at 24h), the OIDC ID token (minutes), the cloud role it assumes, registry push credentials, signing keys, deploy keys, cache write access.

The OIDC path is what turns a runner compromise into a cloud compromise. If the trust policy matches repo:org/repo:* or a branch wildcard, the attacker mints a token for any ref and assumes the role. The fix is pinning sub to repo:org/repo:environment:prod and aud to the provider, and requiring the environment: that's the difference between rotating a token and closing the path.

Cache poisoning is the quiet one. actions/cache entries are branch-scoped, so a compromised runner writes an entry that a later main job restores. Detect by diffing cache keys created in the window; remediate by bumping the key prefix so nothing restores the poisoned entry.

Re-establish. Rebuild runners from a verified image, ephemeral (config.sh --ephemeral), one job per runner. Rotate registration tokens (GitHub's expire in an hour anyway), deploy keys, registry credentials, and the cloud role's trust policy. Rebuild artifacts from source on a clean builder and compare digests against what's deployed: cosign verify or docker manifest inspect.

Trade-off: full fleet rebuild vs scoped quarantine. Scoped is hours; full rebuild is days. Scoped is only honest if you can prove the other runners didn't share a cache backend, a secret store, or a cloud role. If they do, scope is a fiction and you rebuild.

Failure modes. Blocking promotion doesn't unpublish: find what already shipped. A stolen registration token lets the attacker re-register a runner for up to an hour. A modified workflow file on a branch survives a runner rebuild.

Indicators to look for: a runner registered that nobody created, an OIDC token minted for a ref that never deploys, cache writes from a runner that doesn't run that branch, workflow_dispatch runs at odd hours.

What changes the decision: if the runner was ephemeral with no OIDC and no cloud secrets, this is a host incident. Patch and move on. If a long-lived cloud key sat in a repo secret, you're in a full credential-rotation incident, and the clock is that key's lifetime, not yours.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-1

Design a secure CI/CD pipeline for a growing service.

Answer

Assume a Kubernetes service, CI on GitHub Actions, a cloud with OIDC federation (AWS/GCP/Azure), and a platform team of two to five. One decision shapes the rest: build the artifact once, sign it, and promote that exact digest. Rebuilding per environment means the thing you tested is not the thing you shipped.

Identity, not secrets. CI never holds a static cloud key. The job requests an OIDC token and exchanges it for a role via AssumeRoleWithWebIdentity; the trust policy pins the repo and branch (repo:org/svc:ref:refs/heads/main). AWS STS issues a session of 3600 s by default, capped at 43200 s: set it to the job's expected duration, not the max.

YAML
permissions:
  id-token: write      # mint the OIDC token
  contents: read
jobs:
  build:
    runs-on: ubuntu-24.04        # ephemeral, GitHub-hosted
    steps:
      - uses: actions/checkout@v4
      - uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: arn:aws:iam::123456789012:role/ci-push
          aws-region: us-east-1
      - run: |
          docker build -t "$IMAGE:$GITHUB_SHA" .
          docker push "$IMAGE:$GITHUB_SHA"
          DIGEST=$(docker inspect --format='{{index .RepoDigests 0}}' "$IMAGE:$GITHUB_SHA")
          cosign sign --yes "$DIGEST"
          echo "DIGEST=$DIGEST" >> "$GITHUB_OUTPUT"

Provenance and signing. The build platform emits a SLSA provenance attestation (builder identity, source commit, build inputs); cosign signs the digest keylessly via Fulcio and records it in the Rekor transparency log. Admission control (Kyverno or a Sigstore policy controller) rejects any image in the cluster without a valid signature from your identity, so a compromised registry push cannot run.

Promotion. Environments are separate deploy targets that accept a digest, not a tag. Each has its own role scoped to that namespace. Concurrency groups stop two deploys racing; production requires an approval. The manifest references image@sha256:..., so what is running is a fact, not a guess.

Progressive delivery. Argo Rollouts canary: 5% weight, then analysis every 60 s for five iterations against Prometheus. Error rate < 1%, p99 < 300 ms. At 200 rps, 5% is 10 rps, roughly 3000 requests over the window; a 1% error rate yields about 30 errors, enough to trip the gate. On failure the canary weight goes to 0 and the stable ReplicaSet keeps serving; no human is paged to roll back.

Rebuild per environmentBuild once, promote digest
artifactmutable tagimmutable sha256
provenanceper-env, unverifiableone signed attestation
rollbackrebuild old commitredeploy known digest
cost3× build minutes1× build, 3× deploy

Failure modes and detection.

  • Runner compromise: ephemeral runners, no persistent credentials. Detect via provenance showing an unexpected builder or egress to unknown hosts.
  • Credential misuse: OIDC tokens are short-lived. Detect via CloudTrail AssumeRoleWithWebIdentity from an unexpected repo or subject claim.
  • Partial deployment: canary analysis fails and auto-reverts. Detect via the Rollout's analysis run status and the running digest diverging from the intended one.
  • Dependency confusion: pin by digest, generate an SBOM. Detect by diffing SBOMs between releases.

Trade-offs. Build-once costs you a registry that must stay highly available and a promotion step that is a real deploy, not a copy. Canary needs traffic volume to mean anything: below roughly 50 rps the analysis window is too noisy, and blue-green with a full cutover is the better call. Keyless signing depends on Fulcio/Rekor availability; if you cannot accept that dependency, use a KMS-backed key and own the key custody.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Migrate a legacy rebuild-per-environment pipeline.

Answer

I'd assume the legacy pipeline rebuilds the same source per environment, with env-specific scripts, registries, and credentials. If the target is OCI images on Kubernetes, the migration is: build once in a trusted builder, emit an immutable digest plus SBOM, provenance, and signature, then promote that digest through environments while injecting runtime config. If the registry doesn't support tag immutability, turn it on (ECR has image tag immutability) or reference images by digest only.

The mechanism is content addressing. A tag like app:1.0 is mutable; a digest like sha256:abc... is the hash of the manifest and config. BuildKit can emit provenance and SBOM attestations, but the enforceable part is the signature and the admission check. Kyverno verifyImages or OPA Gatekeeper can require a cosign signature, an in-toto/SLSA provenance predicate, and a digest allowlist. If someone rebuilds the tag, the digest changes, the signature no longer matches, and admission denies the pod. That is why digest-pinning catches drift: the runtime cannot silently run a different binary.

Rebuild-per-envBuild-once promote digest
Artifact identityTag per env, often overwrittenDigest, immutable
ConfigBaked or patched at buildRuntime ConfigMap/Secret, env vars, feature flags
SecretsOften in build args or scriptsInjected at deploy from Vault/External Secrets
PromotionRebuild in each envSame digest through staging, canary, prod
RollbackRebuild old commit, hope parityRedeploy previous digest
Drift detectionCompare build logsAdmission denial, digest mismatch alert

A worked trace: build once with docker buildx build --push -t registry/app:1.0 .; record the digest, say sha256:abc... (hypothetical). Sign it: cosign sign --key cosign.key registry/app@sha256:abc.... Attach SBOM: cosign attest --predicate sbom.spdx.json --type spdxjson registry/app@sha256:abc.... Deploy staging with image: registry/app@sha256:abc...; Kyverno verifies signature and provenance. Promote the same digest to prod. If someone rebuilds registry/app:1.0, the new digest is sha256:def...; admission denies because the signature and provenance do not cover that digest. After deploy, query the pod's imageID and compare it to the expected digest; a mismatch is the canary alarm.

Alternatives matter. You can keep rebuilding but pin inputs and diff SBOMs, which is weaker because the build environment is still a variable. You can build once with runtime config, which is the default for most services. You must build separate artifacts when the difference is compiled: CPU vs GPU, FIPS, different native libraries, or kernel modules. The deciding criteria are how many environments, whether config is truly runtime, and how fast rollback must be. If env differences are compiled in, build-once is the wrong migration; use a variant matrix with distinct digests and promote each variant.

Failure modes: config drift when a script patches /etc/hosts or a license file at build time; detect by hashing the old and new root filesystems and diffing SBOMs. Secret leakage when credentials are baked into layers; detect with grype or trivy and registry scanning. Mutable tags overwritten in place; detect by admission denial or digest mismatch. Admission bypass if the webhook is not enforced on all namespaces; detect by policy audit mode and namespace labels. Rollback impossible if old rebuild credentials are retired too early; keep the old pipeline read-only until parity and rollback are proven. Non-reproducible builds from timestamps or network fetches; detect by rebuilding twice and comparing digests.

Cost: runtime config needs a config service or feature-flag path, secret injection, and an admission webhook that adds a policy call per pod. Measure that call; if it is too slow, cache decisions by digest. Hypothetically, 12 environments × 40 min rebuild = 8 h per release; one 40 min build plus 12 promotions at 2 min = about 64 min. Retire environment rebuild credentials and caches only after the old and new artifacts pass parity, rollback has been exercised, and the digest allowlist is the only deploy path.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Deploy progressively with automated guardrails.

Answer

Assumptions first. Stateless HTTP service on Kubernetes, 20k rps at peak, 99.9% availability SLO over a 30-day window, and a pipeline that already emits an immutable image digest. If any of those is false (stateful singleton, batch job, no traffic split) the shape changes, and I'll say how at the end.

The answer. Progressive delivery is four decisions made before the deploy: the release unit, the cohort, the traffic steps, and the guardrail that gates each step. After that a controller, not a human, advances or aborts.

Release unit: one image digest plus its config and migration version. If a migration is in the release, it's expand/contract: additive schema first, backfill, dual-write, and the contract step ships a release later. That is what makes rollback possible at all.

Cohort: canary pods carry their own label so every metric can be filtered to them. Sticky sessions and internal-only routing both break this: the canary has to see the same request mix as the baseline.

Guardrail mechanism: it is a control loop. Argo Rollouts' AnalysisTemplate (Flagger's canary CRD is equivalent) runs a Prometheus query every 60s, evaluates a successCondition, and counts failures; failureLimit: 2 aborts the rollout and sets canary weight to 0. The query is canary-scoped:

PROMQL
sum(rate(http_requests_total{rollout="canary",code=~"5.."}[5m]))
/ sum(rate(http_requests_total{rollout="canary"}[5m]))

successCondition result[0] < 0.01, with a minimum sample count so a 2 rps canary doesn't pass on 40 requests.

Steps and gates:

steptrafficmin bakeadvance gateauto-halt
0shadow / internal30 minno new error signature vs controlany 5xx from a new code path
11%30 mincanary 5xx < 1%, p99 ≤ 1.2× baseline2 failed samples
25%1 h+ burn rate < 1burn > 14.4
325%2 h+ queue depth and DB p99 flatburn > 6
450%4 h+ capacity headroom ≥ 30%burn > 6
5100%———

Burn rate is what makes "sufficient evidence" concrete. A 99.9% SLO over 30 days is 43.2 minutes of budget. Burn rate 1 spends it exactly over the window; 14.4 spends 2% of it in one hour. So the halt rule is the standard multi-window pair: 14.4 over 1h/5m, 6 over 6h/30m, 1 over 3d/6h. The short window stops a recovered blip from holding the rollout.

Why canary-scoped matters: at 1% of 20k rps the canary carries 200 rps. A 5% canary error rate is a 0.05% global error rate: burn rate 0.5 against a 0.1% budget rate, below the 1.0 alerting threshold, so the global SLO never fires. The canary-scoped query fires on the second 60s sample.

Rollback versus roll-forward is decided by state compatibility. Binary-only change: rollback, weight to 0, done in seconds. Migration already applied: rolling the binary back leaves old code reading a new schema. Roll forward with the feature flag off, or isolate the canary. The gate is a migration-version check in the pipeline, not a judgement call at 3am.

Failure modes I've hit: guardrail blind spot when the canary cohort is unrepresentative. Detect by comparing request-mix histograms against baseline; flapping when a shared dependency blips. failureLimit plus a min-sample floor; and a "rollback" that leaves the schema ahead of the code. Detect by asserting the migration version at deploy time.

When not to use it: single-consumer queue partitions, stateful singletons, and batch jobs can't split traffic. There, dark-launch behind a flag and compare outputs offline.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Design a safe production approval process.

Answer

What I'd say first

Assume a 40-service SaaS on EKS, Terraform for infra, GitHub Actions building images, Argo CD syncing to prod, ~30 prod deploys a day, 12 engineers on call. The goal isn't to approve more carefully: it's to make most changes need no human at all, and spend human attention only where a mistake is irreversible or crosses a trust boundary.

Classify, then gate

Three classes, decided by blast radius and reversibility, not by who's asking:

ClassExamplesEvidence requiredApprover
Autostateless service deploy, config flag with kill switchimage digest, unit+integration tests green, canary at 5% for 10 minnone (policy bot)
Peeradditive schema migration, new IAM role scoped to one bucketTerraform plan diff, migration dry-run, rollback script1 engineer, not the author
Two-persondestructive migration, IAM *, VPC/network change, prod data deletionplan diff, blast-radius query, restore-drill evidence2 approvers incl. service owner

What the approver actually sees

An approval is a record bound to a digest, not a person saying "looks good":

approval:
  artifact: sha256:9f2c...   # image digest, not tag
  commit: 4a1b7e2
  plan_hash: sha256:c81d...
  evidence: [tests: pass, canary: pass, plan: 3 add 1 change 0 destroy]
  expires: 2025-06-14T18:00Z
  approvers: [alice, bob]

Why digest binding matters: a tag like app:latest is mutable, so approving it approves nothing. The pipeline could push different bytes a minute later. Binding to the sha256 means any rebuild produces a new digest and the approval is void. Same for plan_hash: if someone edits the Terraform after approval, the hash changes and the admission policy rejects the apply.

Expiry and environment isolation

Approvals carry a TTL, 24 hours is a reasonable default, and die on any of: new commit, new plan, failed re-run of tests, or expiry. They never copy across environments: a staging approval is not a prod approval, because the data, IAM and blast radius differ. Enforce this in the admission controller, not in a wiki.

Emergency bypass

Break-glass exists but is narrow: a named engineer, a single change, a 4-hour window, an alert to #incidents, and a mandatory review within 5 business days. The bypass still records the digest and the reason; it skips the approver, not the audit trail.

Failure modes

  • Rubber-stamping: approvers click through 40 requests/day. Detect by median time-to-approve under ~30 seconds with zero rejections; cost is a bad change shipping with a signature on it. Fix by cutting request volume, not by nagging.
  • Stale approval: approved Monday, applied Thursday after a rebase. Detect via digest/plan-hash mismatch at apply time; cost is unreviewed code in prod.
  • Bypass creep: break-glass used weekly. Detect by counting bypasses per month; if it's routine, the normal path is too slow: fix the path.
  • Approval as bottleneck: p95 approval wait over 4 hours. Measure it; if it dominates lead time, the gate is misclassified.

Metrics

Track approval latency (p50/p95), rejection rate, bypass count, and change-failure rate per class. If auto-class changes fail at the same rate as two-person ones, the extra ceremony isn't buying safety.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Coordinate concurrent deployments to one environment.

Answer

Assumptions I'd state up front: one shared environment (prod), deploys triggered by CI on merge to main, several services plus one Postgres database, and a runner pool that can pause or die mid-deploy.

The 90-second answer. Serialize on the environment, not the pipeline. One concurrency group per environment, plus a lease with a fencing token so a stalled runner that wakes up cannot mutate. Treat schema changes as a separate, ordered stream.

1. Serialize at the environment. In GitHub Actions:

YAML
concurrency:
  group: deploy-prod        # per environment, not per service
  cancel-in-progress: false # prod queues; preview envs set true

Documented semantics: at most one run is running and one is pending per group, and a newly queued run cancels the previously pending one. So cancel-in-progress: false is not a FIFO queue: a burst of ten merges leaves you deploying the tenth and silently dropping 2–9. If every commit must reach prod, put a real queue in front (one deploy workflow that pops from it); the concurrency group alone won't do it.

2. Fence the mutation. A concurrency group stops a second run from starting; it does not stop a paused first run from resuming. Take a Kubernetes coordination.k8s.io/v1 Lease before mutating. Leader-election defaults are leaseDuration 15s, renewDeadline 10s, retryPeriod 2s: the holder must renew every 2s or it self-evicts. Record holderIdentity, leaseTransitions, and the intended image digest. Pass leaseTransitions as a fencing token to every mutating call; the target rejects any token lower than the highest it has seen.

Arithmetic: runner A pauses 40s (GC or network partition) with leaseDuration 15s. The lease expires, B acquires it, leaseTransitions goes 1→2. A resumes and applies with token 1; the target rejects it. Without the token, both A and B write.

3. Schema changes are a separate stream. Expand/contract, never bundled with the app deploy. On PostgreSQL 11+, ADD COLUMN ... DEFAULT <constant> is metadata-only: no table rewrite. A volatile default, or a CHECK that validates existing rows, does rewrite and holds a lock. So: add the column nullable, backfill in batches, then ADD CONSTRAINT ... NOT VALID followed by VALIDATE CONSTRAINT, which takes only SHARE UPDATE EXCLUSIVE. Flyway/Liquibase serialize themselves on their history table, so two migration runners on the same DB will block each other rather than interleave.

Replace vs queue: the criteria:

SituationReplace (cancel pending)Queue (FIFO)
Preview / ephemeral envscorrect: only the tip matterswasteful
Prod, no migrations, cheap rollbackacceptablesafer, slower
Prod, ordered migrationswrong: drops a migrationrequired
Merge burst deeper than the queuesilently skips runsneeds an external queue

Failure modes and how you see them:

  • Runner dies mid-migration. Lease expires at 15s, the next run acquires it. Detect: leaseTransitions incremented with no matching success event, and a version row in the migration table with no completion marker. Fix: idempotent migration runner that records start and finish per version.
  • Duplicate webhook. Two runs, same SHA. Dedupe on (environment, commit SHA).
  • Timeout. The renew loop stalls past renewDeadline (10s) and the holder self-evicts while still running. Detect: a "leader election lost" log line, then a rejected write from the fencing token.
  • Manual kubectl edit during deploy. Detect drift before releasing the lock: Argo CD OutOfSync, or a digest mismatch.

Reconcile before releasing. Compare the digest recorded at acquire against kubectl get deploy <name> -o jsonpath='{.spec.template.spec.containers[0].image}', and confirm the applied migration version. Release the lease only when both match; otherwise leave it held and page.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Design GitOps deployment governance.

Answer

Assumptions: Argo CD 2.10+ as the reconciler, Kubernetes 1.29+, one Git repo per team, separate prod and non-prod clusters, Argo CD installed with its default RBAC (policy.default: role:readonly). Flux equivalents are named at the end.

The 90-second answer

Governance is four gates, not one: what can reach Git, what the reconciler may touch, what it may delete, and how a human gets back in during an incident.

Gate 1: what reaches Git. Branch protection on the environment branch, a CODEOWNERS entry per environment so prod changes need a prod reviewer, and signed commits. CI renders Helm/Kustomize and posts the rendered diff on the PR; the reconciler never resolves a moving chart version itself. Pin the chart version and the image by digest.

Gate 2: what the reconciler may touch. One AppProject per team: spec.sourceRepos limited to that team's repo, spec.destinations limited to the team's namespace on the target cluster, and spec.clusterResourceWhitelist left empty so no cluster-scoped object can be created. Identity is per-project RBAC in policy.csv:

p, role:team-payments, applications, sync, team-payments/*, allow
p, role:team-payments, applications, delete, team-payments/*, deny
p, role:team-payments, logs, get, team-payments/*, allow
g, payments-oncall, role:team-payments

Gate 3: what it may delete. syncPolicy.automated.prune defaults to false; leave it false in prod and enable it per-app only once the resource set is stable. Where prune is on, prunePropagationPolicy defaults to foreground, so a namespace deletion blocks until children are gone: keep that. Mark stateful or externally-owned objects with argocd.argoproj.io/sync-options: Prune=false,Delete=false so a bad manifest cannot take out a database.

Gate 4: ordering and windows. argocd.argoproj.io/sync-wave puts CRDs before CRs; pruneLast: true deletes only after the rest of the sync succeeds. spec.syncWindows blocks prod syncs over the weekend:

YAML
syncWindows:
  - kind: deny
    schedule: "0 16 * * 5"
    duration: 65h
    applications: ['*']
    manualSync: true

manualSync: true keeps break-glass available while the window is closed.

ControlSettingDefaultFailure it prevents
Auto-syncsyncPolicy.automatedoffunreviewed change reaching prod
Pruneautomated.prunefalsedeleting resources still in use
Self-healautomated.selfHealfalsereverting operator/HPA writes
Cluster-scopedclusterResourceWhitelistemptyteam creating ClusterRoles
Reconciletimeout.reconciliation180ssilent drift

Self-heal: the trade-off

selfHeal defaults to false. Enable it for stateless workloads where Git is the only writer; leave it off where another controller owns the field. The classic failure is self-heal against HPA: HPA writes spec.replicas, Argo CD sees OutOfSync and reverts, HPA scales again. A hot loop visible as argocd_app_info{sync_status="OutOfSync"} flapping and a rising argocd_app_reconcile rate. Fix with ignoreDifferences on /spec/replicas, or RespectIgnoreDifferences=true.

Failure modes and detection

  • Controller outage. Nothing reconciles, so drift is silent. Alert on argocd_app_info{sync_status="Unknown"} and on the reconcile histogram going flat; with a 180s default interval, a 10-minute gap is real.
  • Partial sync. A Failed operation phase mid-apply leaves half the resources at the new version. Watch argocd_app_sync_total{phase="Failed"} and diff live against desired.
  • Bad prune. Blast radius is everything the removed manifest owned. Catch it before merge with argocd app diff --local in CI.
  • Secret in Git. gitleaks in CI plus push protection; secrets come from External Secrets or SOPS, never plaintext.

Flux equivalents: Kustomization.spec.dependsOn for ordering, spec.prune, spec.serviceAccountName for per-tenant identity, GitRepository.spec.verify for signature checks, spec.decryption for SOPS.

Recovery. Emergency kubectl changes are allowed, but on-call opens a PR in the same shift. A nightly job diffs live state against Git and files an issue for anything unmanaged.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Verify a release after deployment.

Answer

Core answer (first 90 seconds)

Assume a canary or rolling deploy of a stateless service behind a load balancer, with a backward-compatible DB migration and a named abort authority. Verification has two jobs: prove the thing running is the thing you built, and prove user-visible outcomes still match baseline. Everything else is supporting evidence.

Start with identity, because a green pipeline job only proves orchestration ran. Compare the CI-built image digest to the digest actually running:

kubectl get pods -l app=checkout -o jsonpath=\
'{.items[*].status.containerStatuses[*].imageID}'
# sha256:9f2c...  <- must equal the digest CI pushed

If that digest differs from the one your build produced, stop: you are verifying the wrong artifact. Then confirm config: the configmap/secret checksum annotation on the pod template should match the current configmap, otherwise you have a pod running stale config.

Then exercise the critical journeys synthetically (login, search, checkout) and compare against baseline in segments, not in aggregate. Aggregate error rate hides a broken endpoint behind healthy traffic. Split by endpoint, status class, region and client version.

Numbers and thresholds

Pre-declare the abort criteria before you start, so the decision isn't made under pressure. A workable set:

signalbaselineabort if
p99 latency (checkout)180 ms> 360 ms for 5 min
5xx rate0.2%> 1% for 5 min
error-budget burn (1h)—> 14.4x (2% of monthly budget in 1h)
consumer lag< 1kgrowing for 10 min
DB write errors0any sustained

The 14.4x figure is the multi-window burn-rate threshold from the SRE workbook: 2% of a 30-day budget consumed in one hour. Watch it on both a 1h and a 5m window so a short spike doesn't page you but a sustained burn does.

Why each check catches a class of failure

Digest check catches "deployed the wrong build": the most common cause of a green pipeline with a bad release. Config-hash check catches drift where a configmap changed but pods weren't restarted. Segmented error/latency catches partial failures that aggregate metrics average away. Data/control totals (orders created vs payments captured) catch silent correctness bugs that never surface as errors. Queue depth and consumer lag catch downstream breakage that lags the deploy by minutes. Migration checks catch the expand/contract ordering bug: if the schema change isn't backward compatible, rolling back the app leaves it writing to a schema it doesn't understand.

Window

Observe for a pre-declared window (30 minutes at 5% canary traffic, or 1 hour at full rollout) with telemetry-health checks first: if your metrics pipeline is dropping samples, a "clean" window means nothing. Confirm the canary actually received representative traffic; a canary that only saw health checks proves nothing.

When criteria fail

Three options, and the deciding factor is blast radius and reversibility. Roll back when the artifact is bad and the schema is backward compatible: fastest, cleanest. Roll forward when the migration is already applied and irreversible; fix the app, keep the schema. Isolate when the damage is confined to one shard, region or tenant: route traffic away and keep the rest serving. Rollback is wrong when the migration isn't backward compatible; isolation is wrong when the fault is in shared code.

Close

Record release ID, digest, evidence, decision and residual work. Residual work matters: a release verified at 5% canary is not verified at 100%.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Plan a backward-compatible database deployment.

Answer

What I'd say first (60–120s)

"Backward compatible" means two things at once: old code keeps working against the new schema, and new code keeps working against the old schema, because during rollout both are live. Assume Postgres 15, a 400M-row orders table (~180 GB), no maintenance window, and two app versions running concurrently. The plan is expand → migrate → contract. Everything before the contract is reversible; the contract is the only irreversible step, so it goes last, after the rollback window closes.

Expand. Add the new column nullable:

SQL
ALTER TABLE orders ADD COLUMN currency char(3);

On Postgres 11+ this is metadata-only: ACCESS EXCLUSIVE held for milliseconds, no rewrite. If every row gets the same value, ADD COLUMN currency char(3) NOT NULL DEFAULT 'USD' is also metadata-only and there is no backfill at all. A volatile default (now(), gen_random_uuid()) rewrites all 180 GB under ACCESS EXCLUSIVE; that's the trap. Same class: CREATE INDEX without CONCURRENTLY blocks writes for the whole build; CONCURRENTLY doesn't, but can leave an INVALID index. Check pg_index.indisvalid and drop/retry rather than assuming it worked.

Migrate. Backfill in idempotent, resumable batches keyed on the primary key:

SQL
WITH batch AS (
  SELECT id FROM orders
  WHERE currency IS NULL AND id > :last_id
  ORDER BY id LIMIT 10000
)
UPDATE orders o SET currency = o.currency_code
FROM batch WHERE o.id = batch.id
RETURNING o.id;

Trace: the CTE picks the 10,000 lowest ids above the checkpoint where currency IS NULL. The UPDATE sets those rows and RETURNING yields their ids; the new checkpoint is max(id). If the process dies after the UPDATE commits but before the checkpoint is written, the restart re-runs with the old last_id: the CTE re-selects on currency IS NULL, so rows already updated no longer match and it picks the next 10,000. Nothing is done twice, nothing is skipped. That's what makes it idempotent; the checkpoint only has to be monotonic, not transactional.

Run batches with a short sleep and watch replica lag in pg_stat_replication; pause if lag exceeds ~30 s, because a 10k-row batch on a hot table can push a replica past its read SLA.

Switch and contract. Only after SELECT count(*) FROM orders WHERE currency IS NULL returns 0 do you flip reads. Flip early and new code reads NULL for the tail: either a crash on a NOT NULL assumption or silently wrong currency. Then tighten the column without a scan:

SQL
ALTER TABLE orders ADD CONSTRAINT orders_currency_nn CHECK (currency IS NOT NULL) NOT VALID;
ALTER TABLE orders VALIDATE CONSTRAINT orders_currency_nn;  -- SHARE UPDATE EXCLUSIVE
ALTER TABLE orders ALTER COLUMN currency SET NOT NULL;      -- PG 12+ reuses the validated constraint

Wait out the rollback window (one full business cycle, say two weeks) before dropping currency_code.

Failure modes. Divergence between the two columns: detect with a periodic count(*) WHERE currency IS DISTINCT FROM currency_code; it should be 0. Lock waits: alert on pg_locks waits over 5 s. Bloat: 400M row updates create dead tuples, so autovacuum must keep up or the table doubles.

Trade-offs. Dual-write from the app is simplest but only covers writers you control: batch jobs and other services silently miss it. A trigger captures every writer in-database at the cost of write latency and trigger maintenance. CDC (Debezium on the WAL) needs no app change and catches all writers, but adds infrastructure and lag. Expand-contract isn't always worth it: under ~1M rows, or when a maintenance window is acceptable, a plain ALTER beats three deploys.

Rollback. App rollback is a redeploy, and it works only because the old column is still there: that's why the contract waits. Data recovery is separate: if the backfill wrote wrong values, re-point reads at currency_code rather than restoring a backup.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Handle a failed irreversible migration.

Answer

What I'd say first (60–120s)

"Irreversible" here means the old code can't read the new schema, so rolling back the deploy turns a scoped data problem into a full outage on every read of that path. I don't roll back the code. I stop the write path, freeze the evidence, and choose the repair from data.

Assumptions I'd state: single Postgres 15 primary, nightly logical backup plus WAL archiving every 5 minutes, the migration already committed, no replica I can promote. If any of those is false the plan changes.

Then stop writes. Feature-flag the writer off, or pause the consumer group: whichever is narrower. If the damage is one tenant or one date range, isolate that cohort and keep serving everyone else.

Freeze evidence before touching anything: snapshot the affected tables (CREATE TABLE users_pre_migration AS SELECT * FROM users), record the migration's start LSN, and keep the WAL segment range. The repair will overwrite the only copy of the truth if you skip this.

Choosing the repair

optionwhen it winscost
Roll-forward repairsource data still exists (snapshot, backup, upstream)minutes
Restore + replaythe destructive step destroyed the only copyhours of downtime
Compatibility bridgeold code must keep running while you repairweeks of dual-write debt

The deciding question is whether the pre-change values still exist somewhere. If they do, roll forward. If they don't, restore.

Worked reconciliation (hypothetical figures)

SQL
SELECT
  (SELECT count(*) FROM users)    AS users_total,
  (SELECT count(*) FROM contacts) AS contacts_total,
  (SELECT count(*) FROM users u
     LEFT JOIN contacts c ON c.user_id = u.id
    WHERE c.user_id IS NULL)      AS orphans;

Trace: users_total = 3,142,880, contacts_total = 3,130,480, orphans = 12,400. The gap equals the orphan count exactly, so the damage is a clean skipped cohort with no duplicates. If orphans were 0 but contacts_total exceeded users_total, a previous repair re-ran non-idempotently and inserted duplicates: that's a different incident.

Repair, idempotent (assuming a unique index on contacts.user_id):

SQL
INSERT INTO contacts (user_id, email)
SELECT id, legacy_email FROM users_pre_migration
WHERE legacy_email IS NOT NULL
ON CONFLICT (user_id) DO NOTHING;

Re-run the reconciliation query; expect orphans = 0.

Failure modes and how you see them

  • Non-idempotent repair: duplicate contacts. Detect with contacts_total > users_total, or unique-violation counts in the job log.
  • Restore path: PITR to before the migration loses every write after the restore point. Detect by comparing max(updated_at) to the incident start, if it's older, you've lost writes and must replay from WAL or the app outbox.
  • Bridge left in place: dual-write to the resurrected column never removed. Detect via read counters in pg_stat_user_tables; non-zero reads after the repair window mean the bridge is load-bearing.

Cost arithmetic that decides it

Restoring a 2 TB primary at ~200 MB/s effective replay is roughly 2.5–3 hours of downtime. Repairing 12,400 rows is seconds. That gap is why you exhaust roll-forward before you reach for restore.

Keep the snapshot table as the repair's own rollback, add a pre-migration snapshot plus this reconciliation query to the migration gate, and rehearse the restore path: an untested PITR is not a recovery plan.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Design automated rollback for a bad deployment as a pipeline capability, not a manual incident action. What triggers it, what does it revert to, and what can't it revert?

Answer

Clarify first: what SLO defines "bad", and how much blast radius is acceptable? Assume a stateless service on Kubernetes, canary delivery, artifacts addressed by digest, config in Git. Automated rollback is three pipeline components (detector, decision rule, revert action) and only the first is mostly about code.

Detector. Readiness probes are too coarse: a pod passes readiness while 8% of requests return 500. The pipeline watches probe failure, error-rate delta against the stable cohort, latency percentiles, saturation, and business KPIs where they exist. Thresholds are relative to the current stable baseline, because absolute thresholds drift with traffic mix.

signalwindowtrigger (hypothetical)catches
readiness30 sany pod unready > 2 mincrashloop
error rate3 × 1 mincanary 5xx > baseline + 1 ppfunctional regression
latency3 × 1 minp99 > 1.5× baseline or 500 mstail regression
saturation5 minCPU throttling > 20%capacity regression
business10 mincheckout success −2%silent wrongness

Wiring: the analysis is a pipeline stage that gates promotion, not a dashboard alert. In GitHub Actions it is a job that polls the analysis result and fails the run; with Argo CD/Argo Rollouts it is an AnalysisTemplate the rollout controller evaluates. Either way the pipeline owns the abort, and "continue anyway" must not be the default path.

Statistical power. A 5% canary on 200 rps is 10 rps. A 1 pp error regression is 0.1 errors/s, about 6/min; three 1-minute windows gives ~18 errors: enough to trip a threshold, not enough to separate 1% from 1.5%. Gate on minimum request count as well as elapsed time, and widen the canary when traffic is low.

Last-known-good. The revert target is a tuple: artifact digest + config revision + schema version. Record it at promotion: the digest that survived the previous full analysis, the Git SHA of config, the schema version. Tags are mutable; pin image@sha256:…, and SLSA provenance ties that digest to the commit and builder. Kubernetes keeps a ReplicaSet per revision (revisionHistoryLimit default 10), so kubectl rollout undo is fast, but it reverts only the pod template: ConfigMaps, Secrets and PVCs stay as they are. Under Argo CD automated sync with self-heal, a manual kubectl rollout undo is reverted back to the bad state; the durable revert is reverting the commit in Git, or argocd app rollback to a prior sync revision. So the pipeline's revert action is a Git operation, not a kubectl one.

Code vs state. Code rollback is cheap and reversible. Schema is not. If the release added a column and backfilled it, the old binary still runs (it ignores the column), but the migration itself cannot be undone. The pipeline's rollback contract is therefore "the previous N releases run against the current schema": expand/contract, additive-only DDL, no destructive change in the same release that stops using the old shape. Genuinely irreversible work (a backfill, a message-format change) is forward-fix only, and the pipeline should mark it so and gate it differently.

Strategy interaction. Rolling update with maxSurge/maxUnavailable reverts fast but gives no traffic control, so a 1% regression is invisible until it is at 100%. Canary gives detection but needs the analysis window. Blue/green flips back instantly but doubles capacity and does nothing for state. The strategy decides what the detector can see and how fast the revert lands.

Failure modes. Rollback loops, where the bad artifact is also the last-known-good because the previous release never soaked: require the LKG to have survived a full analysis. Config that does not roll back: diff the running config revision against the LKG tuple. And a rollback that hides the failure: the pipeline must quarantine the bad digest and open an incident, not just redeploy and move on.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Design pipeline observability and audit.

Answer

What I'd say first

Scope: CI on GitHub Actions, CD via Argo CD into Kubernetes, images in an OCI registry, signing with Sigstore. This is two systems, not one: operational telemetry you sample and expire, and audit evidence you cannot lose or edit. They share exactly one join key, the pipeline run ID, and nothing else.

Assumption I'd state out loud: audit records are what you hand a regulator or an incident reviewer six months later, so they must be complete and tamper-evident. Telemetry is for debugging now, so it can be lossy.

The design

Every run gets a run ID (GitHub gives you GITHUB_RUN_ID; on Jenkins it's the build ID). Propagate it as a W3C traceparent header into every job, and into the deploy step so Argo CD's sync carries the same trace ID. One span per job, child spans per step, so a slow docker build and a slow kubectl apply are distinguishable.

Two sinks:

Operational telemetryAudit evidence
Contentspans, queue time, cache hit/miss, retry countswho triggered, source commit, artifact digest, approvals, policy decision, deploy revision
StoreOTLP to Tempo/Jaegerappend-only, hash-chained log (CloudTrail-style digest files, or S3 Object Lock in compliance mode)
Retention30–90 days1–7 years
Sampling10% head sampling is fine100%, never sampled
Accesswhole eng orgrestricted, read-only, exports logged

The audit record for one deploy is small: run ID, actor, source SHA, image digest (sha256:...), the SLSA provenance attestation, approver identity, target environment, resulting deployment revision. Roughly 2 KB. At 400 deploys/day that's ~800 KB/day, ~290 MB/year: cheap enough that sampling it would be indefensible.

Why hash chaining matters

Each audit entry stores the hash of the previous entry. Editing entry N changes its hash, which breaks entry N+1, and so on down the chain. That is what CloudTrail's digest files do: hourly SHA-256 digests plus an RSA signature over them. You don't have to trust the log store; you have to verify the chain.

Failure modes and how you catch them

  • Audit loss. The pipeline emits a run but no audit record lands: dropped write, full disk, crashed sidecar. Detect by reconciling counts: the CI API says 400 runs today, the audit store has 397. Alert on the gap, not on the store's own health. This is why the audit write should be synchronous and fail the job if it can't record; an async buffer that drops on shutdown is how you lose the one record that mattered.
  • Trace break. A job runs on a self-hosted runner that doesn't forward traceparent, so its spans are orphans. Detect by counting spans with no parent per run: a run with 12 jobs and 9 root spans has a propagation hole.
  • Secret leakage. Env vars and command lines land in logs. Redact at the emitter, not the store, and treat the audit log as sensitive because it carries actor identities.

Trade-offs

Synchronous audit writes add latency to every job: tens of ms, but on the critical path. Buffering trades that latency for the loss window above; for audit I take the latency. Full-fidelity telemetry is the other cost lever: at 192k spans/day (400 runs × 12 jobs × 40 spans), sampling to 10% cuts storage roughly 10× and the audit trail stays intact, because the two stores are separate.

Reconstruction test

Once a quarter, take a production deployment from six months ago and try to answer: which commit, which human approved it, which policy version allowed it, what digest is running. If any answer needs a store you've already expired, the retention split is wrong.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Test the CI/CD platform itself.

Answer

Treat the delivery platform as a service with its own SLOs, and test it the way you'd test any distributed system: inject the faults it will actually see, then assert on invariants rather than on "it worked once."

Assumptions I'd state up front: there's a staging instance that mirrors prod config; I can inject faults (kill a runner, drop a webhook, expire a token); and there's a deploy ledger. An append-only record of (commit SHA, environment, actor, timestamp, artifact digest). To reconcile against. Without that ledger you can't tell a lost deploy from a deploy that never should have happened.

The invariants I test:

  1. Exactly-once deploy per (SHA, environment).
  2. Fail-closed promotion: no approval, no prod.
  3. Artifact immutability: what was tested is what ships.
  4. Bounded queues with backpressure, not silent drops.

Mechanism: why each check catches what it claims

Webhook duplication. GitHub and GitLab redeliver on non-2xx and can deliver the same event twice; each delivery carries a unique ID (X-GitHub-Delivery GUID). So the receiver must dedupe on that ID, not on the payload. Test: replay the same delivery three times, assert exactly one pipeline starts. Detection: pipeline-start count per delivery ID > 1 in the ledger.

Webhook loss. The opposite failure: a merge that never triggers a build. You can't catch this by watching the pipeline; you catch it by reconciling merge events from the VCS against pipeline starts. Test: drop a delivery, run reconciliation, assert it flags the gap. This is why the ledger matters.

Runner exhaustion. Saturate a pool of N self-hosted runners with N+1 jobs. Correct behaviour is bounded queueing with a visible "queued" state and an alert before the queue exceeds your SLA, not silent starvation. Detection: queue-depth metric crossing threshold, job wait-time p99.

Runner compromise. A job that reads a secret it shouldn't. Test with a canary secret on an egress-blocked runner; assert the job fails and the egress attempt is logged. Detection: egress deny logs, secret-scanning alerts.

Artifact immutability. Tags are mutable; digests are not. Test: push an artifact, retag it, assert the deploy still resolves the original sha256 digest. Detection: digest mismatch between build record and deploy record.

Approval outage. Kill the approval service mid-promotion. Correct behaviour is fail-closed: the deploy stays blocked. Detection: promotion attempts that succeeded while the approval service returned errors.

Trade-offs

Where to inject: staging gives a safe blast radius but misses prod-only config (real IAM, real network policy). Chaos in prod catches those but risks a real incident. Deciding criterion: inject in staging by default; in prod only for read-only or reversible faults (webhook replay, queue saturation), never for anything that can corrupt the artifact store or the deploy ledger.

Manual audited path vs hard fail: when CI is down, a break-glass manual deploy is sometimes necessary. The trade-off is speed against the guarantee that what ships was tested. Decide by environment: allow break-glass in non-prod; require two-person approval plus a recorded digest in prod.

Failure modes and detection

scenarioinjectioninvariantdetection signal
duplicate webhookreplay delivery 3×one pipeline per delivery IDstart count > 1
lost webhookdrop deliveryreconciliation flags gapmerge events − pipeline starts > 0
runner exhaustionN+1 jobs on N runnersbounded queue + alertqueue depth, wait p99
cache poisoningcollide cache keydigest matchartifact digest mismatch
approval outagekill approval svcfail-closedpromotion during error window

Run these as a scheduled game day, not a one-off. Record the SLOs you're asserting (deploy success rate, time-to-deploy p95, reconciliation lag) and the runbook action for each alert, so a failure during the test is handled the same way it would be at 3am.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Measure CI/CD effectiveness without gaming.

Answer

Core answer

Effectiveness means the pipeline reliably turns a commit into a safe production change, fast. I measure it with the four DORA metrics: deployment frequency, lead time for changes, change failure rate, failed-deployment recovery time: plus two things DORA doesn't cover: pipeline queue/feedback time and rework (changes reverted or hotfixed within 24h). DORA's 2023 report puts elite performers at on-demand deploys, lead time under a day, a 5% change failure rate, and under an hour to recover. The anti-gaming rule is structural: no metric is ever reported alone, and no metric is ever used to rank teams.

Assumptions: I can join CI/CD event data (commit, PR, deploy) to incident data with timestamps, and I have a paging system as an independent incident source.

Why pairing resists gaming

Goodhart's law: once a measure becomes a target it stops measuring. Every throughput metric has a cheap way to inflate it, and each has a stability metric that moves the other way when you cheat.

MetricCheap way to inflatePaired counter-metric
Deployment frequencySplit one release into many no-op deploys; deploy at 3amChange failure rate; deploys per incident
Lead time for changesStart the clock at PR open, not first commitPR review latency; recovery time
Change failure rateReclassify incidents as "expected"; roll forward instead of rollbackIncident count from the paging system, not the deploy tool
Recovery timeDeclare recovery at mitigation, not user-visible fixSLO burn / user-facing error rate
Test pass rateAdd trivial assertions; rerun flaky tests until greenFlake rate (same test passes and fails on the same commit)

Segmentation

Aggregates hide the constraint. Segment by service tier (tier-1 vs internal) and by pipeline stage, not by team leaderboard. A tier-1 service at 5% CFR and 30-min recovery is healthy; an internal tool at 5% CFR deserves different attention. Keep metric definitions in a versioned doc: redefine lead time and the trend line breaks.

Worked example (hypothetical figures)

Team A reports 40 deploys/day, up from 10: looks like 4x. Join to incidents: CFR went 4% → 12%, MTTR 45 min → 4h. Expected failed deploys/day: 40 × 0.12 = 4.8 vs 10 × 0.04 = 0.4. Expected incident-minutes/day: 4.8 × 240 = 1152 vs 0.4 × 45 = 18. The throughput gain cost roughly 63x more incident time. The read is not "deploy less" but "the batch got riskier": check whether the deploy split is real or no-op.

Failure modes and detection

  • Reclassification gaming: source incident data from the paging/on-call system (PagerDuty, Opsgenie), not the deploy tool.
  • Flaky tests masking real failures: track flake rate per test over a window (Datadog CI Visibility, BuildPulse, Trunk); quarantine, don't rerun silently.
  • Survey burden: developer-experience surveys (SPACE/DORA) get gamed by low response rates. Report the response rate alongside the score.
  • Vanity dashboards: sample "successful" releases quarterly and verify artifact provenance. Signed, digest-pinned, and the deployed digest matches the tested one.

What not to do

Don't rank teams by deploy count or fastest pipeline; don't tie bonuses to a single metric; don't compare teams with different definitions. Open-source Four Keys (Google) or LinearB/Sleuth can collect the DORA set, but the pairing and segmentation rules are what keep it honest.

Curated: · Written: · Reviewed:

Difficulty: Hard