Last year I inherited a GitLab CI pipeline that took 38 minutes to run on every merge request. It was linear, stage-gated, and rebuilt the world from scratch each time. Three stages — build, test, deploy — but each job waited for the entire previous stage to finish, even when it only needed one artifact from one upstream job. After six weeks of iterative tuning, that same pipeline averaged 6 minutes and 40 seconds without throwing more runners at the problem. The gains came from restructuring dependencies with DAG, fixing a cache strategy that never hit, and parallelizing the right jobs instead of everything. This article walks through the exact patterns I used, where they break, and how to measure whether they actually help.
Escaping Linear Stages: Building an Efficient DAG with needs and dependencies
By default, GitLab CI enforces stage ordering. Every job in test waits for every job in build, even if it only needs one upstream artifact. In my experience, this is the single largest source of wasted time in intermediate pipelines. DAG — directed acyclic graph — execution with needs: lets jobs start as soon as their specific dependencies finish, regardless of stage.
I found that teams overuse stages as organizational buckets rather than execution constraints. When I audited that 38-minute pipeline, the frontend lint job was waiting for a backend Docker build it never used. Decoupling them immediately recovered 4 minutes. The trade-off is that you need to be explicit about artifacts and dependencies; DAG fails silently if you assume data will be there when it isn't.
How needs Rewrites Your Execution Graph
When you add needs:, the job no longer waits for the prior stage. It will start when the listed jobs complete successfully. You can also set needs: [] implicitly by not defining stages, but I prefer keeping stages for visualization while using needs to override ordering. Use artifacts: true/false on needs to control whether you download artifacts from that dependency — critical for reducing network time when you only need status, not files.
# Before: linear, everything waits for everything
stages: [build, test, package]
build:backend:
stage: build
script: ./build-backend.sh
build:frontend:
stage: build
script: ./build-frontend.sh
test:unit:
stage: test
script: npm test # waits for BOTH build jobs
# After: DAG, test starts as soon as its real dependency is ready
stages: [build, test, package]
build:backend:
stage: build
script: ./build-backend.sh
artifacts:
paths: [dist/backend/]
build:frontend:
stage: build
script: ./build-frontend.sh
artifacts:
paths: [dist/frontend/]
test:unit:backend:
stage: test
needs:
- job: build:backend
artifacts: true
script: ./run-backend-tests.sh
test:unit:frontend:
stage: test
needs:
- job: build:frontend
artifacts: true
script: npm test
When Not to Use needs Everywhere
DAG is not always better. If you have strict deployment ordering or jobs that rely on side effects like populating a shared cache, forcing everything into a DAG can create race conditions. I've also seen pipelines where every job had six needs entries, making the graph unreadable. My rule: use needs for jobs with a clear 1:1 or 1:2 upstream dependency, and keep dependencies: only when you need to limit which artifacts are downloaded but still want stage ordering. And if you chain needs across 10+ jobs, consider splitting the pipeline into parent-child pipelines instead — GitLab's Docker Documentation and GitLab's own runner docs both note that overly complex DAGs increase scheduler overhead on the coordinator.
Cache Invalidation Done Right: Keys, Scopes and Distributed Storage
Cache in GitLab CI is easy to configure and easy to get wrong. In one project, the cache hit rate was effectively 0% for two months because the key was $CI_COMMIT_REF_SLUG per branch but the runner was autoscaled and used a local filesystem. Each new pod had an empty cache. We were paying the cost of compressing and uploading a 1.2GB node_modules on every run with zero benefit.
The first distinction to internalize is cache vs. artifacts vs. dependencies. Cache is best-effort and can be evicted. Artifacts are passed between jobs and stored for a defined expiry. If you need a file in the next job, that's an artifact, not a cache. For a deeper look at how artifacts and registries fit together, see Artifact Management: Container Registries, Helm Charts and Build Caching, which covers when to push to a registry versus passing data through GitLab.
Designing Cache Keys That Actually Hit
A good key balances hit rate with correctness. Branch-only keys cause pollution. Commit-SHA keys never hit. I've found that hashing lockfiles works best for most Node, Python, and Go projects.
variables:
NPM_CONFIG_CACHE: "$CI_PROJECT_DIR/.npm"
cache: &global_cache
key:
files:
- package-lock.json
- pnpm-lock.yaml
prefix: $CI_JOB_NAME
paths:
- .npm/
- node_modules/
- .pnpm-store/
policy: pull-push
when: always
install:deps:
stage: build
cache:
<<: *global_cache
policy: pull-push
script:
- npm ci --cache .npm --prefer-offline
test:unit:
stage: test
needs: [install:deps]
cache:
<<: *global_cache
policy: pull # don't re-upload from test jobs
script:
- npm test -- --maxWorkers=2
Notice the prefix: $CI_JOB_NAME. Without it, a cache saved by install:deps can be overwritten by test:unit with a partial or corrupted state. Using policy: pull on downstream jobs prevents that. Also, set when: always if you want caches saved even on failed jobs — useful when you want to keep a partially populated cache for the next retry.
Distributed Cache on Kubernetes and Docker Autoscalers
If you run runners on Kubernetes or Docker autoscaler, local cache is ephemeral. You need an object storage backend. For the Kubernetes executor, configure the distributed cache via S3-compatible storage. I've used MinIO internally and S3 externally; both work if you tune the timeout and multipart settings. The Kubernetes Documentation is useful here for understanding pod eviction and ephemeral storage limits, which directly affect how long a local cache directory survives. In my experience, without S3-backed cache, your hit rate on an autoscaled fleet will stay under 20%. With it, we moved to 78-85% for lockfile-based keys. One gotcha: set cache: untracked: false and explicitly list paths — untracked caches balloon to gigabytes quickly and your S3 egress bill will reflect it.
Parallel Execution Patterns: Matrix Jobs, Sharding and Resource Limits
Parallelism is where pipeline optimization feels most rewarding, but also where runners melt down if you overdo it. GitLab offers three mechanisms that look similar but solve different problems: parallel: for N identical jobs, parallel:matrix: for combinatorial variants, and job sharding via environment variables.
In my experience, the fastest win is sharding tests. A single Jest run with 900 tests took 9 minutes. Splitting it into 4 parallel jobs with parallel: 4 and sharding by file list brought it to 2 minutes 40 seconds on the same runner types. The overhead of spinning up four containers was about 18 seconds, but the net saving was still over 6 minutes.
Choosing Between parallel and parallel:matrix
Use parallel: N when you want the same script to run N times with CI_NODE_INDEX and CI_NODE_TOTAL available. Use parallel:matrix when you need different variables per job, like Node versions or target architectures. I see teams abuse matrix for what should be simple sharding, creating 12 jobs where 4 would do, and then hitting runner concurrency limits.
# Sharding tests across 4 identical runners
test:unit:sharded:
stage: test
needs: [install:deps]
parallel: 4
cache:
key:
files: [package-lock.json]
paths: [node_modules/]
policy: pull
script:
- |
echo "Running shard $CI_NODE_INDEX of $CI_NODE_TOTAL"
npm exec jest -- --shard=$CI_NODE_INDEX/$CI_NODE_TOTAL --ci --maxWorkers=2
# Matrix for cross-version validation - use sparingly
test:compat:
stage: test
parallel:
matrix:
- NODE_VERSION: ["18", "20", "22"]
DB: ["postgres:14", "postgres:16"]
- NODE_VERSION: ["20"]
DB: ["mysql:8"]
image: node:$NODE_VERSION
services:
- name: $DB
alias: db
script:
- npm test -- --runInBand
The matrix example above creates 7 jobs (3x2 for postgres + 1 for mysql). If you run that on every commit, you will queue. I've found it better to gate matrix jobs with rules: so they only run on main or scheduled pipelines, while merge requests run a single representative configuration.
Sizing and Throttling Parallelism
Don't set parallel: 10 on a runner with 2 vCPUs and 4GB RAM using Docker executor. Each job is a separate container. If your runner's concurrent setting is 4, five of those ten jobs will queue anyway, but you still paid scheduling overhead. I tune based on runner capacity: for a shared Kubernetes runner with 8 vCPUs per pod, parallel: 4 with maxWorkers=2 per shard keeps CPU at 70-80% without thrashing. Monitor the runner's queue time in GitLab's Admin > Runners view or via Prometheus metrics if you export them.
Runner and Executor Tuning: Making Kubernetes and Docker Runners Keep Up
You can optimize YAML forever and still be bottlenecked by runner configuration. In one setup, we had correctly parallelized jobs but the Kubernetes executor was using the default 1 CPU request, throttling every build during npm install. Bumping the request to 2 CPUs and setting a limit of 4 cut that step from 110 seconds to 48.
For Docker executor, watch volume mounts and pull_policy. Using pull_policy: if-not-present saves 10-15 seconds per job if your images are stable, but can cause stale base images. I prefer pull_policy: always for production pipelines and if-not-present for feature branches where speed matters more. Also, limit helper image resource usage — the GitLab runner helper container can OOM if you pass huge artifacts around.
Tags, Resource Groups and Concurrency
Use runner tags to route heavy jobs to beefy runners. For example, tag high-mem for Docker builds that need BuildKit cache, and standard for lint and unit tests. I've also used resource_group to serialize deployments while keeping builds parallel — otherwise two canary deploys would race. This connects directly to deployment concerns covered in Deployment Strategies: Blue-Green, Canary and Rolling Updates Compared; your pipeline speed is irrelevant if your deployment jobs conflict and roll back.
| Data Passing Method | Best For | Hit / Availability | Cost & Performance Note |
|---|---|---|---|
| cache | Dependencies between pipeline runs (npm, pip, Go mod) | Best-effort; may be evicted | Low cost if S3-backed; saves 40-90s per job when hit, zero benefit when missed |
| artifacts | Files needed by later jobs in same pipeline (dist/, coverage) | Guaranteed for pipeline duration | Network-bound; use needs:artifacts:false when not needed to save download time |
| needs (DAG) | Controlling start time, not file transfer | Deterministic dependency graph | Reduces wait time 30-60% vs stage ordering; no storage cost |
| Distributed container registry | Docker layers and Helm charts across pipelines | Persistent and shared | Ideal for multi-stage Docker builds; see registry cache docs for BuildKit |
Cutting Waste with Rules and Workflow Controls: Running Only What Changed
The cheapest job is the one you don't run. GitLab's rules:, workflow:rules:, and rules:changes: let you skip entire sections of the pipeline based on branch, file changes, or variables. In a monorepo with three services, we cut average MR pipeline time by 55% by only running the affected service's jobs.
Start at the top with workflow:rules. I always add a rule to prevent duplicate pipelines when pushing to a merge request branch that also triggers a branch pipeline. Without it, you double your runner usage for no reason.
rules:changes and Parent-Child Pipelines for Monorepos
rules:changes checks which files changed in the push. Combine it with needs and child pipelines to isolate services. One pattern I've used successfully: a thin parent pipeline that triggers child pipelines per service only when that service's path changed. Each child pipeline has its own DAG and cache, so failures are isolated and developers get faster feedback on their slice.
workflow:
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
- if: $CI_COMMIT_TAG
- when: never
stages: [trigger]
trigger:backend:
stage: trigger
trigger:
include: backend/.gitlab-ci.yml
strategy: depend
rules:
- changes:
- backend/**/*
- shared/**/*
when: on_success
- when: never
trigger:frontend:
stage: trigger
trigger:
include: frontend/.gitlab-ci.yml
strategy: depend
rules:
- changes:
- frontend/**/*
- shared/**/*
when: on_success
- when: never
Be careful with rules:changes for jobs that generate artifacts needed later. If a job is skipped but a downstream job still needs it, the pipeline will fail. Use needs: optional: true for those edges, or restructure so downstream jobs also have matching rules:changes. For comparison, GitHub Actions Advanced Workflows: Matrix Builds, Reusable Actions and OIDC shows a similar paths-filter approach — the concept transfers directly, even if the syntax differs.
Caching Security and Supply Chain Implications
Skipping jobs and caching more aggressively has a security angle. Cached node_modules can carry poisoned dependencies across pipelines if your cache key is too coarse and you never re-validate. I enforce npm ci with lockfile hashing and rotate caches on dependency updates, and I treat pipeline hardening as part of optimization. For a thorough checklist, see CI/CD Security: Pipeline Hardening, SLSA and Software Supply Chain — especially the section on pinning actions and verifying artifacts, which applies equally to GitLab's cache and artifact flow.
Measuring What Matters: Pipeline Analytics, Tracing Bottlenecks and Cost
You cannot optimize what you don't measure. GitLab provides pipeline duration graphs, but I rely on explicit timing. Add CI_DEBUG_TRACE: "true" sparingly, or better, wrap scripts with time and export durations as metrics. I export job durations to Prometheus via the runner's metrics and to Grafana, where I track p50/p95 per job, cache hit rate, and queue time.
In one audit, the bottleneck wasn't CPU but artifact download. A 900MB dist artifact was being downloaded to five downstream jobs that only needed 30MB of it. Splitting the artifact into dist:frontend and dist:backend and using needs:artifacts:false for lint jobs saved 42 seconds per pipeline. Another common bottleneck is Docker layer pull on Kubernetes runners without a daemon cache — enabling BuildKit inline cache and pushing to a registry cut Docker builds from 4 minutes to 55 seconds.
Practical Metrics to Track Weekly
Track these three numbers: end-to-end pipeline duration for merge requests, cache hit rate by job name, and runner queue time. If queue time is rising, you are over-parallelizing or under-provisioning. If cache hit rate is below 60% and you use S3, your keys are wrong. If duration variance is high, you have flaky tests or non-deterministic ordering. I review these in a 15-minute weekly check — it's more useful than any one-off optimization pass.
Frequently Asked Questions
When should I use needs instead of dependencies?
Use needs: when you want jobs to start early without waiting for the entire previous stage. Use dependencies: only when you need to limit which artifacts are downloaded but are fine with stage ordering. In practice, I default to needs for all new pipelines because it gives you DAG execution and artifact control in one keyword, and I set artifacts: false on needs when a job only cares about status, not files.
Why is my GitLab cache not hitting even with correct keys?
The most common causes are ephemeral runners without S3-backed storage, cache policy conflicts, and overly narrow key prefixes. If your runners are on Kubernetes or autoscaled Docker, local filesystem cache is lost when the pod terminates — configure S3 distributed cache. Also check that downstream jobs use policy: pull so they don't overwrite a good cache with a partial one, and verify the key files actually exist in the job's working directory.
How much parallelism is too much?
It depends on your runner's CPU, memory, and concurrent setting. A good starting point is 2-4 shards for test suites under 1000 tests and 4-8 for larger suites, then measure queue time and CPU throttling. I've found that beyond 8 parallel shards, the overhead of spinning up jobs and merging results often outweighs the gains unless you have dedicated high-concurrency runners. Gate heavy matrix jobs to main branch or schedules to avoid queuing merge requests.
Should I use cache or artifacts for Docker layers?
Use neither directly. For Docker layers, push BuildKit cache to a container registry with --cache-from and --cache-to or use registry mirrors. GitLab cache is not designed for large layer blobs and will be slow and unreliable. Artifacts work for small images, but a registry is persistent across pipelines and shared across runners, which is what you want for layer caching.