Last year I cut a client's main pipeline from 23 minutes to just under 6, and the application code barely changed. The wins came entirely from fixing how we cached dependencies, how we split tests, and how we built container images. If your CI pipeline still feels like a coffee break you didn't ask for, the problem is rarely CPU limits — it's almost always wasted work. This article breaks down the three levers I pull first on any slow pipeline: intelligent caching, true test parallelization, and Docker layer optimization, with concrete configurations you can adapt for GitHub Actions, GitLab CI, and similar runners.
Diagnosing Where Your Pipeline Actually Spends Time
Before adding cache directives or throwing more runners at the problem, you need a baseline. In my experience, teams guess wrong about their bottleneck about 70% of the time. They assume tests are slow when it's actually dependency installation or image building.
I start by adding simple timing wrappers to every major step. Most CI systems already expose step durations, but aggregating them over 20-30 runs reveals patterns. Look for three signals: high variance between runs (often cache misses), long tail steps that block everything else, and sequential jobs where a runner sits idle waiting for an upstream stage.
Instrumenting Your Pipeline With Granular Timings
On GitHub Actions, I enable step summaries and upload timing data as an artifact. On GitLab, I use CI_JOB_TRACE artifacts. Even a crude approach works — wrap your commands:
#!/bin/bash
set -e
start=$(date +%s)
npm ci
end=$(date +%s)
echo "npm ci took $((end-start))s" | tee -a timing.log
start=$(date +%s)
npm run build
end=$(date +%s)
echo "build took $((end-start))s" | tee -a timing.log
Collect that timing.log for a week. I once found a pipeline where npm ci averaged 92 seconds on a cache miss but only 11 seconds on a hit — yet the hit rate was only 34% due to a bad cache key. Without numbers, we would have blamed Jest.
The Cold Start vs. Warm Cache Comparison
Run your pipeline twice: once with caches cleared and once immediately after. The delta tells you your theoretical best case. If the difference is less than 15%, your caches are either ineffective or not the real problem. If the difference is 3x or more, you have found your leverage point. I've found that documenting this cold vs. warm comparison is the easiest way to justify optimization time to management.
Caching Dependencies Without Poisoning Your Builds
Caching is not just turning on actions/cache and calling it a day. A poorly keyed cache is worse than no cache — it gives you false confidence while serving stale artifacts or causing non-deterministic failures.
The core principle is precision in your cache key. You want to invalidate exactly when inputs change, and not before. For Node.js, that means hashing both package-lock.json and the Node version. For Python, it's poetry.lock or requirements.txt plus the Python version. For Go, it's go.mod and go.sum.
# GitHub Actions: precise caching for Node.js with fallback
- name: Cache Node dependencies
uses: actions/cache@v4
with:
path: ~/.npm
key: npm-${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}-${{ hashFiles('.nvmrc') }}
restore-keys: |
npm-${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}-
npm-${{ runner.os }}-
- name: Install dependencies
run: npm ci --prefer-offline
Notice the restore-keys fallback. In my experience, a partial cache hit is still 60-80% faster than a full download, especially for large native modules. But never fall back across major lockfile changes — that's how you get ghost dependencies that pass CI but fail in production.
Avoiding Cache Poisoning and Bloating
Two mistakes I see constantly: caching node_modules directly instead of the package manager cache, and never evicting old caches. Caching node_modules couples your cache to the OS, architecture, and Node ABI. It breaks when you upgrade a native dependency. Cache the download directory (~/.npm, ~/.cache/pip, ~/.cache/go-build) and let the install step do its linking and compilation.
Cache bloat is the other killer. GitHub Actions has a 10GB cache limit per repo and evicts least-recently-used entries. If you cache .next/cache, Playwright browsers, and pip at once without compression, you churn through that limit in days. I recommend separating caches by purpose with distinct keys and using actions/cache with save-always: false on pull requests that don't need to populate the primary branch cache.
For teams running GitLab, the model is slightly different but the principle holds. You get more control over distributed cache backends like S3. I cover the DAG and cache interplay in more detail in GitLab CI Pipeline Optimization: DAG, Cache and Parallel Jobs, which is worth reading if you are on GitLab's shared runners.
Docker Layer Optimization for Ephemeral CI Runners
CI runners are ephemeral by design, which is exactly why naive Docker builds are so slow there. Every run starts with an empty Docker daemon, so docker build without configuration rebuilds every layer. The fix is to externalize the build cache.
According to the Docker Documentation, BuildKit can import and export caches to a registry, which survives across ephemeral nodes. This is far more reliable than trying to use actions/cache for Docker layers, which was never designed for large layer blobs.
# Build with registry-backed cache using docker/build-push-action
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Build and push with inline cache
uses: docker/build-push-action@v5
with:
context: .
push: true
tags: ghcr.io/org/app:${{ github.sha }}
cache-from: type=registry,ref=ghcr.io/org/app:buildcache
cache-to: type=registry,ref=ghcr.io/org/app:buildcache,mode=max
build-args: |
BUILDKIT_INLINE_CACHE=1
The mode=max is critical. By default, only the final stage is cached. With max, every intermediate layer is cached, which matters for multi-stage builds. I saw a Java multi-stage build drop from 4m 40s to 48s with this change alone.
Writing Dockerfiles That Cache Effectively
Your Dockerfile order determines cache hit rate more than any CI setting. I follow a strict hierarchy: least likely to change first.
Copy dependency manifests alone, install dependencies, then copy source code. Never do COPY . . before RUN npm ci. For example:
# Bad: invalidates cache on any file change
COPY . .
RUN npm ci
RUN npm run build
# Good: dependency layer cached until package files change
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
COPY src ./src
COPY tsconfig.json ./
RUN npm run build
I also split dev and prod dependencies. If your tests need devDependencies, create a separate test stage. That way your production image build doesn't invalidate when you add a testing library. When orchestrating these builds on Kubernetes-based runners, understanding ephemeral storage helps — the Kubernetes Documentation on emptyDir and ephemeral volumes explains why local Docker layer caches disappear between pods.
When to Use Layer Mount Caches
For package managers inside Docker, use BuildKit cache mounts instead of registry cache for even faster results:
# syntax=docker/dockerfile:1.4
FROM node:20-alpine
RUN --mount=type=cache,target=/root/.npm \
--mount=type=cache,target=/app/.npm \
npm ci
This keeps the npm cache outside the layer itself, reducing image size and avoiding invalidation from lockfile tweaks that don't affect most packages. In practice, I've found this shaves another 15-20 seconds off Node builds.
Test Parallelization Strategies That Scale Past 1000 Tests
Running tests serially is the most common speed killer I encounter in mid-size codebases. A suite that takes 12 minutes on one runner can often finish in 3-4 minutes across four shards — if you split it correctly.
There are two levels: job-level parallelism (splitting test files across runners) and process-level parallelism (running tests in parallel inside one runner via Jest workers, pytest-xdist, etc.). Job-level gives you better isolation and scales linearly, but has overhead from spinning up environments. Process-level is faster to start but limited by CPU and memory on a single runner. I usually combine both.
For Jest, Vitest, or Playwright, file-based sharding is the simplest reliable method. Avoid timing-based sharding until you have stable historical data — it adds complexity and can mask flaky tests.
# Example: Sharding Jest tests across 4 parallel jobs
# In GitHub Actions matrix
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
shard: [1, 2, 3, 4]
steps:
- uses: actions/checkout@v4
- run: npm ci
- run: npm test -- --shard=${{ matrix.shard }}/4 --ci --maxWorkers=2
env:
JEST_JUNIT_OUTPUT: junit-${{ matrix.shard }}.xml
- uses: actions/upload-artifact@v4
with:
name: junit-${{ matrix.shard }}
path: junit-${{ matrix.shard }}.xml
The --maxWorkers=2 inside each shard is intentional. On a 2-core GitHub runner, setting workers higher than cores causes context switching that actually slows the run. I've benchmarked this — two workers per 2-core runner is almost always optimal; four workers is slower.
Handling Flakes and Shared State in Parallel Runs
Parallelization amplifies flakiness. Tests that passed serially because they implicitly depended on order or shared a database will fail when run concurrently. I enforce three rules:
First, each shard must get an isolated database or schema. Use template databases in Postgres or random database names per job. Second, avoid shared filesystem state — write to tmpdir with unique prefixes. Third, make your test runner aware of retries but track them. I fail the pipeline if flaky retries exceed 2% — otherwise you hide real problems.
If you are using GitHub Actions, the matrix approach I show above is covered in more depth in GitHub Actions Advanced Workflows: Matrix Builds, Reusable Actions and OIDC, including how to fan-in results for a single required status check. That fan-in pattern is essential — you don't want to require four separate green checks for branch protection.
Structuring Workflows to Eliminate Idle Runner Time
The fastest cache and best sharding still lose if your workflow is a straight line. I see pipelines defined as lint -> test -> build -> deploy where build waits for lint to finish even though they have no dependency. Modern CI systems support Directed Acyclic Graphs (DAGs) to run independent jobs concurrently.
Separate your workflow into independent tracks: lint/typecheck, unit tests, and Docker build can all start immediately after checkout. Integration tests that need the built image should depend only on the build, not on lint. This trims queue time dramatically.
Another trick I use is fail-fast for lint and typecheck but not for the full matrix. If ESLint fails, I want the whole workflow to stop in 30 seconds, not after 6 minutes of tests. Configure fail-fast: true for pre-checks and fail-fast: false for test shards so you get complete failure data in one run.
Conditional Execution and Path Filtering
Not every change needs the full pipeline. Docs-only changes shouldn't rebuild a Docker image. I apply path filters aggressively:
on:
pull_request:
paths-ignore:
- 'docs/**'
- '*.md'
jobs:
build:
if: needs.changes.outputs.app == 'true'
runs-on: ubuntu-latest
steps:
- run: echo "Building because app files changed"
Combined with reusable workflows, this keeps the pipeline fast for the 30% of PRs that are non-code changes. Just be careful not to over-filter in a way that hides integration failures — I always run a full pipeline on main regardless of path filters.
Speed improvements also interact with security controls. Faster pipelines tempt teams to skip signing or scanning steps. Don't. Instead, parallelize security scans alongside tests. I discuss how to keep SLSA provenance and scanning without slowing merges in CI/CD Security: Pipeline Hardening, SLSA and Software Supply Chain.
Measuring Speed Improvements Without Vanity Metrics
It's easy to report a 50% improvement that doesn't actually help developers. I track three metrics that reflect real developer experience: median time to green on pull requests, p95 time to green, and queue time (time from push to job start).
Median tells you the typical experience; p95 tells you if your optimization helps worst-case changes. Queue time reveals runner capacity issues — adding caches won't help if jobs wait 4 minutes for a runner. In one team, we added 10 more concurrency slots on self-hosted runners and p95 dropped by 5 minutes with zero code changes.
One comparison I use when proposing changes to stakeholders is the cost vs. speed tradeoff of different approaches:
| Optimization | Typical Time Saved | Implementation Effort | Recurring Cost |
|---|---|---|---|
| Dependency Cache (proper keying) | 60-90s per job | Low (1-2 hours) | Cache storage ~$2-5/mo |
| Docker Registry Cache | 2-4 min per build | Medium (half day) | Registry storage + egress |
| Test Sharding (4 shards) | 50-75% of test time | Medium (1 day) | 4x runner minutes |
| DAG Parallel Stages | 1-3 min wall-clock | Low (2-3 hours) | None |
| Self-hosted Larger Runners | 20-40% per job | High (1-2 weeks) | Infra + maintenance |
This table is based on my measurements across Node.js and Python services with 10-20 minute baseline pipelines. Your numbers will vary, but it frames the discussion: caching and DAG restructuring are almost always the highest ROI first steps.
Finally, track cache hit rate over time. I add a step that echoes cache hit/miss to a metrics service or even just logs it for Datadog. If hit rate drops below 80% after an optimization, something is wrong with your key. If it stays at 99% but pipeline is still slow, your cache isn't covering the bottleneck.
Frequently Asked Questions
How do I know if my cache is actually being used?
Check the CI logs for cache hit/miss messages. In GitHub Actions, actions/cache logs "Cache hit" or "Cache miss" explicitly. I also add a verification step that checks for the cached directory and prints its size and timestamp. For Docker, run docker buildx build --progress=plain and look for CACHED next to steps. If you never see cache hits, your key is likely too specific (e.g., includes commit SHA) or your cache is evicted before reuse due to size limits.
Should I parallelize tests or just use a bigger runner?
Do both in order. First, try process-level parallelism inside one runner by tuning maxWorkers or pytest-xdist -n auto. If tests still exceed 5 minutes, shard across multiple jobs. A larger runner helps single-threaded steps like TypeScript compilation, but it won't scale linearly for thousands of tests the way sharding does. In my experience, sharding to 4 jobs on standard 2-core runners outperforms one 8-core runner for test suites and costs less in most cloud CI pricing.
Why is my Docker build still slow even with layer caching?
Common causes are: 1) Your Dockerfile copies source code before installing dependencies, invalidating the cache on any file change; 2) You are not using mode=max so intermediate layers aren't cached; 3) You use ADD with a remote URL that busts cache every time; or 4) Your base image tag is floating (e.g., node:20 vs node:20.11-alpine) and changes frequently. Pin your base image with a SHA or specific patch version and reorder your Dockerfile to copy dependency files first.
Can aggressive caching hide bugs or cause flaky builds?
Yes, if your cache key includes too little. For example, caching node_modules directly can hide a broken install script that only fails on clean installs. I avoid this by caching the package manager cache, not the installed modules, and by running a nightly scheduled pipeline with caches disabled to catch drift. Also validate that lockfile hashes are part of the key — otherwise a dependency update in code won't invalidate the cache and you'll test against old code.