Skip to content
Latchkey

How to Cache with restore_keys in CircleCI

Layered keys let CircleCI fall back to an older cache when the exact key misses.

restore_cache tries each key in order. A checksum-based primary key plus a broader fallback means even a stale cache seeds your install, cutting cold-cache time.

Layered restore with a fallback key

List the precise key first, then a prefix that matches the most recent cache.

.circleci/config.yml
jobs:
  build:
    docker:
      - image: cimg/node:20.11
    steps:
      - checkout
      - restore_cache:
          keys:
            - deps-v1-{{ checksum "package-lock.json" }}
            - deps-v1-
      - run: npm ci
      - save_cache:
          key: deps-v1-{{ checksum "package-lock.json" }}
          paths:
            - ~/.npm

Notes

  • CircleCI caches are immutable; bump the v1 prefix to force a clean rebuild.
  • The trailing deps-v1- fallback matches the newest cache with that prefix, avoiding a full cold install.

Verify it actually works

  • Trigger the real event rather than a manual run. Manual dispatch populates a different context, so behaviour depending on the event will differ.
  • Assert on the outcome, not on the step exiting zero. Many steps report success while producing nothing.
  • Check it on a fresh runner with a cold cache once, so you are not testing warm state that will not exist on the next contributor machine.

Frequently asked questions

How do I cache with restore_keys in CircleCI?
restore_cache tries each key in order. A checksum-based primary key plus a broader fallback means even a stale cache seeds your install, cutting cold-cache time.
Layered restore with a fallback key?
List the precise key first, then a prefix that matches the most recent cache.

Related guides

References

Run this faster and cheaper on Latchkey managed runners - self-healing included. Start free → 30-day trial · No credit card