CI/CD pipelines: artifacts, caching, secrets, environments, GitOps, rollbacks

Build once, promote the same digest, and let environments differ only in configuration. Anything that can change the artefact between stages breaks the evidence testing gave you.

Read the briefing
About 3 min to read 9 drills

What to remember

  1. Build once, promote by digest. Rebuilding per stage means production runs something that was never tested.
  2. OIDC federation, not stored cloud keys. Short-lived tokens scoped to repo, branch and environment. Nothing to leak.
  3. Pin third-party actions by commit SHA. A moving tag in your pipeline is scheduled remote code execution.
  4. A cache key must fully determine the content. Otherwise a cache hit is a correctness hazard, not a speed win.
  5. Quarantine flaky tests with an owner and a deadline. Blanket retries hide real races; deleting loses coverage.

The big picture

A pipeline is a promotion machine: it builds one immutable artifact, proves things about it, and moves that exact artifact toward production with controls that leave an audit trail. The interview topics are artifact immutability, caching that cannot change results, secrets via short-lived federated credentials, environment protection, push versus pull (GitOps) deployment, deploy strategies with rollback, and what to do about flaky tests.

The mental model

Build once, promote the same digest, and let each environment differ only in configuration. Anything that can change the artifact between environments (a rebuild, a mutable tag, an untracked config baked at deploy time) breaks the chain of evidence that testing gave you.

In depth

Artifacts, caching, and reproducibility

Build the artifact once and promote it: a digest-addressed container image or a versioned package, with environment-specific behaviour supplied as configuration at runtime, not baked per environment. Rebuilding per stage means production runs something that was never tested. Reference images by @sha256: in manifests so a rollout is exact and a rollback is unambiguous; keep tags for humans.

Caches (dependency caches, layer caches) are accelerators keyed on lockfiles or content hashes: a cache miss must produce an identical result, or the cache is a correctness hazard. Cache keys that are too broad cause stale-dependency bugs that appear only in CI; keys that include the lockfile hash are the standard. Restore-keys give partial hits without correctness risk. Never cache anything mutable that the build's output depends on but that is not part of the key.

Secrets, environments, and permissions

The modern default is OIDC federation: the CI provider mints a short-lived token that a cloud role trusts, scoped by repository, branch, and environment, so there is no long-lived cloud key to leak. Where secrets must exist, they are scoped per environment, masked in logs, and never exposed to workflows triggered by pull requests from forks (which is the classic exfiltration path, along with pull_request_target and untrusted build scripts). Pin third-party CI actions by commit SHA, because a moving tag is remote code execution in your pipeline.

Environments with protection rules (required reviewers, branch restrictions, wait timers) are how promotion is gated and recorded: the approval is an artifact of the deployment, not a Slack message. Keep the CI job's cloud permissions minimal and different per environment; a build job should not hold production credentials at all.

GitOps, deploy strategies, and flaky tests

Push deployment means CI holds cluster credentials and applies changes; pull-based GitOps means an in-cluster controller reconciles to a git-declared state, so CI never holds cluster credentials, drift is corrected continuously, and the repository is the audit log. The trade is an extra component and an indirection when debugging ("why has it not applied yet?"). Either way, the deployed state should be reconstructible from a commit.

Strategies: rolling (cheap, gradual, no extra capacity, slow rollback), blue/green (instant switch, double capacity, awkward with schema changes), canary (small exposure with analysis, best signal, needs traffic and tooling). A rollback is a redeploy of the previous artifact, which is why immutability and backward-compatible migrations matter more than the strategy you pick.

Flaky tests destroy the signal that makes the pipeline trustworthy. The discipline is to quarantine them (still run, but not blocking), track each with an owner and a deadline, and fix or delete: blanket retries hide real races, and deleting without analysis loses coverage. Measure flake rate as a first-class pipeline metric alongside duration and failure rate.

Myths and facts

Myth: Rebuilding per environment is fine as long as the code is the same.

Fact: Different base images, dependency resolution, and build-time inputs produce a different artifact; promote the tested one.

Myth: A cache is just a speed optimization and cannot break correctness.

Fact: A cache keyed too broadly returns stale dependencies; the key must fully determine the content.

Myth: Storing cloud keys in CI secrets is secure enough.

Fact: Long-lived keys are the most common CI compromise; use OIDC federation with short-lived, scoped credentials.

Myth: Pinning an action to a version tag is safe.

Fact: Tags move; pin third-party actions by commit SHA and update deliberately.

Myth: Retrying flaky tests automatically is a pragmatic fix.

Fact: It hides real races and erodes trust; quarantine with an owner and a deadline instead.

How pros do it

  • Build once, promote by digest; supply environment differences as configuration.
  • Key caches on lockfile or content hashes; never let a cache change the result.
  • Use OIDC federation for cloud access, scope per environment, and pin third-party actions by SHA.
  • Gate promotion with environment protection rules so approvals are recorded.
  • Track flake rate, quarantine with owners and deadlines, and keep rollback a single documented command.

Questions people ask

What does your ideal pipeline look like?

Walk it as a promotion machine, in order: build one immutable artifact, prove things about it, promote that exact digest through environments with configuration injected at runtime; short-lived federated credentials; environment protection as the audit record; a progressive rollout gated on health; a rollback that is one rehearsed command. Say the mechanism behind all of it in one sentence: the bytes that passed tests are the bytes that serve traffic. Caveat to volunteer: the automated gates are what block; the human approval is the record.

What is the fastest rollback?

Say 'redeploy the previous digest' (or revert the commit in GitOps): one command or one click, practised, fast because the artifact is immutable and the application is stateless. Then give the condition before they ask: it only works while the schema is still compatible with the previous version, which is what expand/contract buys you; after a destructive migration you are fixing forward.

How should the pipeline get cloud credentials?

Answer 'OIDC federation' and then say what it changes: the CI provider signs a short-lived token per run, a cloud role trusts it, scoped by repository, branch, and environment, so there is no long-lived key to leak or rotate. Where a stored secret is unavoidable, scope it per environment, mask it, and never expose it to fork-triggered runs. Caveat: a wildcard subject in the trust policy hands the role to every branch.

Push or pull deployment?

Make a call and name both sides: pull-based GitOps when the target is Kubernetes and you want no cluster credentials in CI, continuous drift correction, and a commit as the audit record; push when the setup is small or the target is not Kubernetes. Describe the controller in one sentence: it reconciles the cluster to what Git declares, on a loop. Caveat: you need a health signal to know when a rollout actually finished, and the pipeline still builds and tests first.

Where should database migrations run in the pipeline?

As their own idempotent, reviewed step before the application rollout, designed expand, migrate, contract so the previous version still runs against the new schema. Say why not inside application startup at scale: a slow migration becomes a fleet-wide boot failure. Caveat: the destructive contract step belongs in a later release, after a bake.

How long should CI take?

Give a number and the reason for it: short enough that people do not batch changes; under ten minutes for the blocking path is a common target, with slower suites post-merge or nightly. Caches keyed on lockfile hashes and parallel jobs are how you get there. Caveat: a cache miss must produce an identical result, or the speed came at the cost of correctness.

How do we keep pull requests from forks safe?

Three rules, then the mechanism: no secrets in fork-triggered workflows, no pull_request_target that checks out or runs untrusted code, and approval required for first-time contributors. The mechanism: a fork can change the test script, so any secret the job can read is theirs. Caveat: pull_request_target is fine for jobs that only label or comment.

Further reading

Drills · 9

Answer in your head, or out loud, before you reveal. Mark each one: "Again" brings it back, "Got it" counts on your desk.

1 Pick the strongest answer

Your pipeline builds the service image in the staging job, runs the integration suite against it, then builds the image again in the production job from the same commit SHA and deploys that. Both builds pass. Why would I still reject this design?

  1. Two builds of the same commit are not guaranteed to be identical (floating base-image tags, dependency ranges resolved at build time, timestamps), so what was tested in staging is not provably what ships; build once, push by digest, and promote that digest. The artifact, not the source commit, is the unit of promotion; only an immutable digest carries the test evidence forward.
  2. Rebuilding is fine because the commit SHA pins everything the build depends on. A source SHA pins your code, not an unpinned FROM tag, a ^1.2 dependency range, or whatever the package mirror serves that minute.
  3. Rebuilding is required because production needs different environment variables baked into the image. Environment-specific configuration belongs at runtime (env, config maps, secrets), precisely so one artifact can run everywhere.
  4. The only problem is cost: the second build wastes CI minutes. The cost is real but incidental; the design flaw is provenance — the production artifact has no test evidence attached to it.
In short

Two builds of the same commit can differ, so build the image once and promote the same digest to production.

Why

Promotion means the bytes that passed tests are the bytes that serve traffic. A container build is not a pure function of the source commit: FROM node:20 resolves to whatever that tag points at today, npm install without a lockfile resolves ranges, and some tools embed build timestamps. Building once, pushing by digest (repo@sha256:…), and passing that digest to every later stage turns "we tested this commit" into "we tested this artifact". Environment differences are injected at deploy time, never baked in.

The common mistake

Answering 'cost' or 'time'. The waste is incidental; the flaw is provenance: production runs bytes that carry no test evidence, and 'roll back to the previous prod image' has no exact answer.

Read the docs

2 Pick the strongest answer

Your GitHub Actions workflow deploys to AWS. Today it uses an IAM user's AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY stored as repository secrets (option A). I want it on an IAM role whose trust policy names GitHub's OIDC provider, with the job requesting permissions: id-token: write and exchanging that token for role credentials (option B). What does B actually change?

  1. B is safer only because the repository secret is encrypted at rest in GitHub. Repository secrets are encrypted at rest too; the difference is credential lifetime (minutes vs indefinite) and the ability to scope trust to a repo, ref, or environment.
  2. The job exchanges a short-lived, GitHub-signed identity token (with claims for repository, ref, and environment) for STS credentials that expire within the job; there is no long-lived secret to leak or rotate, and the role's trust policy can restrict which repository and branch may assume it. Federation replaces a stored credential with a per-run proof of identity that AWS verifies against GitHub's public keys; scope and lifetime are the whole point.
  3. B stores the same static key inside GitHub's OIDC provider instead of the repository, so the exposure is unchanged. No static AWS key exists in B; the token is minted per run and signed by GitHub's issuer, and AWS validates the signature and claims.
  4. B requires a self-hosted runner inside the AWS VPC so the token can reach STS privately. OIDC federation works from GitHub-hosted runners over the public STS endpoint; no network placement is involved.
In short

OIDC swaps a stored long-lived key for a short-lived token that GitHub signs per run and AWS checks against a trust policy.

Why

With OIDC the runner asks GitHub's token service for a JWT whose sub claim encodes repo:org/name:ref:refs/heads/main (or an environment), then calls sts:AssumeRoleWithWebIdentity. AWS checks the signature against GitHub's published keys and evaluates the trust policy's conditions on aud and sub. The credentials it returns live for the session and cannot be copied out of a laptop, a log, or a fork. Long-lived IAM user keys, by contrast, are valid until someone remembers to rotate them, and rotation itself is a manual, error-prone deploy.

The common mistake

Stopping at 'no stored key'. The trust policy's sub condition is the actual control; a wildcard subject hands the deploy role to every branch in the organisation.

Read the docs

3 Answer out loud

You shipped v42: a code change plus a database migration. Twenty minutes later the error rate climbs and you decide to roll back. How do you make that rollback safe right now, and what had to be true before the deploy for a safe rollback to exist at all? Three to six sentences.

In short

A strong answer rolls back only the application to the previous image and never runs a down migration on live data.

What a strong answer does
  • rollback mechanics: Rolls back only the application to the previous digest because the migration was additive and the schema is compatible with N-1; flips a feature flag first if one exists; states the decision rule for rollback versus forward-fix (destructive migration or data already written in the new shape means forward-fix only); never runs a down migration under live traffic.
  • preconditions: Expand/contract sequencing, the N-1 image tested against the new schema in CI, the migration shipped as its own reviewed and observable step (with a dry run against a production-like snapshot), a flag to decouple exposure from deploy, and backups/PITR named as the last resort rather than the plan.
  • communication: Leads with the decision rule, then the mechanism, then the preconditions; precise vocabulary (additive, N-1 compatible, expand/contract, digest) used correctly.
Why

Interviewers are listening for the asymmetry: application rollback is cheap because the artifact is immutable and stateless, schema rollback is dangerous because data has moved. The expand/contract pattern makes the schema compatible with both the old and new code for a window, which is exactly what turns "rollback" into "redeploy the previous digest". Candidates who reach for a down migration or a backup restore reveal they have not had to roll back under live writes.

The common mistake

Running a down migration, or restoring last night's backup, against a database that has taken twenty minutes of writes. Both destroy data; a strong answer says so before naming the fix.

4 Design round

Design me the deploy pipeline for a Postgres-backed order API, three replicas behind a load balancer at about 2k requests per second, whose releases regularly include schema changes. Today releases happen at 02:00 behind a maintenance page, and 'rollback' means restoring a backup. Remove the maintenance window, and tell me how you would prove rollback works before you need it.

  • No maintenance windows: the API stays available through deploys and rollbacks.
  • Rolling back the application must complete in under five minutes.
  • Changes pass through two environments before production, and production requires a recorded human approval.
  • The schema has about 40 tables and some migrations rewrite large ones.
In short

A strong design builds one image, promotes it by digest, keeps every migration backward compatible, and rehearses the rollback.

A strong answer covers
  • Builds one immutable artifact (image by digest) and promotes the same digest through dev, staging and production; never rebuilds per environment and never deploys by mutable tag.
  • Decouples schema migrations from code deploys with expand/contract: additive, backward-compatible migrations first, code that uses them second, destructive cleanup last, so any running version N or N-1 works against the current schema.
  • Makes large-table changes online (concurrent index builds, batched backfills, statement and lock timeouts) and runs migrations as a separate, idempotent, observable step with its own review.
  • Deploys with a canary or blue/green rollout gated on health signals (error rate, latency, database errors and lock waits) and automatic rollback to the previous digest; rollback never touches the schema.
  • Uses environment protection rules so the production approval is an audit record, while the real gates are automated: tests, N-1 compatibility run, migration dry-run against a production-like snapshot, SLO or error-budget check.
  • States how rollback is proven: every staging release rehearses deploy N, migrate, deploy N-1; a periodic production game day; rollback duration measured against the five-minute target.
What a strong answer does
  • design quality: Digest promotion, expand/contract with online migration technique for large tables, health-gated progressive delivery with automatic rollback, approvals as audit with automated gates, and a concrete rehearsal that measures rollback time.
  • tradeoffs: Two or more tradeoffs with a decision: cleanup cadence versus safety, canary needs stateless requests, blue/green capacity versus rollback speed, human approval latency versus audit value.
  • communication: Restates constraints with numbers, walks artifact → schema → rollout → gates → verification, names failure modes at each step, and closes with decisions.
Why

The design hinges on one observation: rollback is only fast when it is a stateless redeploy, and it is only stateless when the schema is compatible with both versions. Everything else — digest promotion, health-gated progressive delivery, approvals as audit, and a rehearsed rollback — follows from making that compatibility a tested property rather than a hope. Candidates who keep "restore the backup" as their rollback plan have not separated the application from the data.

The common mistake

Keeping 'restore the backup' as the rollback plan, or asserting backward compatibility without testing N-1 against the migrated schema in CI. A rehearsed rollback with a measured duration is what separates the design from the diagram.

5 Pick the strongest answer

You are choosing between (A) the CI pipeline running helm upgrade against the production cluster after tests pass, and (B) an in-cluster controller, Argo CD or Flux, that reconciles the cluster to a Git repository into which the pipeline commits the new image digest. Tell me what B actually buys you and what it costs. Which of these is right?

  1. In B a manual kubectl edit in production persists, because the controller only acts when a new commit lands. Reconcilers loop on an interval and on webhooks; with self-heal / automated sync enabled they revert manual edits, and even without it they flag the drift as out of sync.
  2. B removes the need for tests and image promotion because the controller validates manifests before applying them. The controller applies whatever Git says; building, testing, and producing the digest remain the pipeline's job.
  3. The cluster pulls its desired state: no cluster credentials live in CI, the controller keeps correcting drift back to what Git declares, and a deploy is an auditable commit — at the cost of a second repository and handoff, reconcile latency, and needing a separate signal to know when the rollout actually finished. Pull-based GitOps trades credential exposure and drift for indirection; naming both sides is what interviewers listen for.
  4. B is push-based, because the pipeline pushes a commit to the Git repository. Push versus pull describes who applies changes to the cluster; in B an agent inside the cluster pulls from Git, and CI never talks to the API server.
In short

In pull-based GitOps the cluster pulls its state from Git: no cluster credentials in CI and drift is corrected, at the cost of indirection and delay.

Why

Push deploys are simple and give immediate feedback in the pipeline log, but every CI runner that can deploy holds cluster credentials and nothing corrects drift after the run. Pull-based GitOps inverts the trust: the controller runs inside the cluster with a read-only Git credential, compares live state to the declared state on a loop, and reconciles. The costs are real — a deploy becomes "commit, wait for reconcile, then check the controller's status", and you need health assessments or notifications to close the loop. Neither model removes the need to build and test the artifact first.

Read the docs

6 Find what's broken

This workflow tests every pull request and deploys on merge to main. A security reviewer and a release engineer both bounce it. Which lines, and what would you change on each?

name: ci-cd
on:
  pull_request_target:
    branches: [main]
  push:
    branches: [main]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          ref: ${{ github.event.pull_request.head.sha }}
      - uses: actions/setup-node@v4
        with:
          node-version-file: .nvmrc
      - run: npm ci && npm test
        env:
          NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
  build:
    needs: test
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: docker/build-push-action@master
        with:
          push: true
          tags: ghcr.io/acme/api:${{ github.sha }}
  deploy-prod:
    needs: build
    if: github.event_name == 'push'
    runs-on: ubuntu-latest
    environment: production
    steps:
      - uses: actions/checkout@v4
      - run: docker build -t ghcr.io/acme/api:prod . && docker push ghcr.io/acme/api:prod
      - run: kubectl set image deploy/api api=ghcr.io/acme/api:prod
In short

The three faults are pull_request_target running PR code with secrets (line 3), the action pinned to @master (line 25), and the rebuild in deploy (line 36).

What's broken
  • Line 3: pull_request_target runs in the base repository's context with secrets available, and the test job then checks out the PR head (line 13) and runs npm test with NPM_TOKEN in the environment (line 19). A fork can open a PR whose test script exfiltrates the token.
  • Line 25: The build action is pinned to a mutable branch (@master); whoever controls that ref controls code that runs with your registry credentials.
  • Line 36: The deploy job rebuilds the image from source and pushes a floating :prod tag instead of promoting the digest the build job produced and tests ran against.
Why

Three separate disciplines are broken. Secrets: pull_request_target exists so maintainers can act on a PR with secrets, and it is only safe when the job never executes PR-controlled code; checking out head.sha and running its tests is the textbook "pwn request". Supply chain: @master is a mutable pointer, so the pipeline's trust boundary includes everyone who can push to that upstream branch. Artifacts: the deploy job discards the tested digest and builds again, then hides the result behind a tag that means something different every day. Lines 16, 31 and 33 are fine — reading the Node version from .nvmrc, gating deploy on push events, and using a protected production environment are all things a reviewer would praise.

Read the docs

7 Scenario: what do you do next?

You run CI/CD for a fleet of 40 validators on a proof-of-stake network. The pipeline built client release 2.4.0 as an image, and 20 minutes ago the rollout job upgraded the 4 canary validators; the remaining 36 are scheduled to upgrade in 40 minutes on a timer. Dashboards: the 4 canaries show skipped-slot rate up from about 2% to 11% and vote latency p95 roughly 3x, while the other 36 validators are flat. RPC nodes were not touched.

Step 1. The release manager writes: 'Canaries are still voting and producing blocks — OK to let the 15:00 rollout go?' What do you do first?

  1. Roll the 4 canaries back immediately, without looking at anything else. Rollback may well be right, but you have not yet shown the canaries differ from the control group; you would lose the evidence and could mask a network-wide problem that rollback will not fix.
  2. Pause the timed rollout to the 36, then compare the canaries against the untouched validators over the same window and check network-wide skip rate to rule out congestion. Stopping the spread is free and reversible; the canary-versus-control comparison on one window is the single piece of evidence that separates 'our build is degraded' from 'the network is slow tonight'.
  3. Upgrade the RPC nodes too, so the whole system is on one version before judging. Widens the exposure of an unverified release to another tier while the question is still open.
  4. Let it go: producing blocks and voting means the release works. Working is not healthy. The canary exists to catch degradation before 100% exposure; a 5x skip rate on 10% of the fleet is the signal you built it to see.

Step 2. Network-wide skip rate is flat at ~2%; only the 4 upgraded validators are degraded. The 2.4.0 release notes mention a changed default for the accounts-cache size. The release manager wants to ship 2.4.0 plus a cache-size override to all 40 now to 'fix forward'. What do you do?

  1. Roll the 4 canaries back to the previous known-good image digest (the one the other 36 run), confirm skip rate and vote latency recover, keep the rollout paused, and investigate the cache default on one canary afterwards. A known-good artifact beats a guessed fix; the rollback target has 36 validators of evidence behind it, the override has none. Mitigate, then root-cause.
  2. Leave the canaries degraded so you can debug the live problem. Canaries are real validators with real stake and real rewards at risk; debugging live is acceptable only when rollback is impossible.
  3. Restart the canaries; the new cache probably needs to warm up. Twenty minutes in with a 5x skip rate, 'warm-up' has no evidence behind it, and a restart destroys the very warm state the theory depends on.
  4. Ship 2.4.0 with the override to all 40 at once — the cause is obvious from the release notes. An unverified fix at 100% exposure is how a 10% degradation becomes a fleet-wide outage; release notes are a hypothesis, not a measurement.

Step 3. Canary metrics recover within minutes of the rollback. In the postmortem you note that the only gate between canary and fleet was a 60-minute timer. What do you propose?

  1. Add a checklist item: the release manager must look at the dashboards before the fleet rollout. An eyeball at a time-based gate is a reminder, not a mechanism; it fails at 03:00 and on the day the release manager is on holiday.
  2. Increase the canary group from 4 to 20 validators so problems show up faster. The problem was visible with 4; a larger canary only multiplies the blast radius of the next bad release without adding a gate.
  3. Automated canary analysis in the pipeline: compare canaries against a control group on skipped-slot rate, vote latency and slot lag over a fixed bake window; abort and roll back automatically on threshold breach; promote the same image digest only on a green analysis. A mechanism gated on validator health removes the failure class; the timer only ever measured elapsed time.
  4. Drop the canary stage and test releases more thoroughly on a devnet instead. A devnet cannot reproduce mainnet load, stake distribution, or peer behaviour; canaries exist because staging is insufficient, and the two are complementary.
In short

Pause the rollout first, compare canaries with the untouched validators, roll back to the known-good digest, then gate promotion on health, not time.

Why

The shape being scored is independent of the chain: stop the spread before you diagnose, compare treatment against control before you conclude, roll back to a known-good artifact by digest before you attempt a guessed fix, and then replace a time-based gate with a health-based one. Validator fleets make the stakes explicit — skipped slots and late votes are lost rewards and, on some networks, penalties — but the same canary analysis applies to any rollout: define the metrics, the control group, the bake window, and the abort threshold in the pipeline, and promote the identical artifact only when the analysis passes.

8 Quick recall

Interviewer: 'A test fails about one run in ten on code nobody has touched. What do you do with it?' Name the one practice a strong answer gives: not deleting it (lost coverage), not blind retries (hidden races), but keeping it running, tracked with an owner and a fix deadline, outside the blocking suite. What is it called?

In short

The answer is quarantine.

Accepted

quarantine · Quarantine · QUARANTINE

Why

Quarantine keeps the test executing and visible (so the flake is measured and owned) without letting it block merges; deleting it loses coverage and blind retries hide real regressions while lengthening every pipeline run.

9 Read the output

package-lock.json has not changed in weeks, yet every run misses the cache and then saves a new one. Why, and what do you change?

# .github/workflows/ci.yml (excerpt)
- uses: actions/cache@v4
  with:
    path: ~/.npm
    key: npm-${{ runner.os }}-${{ github.sha }}
- run: npm ci

# job log — the same on every run except for the SHA, including two pushes to the same branch 3 minutes apart
Run actions/cache@v4
Cache not found for input keys: npm-Linux-8f3a0c9e2b7d4f1a6c5e9b0d3a2f7c8e1b4d6a90
...
Post job cleanup.
Cache saved with key: npm-Linux-8f3a0c9e2b7d4f1a6c5e9b0d3a2f7c8e1b4d6a90
  1. The key includes the commit SHA, so every commit produces a never-before-seen key; key on hashFiles('**/package-lock.json') instead and add a restore-keys prefix so a lockfile change still restores the closest older cache. A cache key must be a function of the cache's inputs; the SHA changes on every commit even when the inputs did not.
  2. ~/.npm is the wrong path; npm's cache lives in node_modules, so nothing useful is saved. ~/.npm is npm's content-addressable cache and the right thing to persist for npm ci; the path affects what is saved, not whether the key matches.
  3. actions/cache only restores caches created on the default branch, so feature branches always miss. A branch can restore caches created on itself or on its base/default branch; two pushes to the same branch would hit if the key were stable.
  4. The repository is over the cache storage limit, so each cache is evicted before the next run. Eviction is least-recently-used under a size cap; it would not miss on back-to-back runs three minutes apart.
In short

The key contains the commit SHA, so it changes every run; key on the lockfile hash and add restore-keys.

Why

A cache is a lookup keyed by a string; if the string encodes something that varies per run, the lookup is dead on arrival and you pay the save cost every time. The inputs to a dependency cache are the lockfile and the platform, so hashFiles over the lockfile is the key and restore-keys provides a prefix fallback for partial reuse. Two properties should survive any cache design: a miss must produce the same build result, only slower; and nothing correctness- or secret-bearing should ever live in a cache, because caches are shared across runs and, for base-branch caches, across pull requests.

Read the docs

Next lesson IaC review: spotting the faults a reviewer looks for in HCL
Drill · CI/CD pipelines
0:00

Loading…