14 Jenkins Tips to Build Faster Pipelines

14 ways to speed up Jenkins pipelines: parallel and matrix stages, caching, shallow clones, Kubernetes agents, durability settings and lean Groovy.

Dec 13, 2025 - 16:26
Nov 10, 2026 - 04:03
 0  128
14 Jenkins Tips to Build Faster Pipelines

To build faster Jenkins pipelines, measure where the time goes, then run independent stages in parallel, skip work that has not changed, cache dependencies and Docker layers, use short-lived agents sized for the job, and keep heavy logic in shell steps instead of Groovy on the controller. Most slow builds lose time in checkout, dependency downloads, and serial test runs.

This guide is part of our CI/CD pipeline examples series. Each tip below names the real Jenkins directive or plugin, shows a short Jenkinsfile snippet, and says when it helps and when it does not. Syntax was checked against the official Pipeline Syntax reference and plugin pages in November 2026.

Key takeaways

  • Find the slowest stage before you change anything. A five minute dependency download is a different problem from a five minute test suite.
  • parallel and matrix give the biggest wins when you have spare agent capacity. Without free executors they just queue.
  • Shallow clones, when { changeset } and dependency caches cut repeat work on every run.
  • Ephemeral agents on Kubernetes remove "dirty workspace" bugs and let you scale build capacity up and down.
  • Keep the controller for orchestration. Run zero executors on the built-in node and move parsing and loops out of Groovy.

Quick reference: the 14 tips

#TipJenkins featureTypical saving
1Measure stage timingsPipeline Graph View, build logsTells you where to start
2Run independent stages in parallelparallel, parallelsAlwaysFailFast()Wall-clock time of the longest branch
3Fan out across versions and platformsmatrixMany combinations at once
4Clone lessShallow clone, reference repoCheckout time on large repos
5Skip unchanged componentswhen { changeset }Whole stages in monorepos
6Cache dependenciesJob Cacher plugin, persistent volumesPackage download time
7Reuse Docker layersBuildKit registry cacheImage build time
8Use ephemeral agentsKubernetes pluginQueue time, clean workspaces
9Keep builds off the controller0 executors on the built-in nodeController stability
10Move files the right waystash for small files, artifact repo for largeTransfer time between agents
11Lower pipeline durabilitydurabilityHintController disk I/O
12Write lean GroovyShell steps, shared librariesController CPU and memory
13Stop runaway and stale buildstimeout, disableConcurrentBuilds, buildDiscarderExecutor and disk capacity
14Split test suitesParallel Test Executor pluginTest stage time

1. Measure stage timings before you optimise

Open a few recent builds and note how long each stage took. The Pipeline Graph View plugin shows stage durations visually, and timestamps in the console log (the Timestamper plugin, or options { timestamps() } where it is installed) show which individual step is slow. Write down a baseline: total time, queue time, checkout, dependency install, build, test, and publish.

Queue time deserves its own line. If builds wait ten minutes for a free executor, no amount of caching inside the pipeline will fix that. You need more agents or fewer concurrent jobs. For pipeline health metrics over time, see our list of CI/CD monitoring tools.

2. Run independent stages in parallel

Lint, unit tests, and a security scan usually do not depend on each other. Declarative Pipeline lets you run them as parallel branches. The stage takes as long as its slowest branch instead of the sum of all three.

pipeline {
  agent none
  options { parallelsAlwaysFailFast() }
  stages {
    stage('Checks') {
      parallel {
        stage('Lint') {
          agent { label 'linux' }
          steps { sh 'npm ci && npm run lint' }
        }
        stage('Unit tests') {
          agent { label 'linux' }
          steps { sh 'npm ci && npm test' }
        }
        stage('Dependency scan') {
          agent { label 'linux' }
          steps { sh './scripts/scan-deps.sh' }
        }
      }
    }
  }
}

parallelsAlwaysFailFast() aborts the other branches as soon as one fails, so you do not wait for a full test run when lint has already broken the build. You can also set failFast true on a single parallel stage. Parallel branches only help when there are enough executors to run them at the same time. If every branch lands on the same single-executor agent, they run one after another.

3. Use matrix for version and platform combinations

When you test against several runtime versions or operating systems, the matrix directive generates the combinations for you and runs them in parallel.

stage('Test matrix') {
  matrix {
    axes {
      axis { name 'JDK'; values '17', '21' }
      axis { name 'OS'; values 'linux', 'windows' }
    }
    agent { label "${OS}" }
    stages {
      stage('Test') {
        steps { echo "Testing on ${OS} with JDK ${JDK}" }
      }
    }
  }
}

Use excludes to drop combinations you do not support. Each cell needs an executor, so a 3 by 3 matrix wants nine free slots to finish in one pass.

4. Clone less of the repository

On a repository with years of history, a full clone can take longer than the build. The Git plugin supports shallow clones and reference repositories through CloneOption.

checkout([$class: 'GitSCM',
  branches: scm.branches,
  userRemoteConfigs: scm.userRemoteConfigs,
  extensions: [
    [$class: 'CloneOption', shallow: true, depth: 1, noTags: true, timeout: 10]
  ]
])

Shallow clones break tools that need history, such as git describe or versioning based on tags, so test before rolling out. On long-lived agents, a reference repository (a local mirror the clone borrows objects from) gives most of the speed without losing history. If you call checkout yourself, add options { skipDefaultCheckout() } so Jenkins does not clone twice.

5. Skip stages when nothing relevant changed

In a monorepo, a change to the docs folder should not rebuild every service. The when directive with changeset runs a stage only if files matching a pattern changed.

stage('Build payments service') {
  when { changeset 'services/payments/**' }
  steps { sh 'make -C services/payments build' }
}

Combine it with branch or anyOf so that release branches still build everything. Be careful on the first build of a new branch: the changeset can be empty, so decide whether an empty changeset means "build all" or "build nothing".

6. Cache dependencies between builds

Downloading the same Maven, npm, or pip packages on every run is slow and hard on your network. Two common approaches:

  • Job Cacher plugin. The Job Cacher plugin saves and restores folders such as ~/.m2/repository or node_modules, and can invalidate the cache when a lockfile changes. It works well with ephemeral agents because the cache lives outside the agent.
  • Persistent volumes on Kubernetes agents. Mount a shared volume at the package cache path in your pod template. This is fast but needs care when several builds write to the same cache at once.

A local proxy repository such as Nexus or Artifactory also helps, because downloads come from inside your network instead of the internet.

7. Reuse Docker layers with BuildKit cache

On ephemeral agents the local Docker cache is empty every time. BuildKit can export and import cache to a registry, so the next build reuses unchanged layers. The Docker registry cache backend documents these flags:

docker buildx build \
  --cache-from type=registry,ref=registry.example.com/app:buildcache \
  --cache-to type=registry,ref=registry.example.com/app:buildcache,mode=max \
  -t registry.example.com/app:${GIT_COMMIT} --push .

Order your Dockerfile so that rarely changing steps (base image, OS packages, dependency install) come before COPY . .. Otherwise every code change invalidates the dependency layer.

8. Use ephemeral agents on Kubernetes

The Kubernetes plugin starts a pod for each build and deletes it afterwards. You get clean workspaces, per-build tool containers, and capacity that follows demand.

pipeline {
  agent {
    kubernetes {
      yaml '''
apiVersion: v1
kind: Pod
spec:
  containers:
  - name: maven
    image: maven:3.9-eclipse-temurin-21
    command: ["sleep"]
    args: ["infinity"]
    resources:
      requests: { cpu: "1", memory: "2Gi" }
'''
    }
  }
  stages {
    stage('Build') {
      steps { container('maven') { sh 'mvn -B package' } }
    }
  }
}

Set CPU and memory requests honestly. Under-sized pods get throttled and look like a slow pipeline. Pair ephemeral agents with tips 6 and 7, since they start with empty caches.

9. Keep builds off the controller

The Jenkins controller schedules work, stores build records, and serves the UI. Running builds on it competes with all of that. The Jenkins documentation recommends setting the built-in node (called "master" before Jenkins 2.307) to zero executors and running every build on agents. Use labels so jobs land on agents with the right tools and size.

10. Move files between stages the right way

stash and unstash copy files through the controller. They are fine for small things such as a compiled JAR or a test report, but slow for large directories. For big outputs, push to an artifact repository or object storage and pull the file in the next stage. Use archiveArtifacts only for files people need to download from the build page, and add fingerprint: true when you want to trace which build produced a file.

11. Lower pipeline durability for short builds

By default Jenkins writes pipeline state to disk often so that a build can resume after a controller restart. For short builds that can simply be re-run, the PERFORMANCE_OPTIMIZED durability setting reduces disk writes on the controller.

options { durabilityHint('PERFORMANCE_OPTIMIZED') }

The trade-off is documented on the Scaling Pipelines page: if the controller crashes mid-build, that build may not resume. Keep the default for long deployments where resuming matters.

12. Write lean Groovy and use shared libraries

Pipeline Groovy runs on the controller in a special interpreter (CPS) that serialises state. Loops over large lists, JSON parsing, and string manipulation in Groovy are slow and load the controller. The official Pipeline best practices page advises using Groovy as glue and doing real work in sh or bat steps, which run on the agent.

Shared libraries keep common steps in one versioned place so that every team does not copy a slightly different, slightly slower Jenkinsfile. Pin library versions with @Library('[email protected]') _ so a library change does not surprise every pipeline at once. Our Jenkins best practices guide covers library design in more depth.

13. Stop runaway and stale builds

A hung test that runs for six hours holds an executor the whole time. A pile of old builds fills the controller disk. These options are cheap insurance:

options {
  timeout(time: 30, unit: 'MINUTES')
  disableConcurrentBuilds(abortPrevious: true)
  buildDiscarder(logRotator(numToKeepStr: '30', artifactNumToKeepStr: '5'))
}

abortPrevious: true cancels the older run on a branch when a newer commit arrives, which is useful for pull request builds where only the latest commit matters. Check that your installed Pipeline plugin version supports it.

14. Split long test suites across agents

When a single test stage dominates the build, split it. The Parallel Test Executor plugin uses test timings from previous builds to divide tests into roughly equal groups with splitTests, then you run each group in a parallel branch. Many test frameworks (pytest-xdist, Gradle's maxParallelForks, Jest workers) can also parallelise inside one agent if it has spare cores.

Build-tool settings that make a difference

Jenkins only orchestrates. Much of the build time sits inside Maven, Gradle or npm, and each has its own switches.

ToolSettingEffect
Mavenmvn -B -T 1C verify-B runs in batch mode with less log noise; -T 1C builds modules in parallel, one thread per CPU core
Maven-o (offline) on a warm cacheSkips remote repository checks when every dependency is already cached
Gradle--build-cache, --parallelReuses task outputs from earlier builds and runs independent projects at the same time
GradleRemote build cacheShares task outputs between CI agents and developer machines
npmnpm ci --prefer-offlineClean, lockfile-exact install that uses the local cache before the network
Docker.dockerignoreKeeps node_modules, .git and build output out of the build context

Test each flag on its own. Parallel module builds can expose ordering bugs in projects that were never built in parallel before, and offline mode fails loudly the first time a new dependency is added.

Putting it together: an example Jenkinsfile

The pipeline below combines several tips: options for durability and timeouts, a shallow checkout, a changeset guard, parallel checks, and a registry-cached image build. Adjust labels, paths and registry names to your setup.

pipeline {
  agent { label 'linux-docker' }
  options {
    skipDefaultCheckout()
    durabilityHint('PERFORMANCE_OPTIMIZED')
    timeout(time: 30, unit: 'MINUTES')
    buildDiscarder(logRotator(numToKeepStr: '30'))
    parallelsAlwaysFailFast()
  }
  stages {
    stage('Checkout') {
      steps {
        checkout([$class: 'GitSCM',
          branches: scm.branches,
          userRemoteConfigs: scm.userRemoteConfigs,
          extensions: [[$class: 'CloneOption', shallow: true, depth: 20, noTags: true]]])
      }
    }
    stage('Install') {
      steps { sh 'npm ci --prefer-offline' }
    }
    stage('Checks') {
      parallel {
        stage('Lint') { steps { sh 'npm run lint' } }
        stage('Unit tests') { steps { sh 'npm test -- --ci' } }
      }
    }
    stage('Image') {
      when { anyOf { branch 'main'; changeset 'Dockerfile' } }
      steps {
        sh '''
          docker buildx build \
            --cache-from type=registry,ref=registry.example.com/web:buildcache \
            --cache-to type=registry,ref=registry.example.com/web:buildcache,mode=max \
            -t registry.example.com/web:${GIT_COMMIT} --push .
        '''
      }
    }
  }
}

Here the parallel branches share one agent and workspace, so dependencies are installed once. That works when both branches only read the workspace. If they write to the same files, give each branch its own agent and share results with stash or a cache instead.

Plan agent capacity

Parallelism moves the bottleneck from the pipeline to the agent pool. A rough way to size it:

  1. Count the maximum parallel branches in your busiest pipeline.
  2. Multiply by the number of builds you expect at the same time during peak hours (for example, after a stand-up when many pull requests land).
  3. Compare that with your total executors. If peak demand is much higher, builds will queue no matter how well each pipeline is written.

Static agents need this capacity all day. Kubernetes or cloud agents (such as the EC2 or Azure VM agent plugins) scale with demand, which is usually cheaper when load is spiky. Keep an eye on the controller too: hundreds of concurrent builds increase its memory and disk use even when the work runs elsewhere.

How to tell whether a change worked

Track a few numbers per pipeline before and after each change:

  • Median and 90th percentile build duration, not the single best run.
  • Median queue time.
  • Duration of the slowest stage.
  • Cache hit rate, if your cache tool reports it.
  • Failure rate, to make sure speed did not come from skipping something that mattered.

Looking at the 90th percentile matters because slow outliers (cold caches, busy agents) are what developers remember. A change that improves the median but makes the tail worse is not a win.

Common mistakes that cancel out the gains

  • Adding parallel branches without adding agents, so branches queue.
  • Caching a directory that changes on every build, which costs upload time and saves nothing.
  • Running npm ci or mvn install in every parallel branch instead of once, then sharing the result.
  • Installing tools at runtime with apt-get or curl instead of baking them into the agent image.
  • Letting plugin count grow unchecked. Each plugin adds load and upgrade risk; review them with our list of useful Jenkins plugins.

When a pipeline fails rather than just runs slowly, our guide to common CI/CD pipeline failures and fixes is the next stop.

A sensible order to apply these tips

  1. Measure (tip 1) and fix queue time first.
  2. Move builds off the controller and add timeouts (tips 9 and 13).
  3. Cut repeat work: shallow clone, changeset, caches (tips 4 to 7).
  4. Parallelise once you have the agent capacity (tips 2, 3, 8, 14).
  5. Tune the controller last (tips 10 to 12).

Re-measure after each change. If a tip does not move the number, revert it and keep the pipeline simpler.

FAQ

What is the fastest way to speed up a Jenkins pipeline?

Run independent stages in parallel and cache dependencies. Those two changes usually give the largest drop in wall-clock time, as long as you have enough agents to run branches at the same time.

Does parallel always make Jenkins builds faster?

No. Parallel branches need free executors. If all branches wait for the same agent, they run one by one and the build can even get slower because of extra setup in each branch.

How do I cache dependencies in Jenkins?

Use the Job Cacher plugin to save and restore folders like ~/.m2 or node_modules, mount a persistent volume on Kubernetes agents, or point builds at a local Nexus or Artifactory proxy.

Should builds run on the Jenkins controller?

No. Jenkins recommends zero executors on the built-in node. Run builds on agents so the controller can focus on scheduling, storing build history, and serving the UI.

What does durabilityHint PERFORMANCE_OPTIMIZED do?

It reduces how often Jenkins writes pipeline state to disk, which lowers controller I/O. The cost is that a build may not resume if the controller restarts during the run.

How do I skip stages when files have not changed?

Use when { changeset 'path/**' } on the stage. It runs only if the commit touched matching files. Decide how to handle the first build of a branch, where the changeset can be empty.

Are Kubernetes agents faster than static agents?

They reduce queue time and give clean workspaces, but each pod starts with empty caches. Add a dependency cache and a Docker registry cache to get the speed benefit.

Learn Jenkins hands-on

If you want to practise these patterns on real pipelines, our Jenkins training runs in our Kharadi, Pune classroom and live online. For interview preparation, see 100+ Jenkins interview questions.

References

What's Your Reaction?

Like Like 0
Dislike Dislike 0
Love Love 0
Funny Funny 0
Angry Angry 0
Sad Sad 0
Wow Wow 0
Mridul I am a passionate technology enthusiast with a strong focus on DevOps, Cloud Computing, and Cybersecurity. Through my blogs at DevOps Training Institute, I aim to simplify complex concepts and share practical insights for learners and professionals. My goal is to empower readers with knowledge, hands-on tips, and industry best practices to stay ahead in the ever-evolving world of DevOps.