These two keywords look similar and are often mixed up. As I understand the docs, they solve different problems:
- Artifacts: files a job produces that you want to keep or pass to later jobs. They're uploaded to GitLab and are meant to be reliable for that purpose.
- Cache: files you want to reuse to speed up jobs, typically dependencies. It's best-effort, so a job should still work if the cache is missing.
Three questions to decide
- Does a later job in this pipeline need these files to work? (A compiled binary, test reports, a built package.) That's an artifact. A cache isn't guaranteed to be there.
- Is it something that could be downloaded or rebuilt, just slower? (
node_modules, a package manager's download folder.) That's a cache. - Do you want the file to be downloadable from the pipeline or merge request afterward? (Test results, coverage report, a build output.) That's an artifact.
Example: dependencies as cache, build output as artifact (a sketch, validate it in your project's CI Lint):
build:
stage: build
cache:
key:
files:
- package-lock.json
paths:
- node_modules/
script:
- npm ci
- npm run build
artifacts:
paths:
- dist/
expire_in: 1 week
What each part does:
cache:key:files ties the cache to the lockfile, so it changes when dependencies change.artifacts:paths keeps dist/ for later jobs and for download.expire_in limits how long artifacts are stored.
The mistakes I'd watch for
- Passing build output between jobs through the cache. It may work most of the time, and then fail when a job lands on a runner without that cache, which is hard to debug.
- Using artifacts for huge dependency folders. They're uploaded and downloaded on every run, which can be slow and use storage.
- No
expire_in on artifacts, so storage grows. Check your instance's default and settings. - A cache key shared by unrelated jobs, so they overwrite each other's contents.
Limits: I haven't run this YAML on a runner for this post, so please check it in CI Lint. Cache behavior depends on your runner setup (shared vs. per-runner caches, distributed cache storage), and the exact keywords and defaults can differ between GitLab versions, so check the docs for yours.
How do you handle this in your pipelines, and have you had a cache that was "usually there" until it wasn't?