GitLab CI Caching Strategies for Faster Pipelines
Optimize GitLab CI pipeline speed with effective caching strategies. Learn cache keys, policies, fallback keys, and the difference between cache and artifacts.
Detailed Explanation
Caching Strategies in GitLab CI
Caching is the single most impactful optimization for pipeline speed. A well-configured cache can reduce pipeline duration by 50-80% by avoiding repeated dependency downloads.
Branch-Based Cache
cache:
key: ${CI_COMMIT_REF_SLUG}
paths:
- node_modules/
Each branch gets its own cache. This prevents cache corruption when branches have different dependencies.
Lock-File Based Cache
cache:
key:
files:
- package-lock.json
paths:
- node_modules/
The cache key is a hash of package-lock.json. The cache is invalidated automatically when dependencies change.
Fallback Keys
cache:
key:
files:
- Gemfile.lock
prefix: ${CI_COMMIT_REF_SLUG}
paths:
- vendor/ruby/
fallback_keys:
- ${CI_DEFAULT_BRANCH}-gems
If no cache exists for the current branch, GitLab falls back to the default branch cache.
Cache Policies
| Policy | Behavior |
|---|---|
pull-push |
Download cache before job, upload after (default) |
pull |
Only download, never upload. Use for jobs that don't modify cached content. |
push |
Only upload. Use for the initial cache population job. |
Cache vs. Artifacts
| Feature | Cache | Artifacts |
|---|---|---|
| Purpose | Speed up jobs | Pass files between jobs |
| Reliability | Best-effort | Guaranteed |
| Scope | Across pipelines | Within a pipeline |
| Storage | Runner-local | GitLab server |
Real-World Example
install:
script: npm ci
cache:
key: ${CI_COMMIT_REF_SLUG}
paths: [node_modules/]
policy: push
test:
script: npm test
cache:
key: ${CI_COMMIT_REF_SLUG}
paths: [node_modules/]
policy: pull
Use Case
Apply caching strategies to any pipeline that installs dependencies. The right caching configuration can reduce a 10-minute pipeline to 2-3 minutes by reusing previously downloaded packages.