A slow Jenkins costs far more than it seems: every extra minute on a PR is multiplied by every PR from every developer, and a controller that is slow to respond makes people stop looking at their results. In Scaling Jenkins you saw how to add capacity (more agents, bigger or split controllers); this lesson is about the opposite: doing more with the same capacity. You will learn to measure where the time goes before touching anything, to tune the controller (JVM, disk, plugins, retention and logs), to write pipelines that do not punish the controller, to speed up builds with caches, parallelism and prebuilt images, and to cut agent startup time. You will apply all of it in a case study: the orders-api pipeline, which, after the security scans and the pods of module 8, no longer comfortably meets its feedback target.
Measure Before Optimizing
The rule of all optimization: do not optimize what you have not measured. Intuition is often wrong: the stage that "looks" slow may not be the one that weighs the most, and the time a PR takes may be spent in the queue and not in any stage at all.
You already have the data sources:
| Question | Source | Lesson |
|---|---|---|
| How long does a build wait before it starts? | queueDurationMillis from wfapi, jenkins_job_queuing_duration |
07-02, 05-05 |
| How long does each stage take in a specific build? | Pipeline Graph View | 02-06 |
| How does the average duration per stage evolve? | Stage View (Average stage times), wfapi |
07-02 |
| Is the controller saturated? | Heap after GC, CPU, disk I/O | 05-05, 08-05 |
| What is the controller busy with right now? | Thread dumps | 09-02 |
Average Duration per Stage with wfapi/runs
wfapi/describe (07-02) describes one build; wfapi/runs returns a job's most recent builds (about ten by default) with their stages. With jq, you get an average per stage, sorted from highest to lowest:
# JENKINS_URL, JENKINS_USER_ID and JENKINS_API_TOKEN variables from 03-06 (fictitious values)
curl -s -u "$JENKINS_USER_ID:$JENKINS_API_TOKEN" \
"$JENKINS_URL/job/orders-api/job/main/wfapi/runs" \
| jq -r '[ .[] | select(.status == "SUCCESS") | .stages[] | {stage: .name, ms: .durationMillis} ]
| group_by(.stage)
| map({stage: .[0].stage, avg: ((map(.ms) | add / length) / 1000 | floor), builds: length})
| sort_by(-.avg)[]
| "\(.avg) s\t\(.builds) builds\t\(.stage)"'select(.status == "SUCCESS"): green builds only; a build that fails inBuildsays nothing about how longImagetakes..stages[] | {stage, ms}: one entry per stage and build.group_by(.stage)andmap(...): groups by stage name and calculates the average in seconds. It works because stage names are stable (04-07): with dynamic names, this analysis would be impossible.sort_by(-.avg): from highest to lowest. The first line is the candidate for optimization.- A limitation you already know: Stage View does a poor job of representing parallel branches; depending on the version, you will see
Checkswith the duration of its slowest branch. The details of each branch are in Pipeline Graph View.
Trends in Prometheus
For the platform as a whole, the dashboard from 05-05 already calculates the average duration per job. To track the feedback target, what matters is the duration of PRs and how it evolves:
# Average duration (minutes) of orders-api builds over the last week, per branch or PR
sum by (jenkins_job) (rate(default_jenkins_builds_duration_milliseconds_summary_sum{jenkins_job=~"orders-api/.*"}[7d]))
/
sum by (jenkins_job) (rate(default_jenkins_builds_duration_milliseconds_summary_count{jenkins_job=~"orders-api/.*"}[7d]))
/ 60000- It is the summary average formula from 05-05, with a 7-day window and a regular expression filter (
=~) that includesmainand thePR-Njobs. / 60000: from milliseconds to minutes.- Check in
/prometheus/which metrics your version of the plugin exports: some versions can also publish the duration per stage if it is enabled in their configuration.
And one discipline: record the baseline before every change and measure afterwards with the same method and a reasonable number of builds. An improvement that does not show up in the average of twenty builds probably does not exist.
The Controller: The JVM
The controller is a Java process. The basic memory decisions (setting -Xms/-Xmx to the same value, leaving headroom in the container) are in 08-05. Here come the finer adjustments, which have to be stated with caution: they depend on the Java version, and the Jenkins documentation maintains JVM recommendations that are worth checking for yours.
Heap Size
- Neither too small nor oversized: the ideal heap is one that, after collections, stays between half and two thirds used at peak hours. If usage stays above 80-85% after each GC, there is not enough memory; if it never goes above 30%, there is too much (and a large heap has more expensive collections).
- Measure after GC, not at any random moment: heap usage rises and falls like a sawtooth; what matters is the floor after each collection.
The Collector: G1 and Its Logs
Modern JVMs use G1 as the default collector, and it is the one the Jenkins community recommends for the controller. It is rarely worth changing it or tuning its internal parameters; what is worth it is seeing what it does, with GC logs:
jenkins-controller:
# ... image, secrets, volumes and networks as in 08-03 ...
environment:
JAVA_OPTS: >-
-Djenkins.install.runSetupWizard=false
-Xms2g -Xmx2g
-XX:+AlwaysPreTouch
-XX:+HeapDumpOnOutOfMemoryError
-XX:HeapDumpPath=/var/jenkins_home/diagnostics
-Xlog:gc*:file=/var/jenkins_home/logs/gc.log:time,uptime,level,tags:filecount=5,filesize=20M
mem_limit: 3gEach option:
| Option | What it does | When to use it |
|---|---|---|
-Djenkins.install.runSetupWizard=false |
Disables the setup wizard | Always with JCasC; remember that JAVA_OPTS replaces the image's own (08-03) |
-Xms2g -Xmx2g |
A fixed 2 GB heap | Size it according to your metrics |
-XX:+AlwaysPreTouch |
Physically reserves all of the heap memory at startup | Avoids pauses as memory gets used; startup takes a little longer. Useful with -Xms equal to -Xmx |
-XX:+HeapDumpOnOutOfMemoryError and -XX:HeapDumpPath |
If the heap runs out, writes a heap dump for analysis | Always recommended. The directory must exist and have at least as much free space as the heap |
-Xlog:gc*:file=... |
GC logs (modern Java unified logging syntax), rotated across 5 files of 20 MB | Always recommended: minimal cost, and without them you cannot diagnose pauses |
- Do not add options copied from old articles: many JVM guides were written for Java versions in which the default collector was a different one; some options no longer exist and the JVM will refuse to start, and others make performance worse with G1. Only add an option if you know which measured problem it solves.
- A warning about heap dumps: a controller heap dump contains the process memory, including decrypted credentials. Treat it as a secret: restricted permissions, never in a support bundle or a public issue, and delete it after the analysis.
- With Helm (08-02), the same goes in
controller.javaOpts.
Reading the GC Logs
What you are looking for in gc.log:
- Long pauses (
Pause Young,Pause Full) of more than a second, especially if they are frequent: the interface freezes while they last. - Repeated
Pause Fullentries: the heap is at its limit and G1 is falling back to full collections. This is the clearest sign of a lack of memory or of a leak. - The usage after each collection, which gives you the floor discussed in the previous section.
GC log analysis tools (there are several, both free and commercial) turn the file into charts of pauses and occupancy; for a first look, grep "Pause Full" gc.log | tail is enough.
The Controller: Disk, Plugins, Interface, Retention and Logs
JENKINS_HOME on a Fast Disk
Jenkins performs a huge number of small writes: every pipeline step, every log line, every build.xml. Disk latency matters more than its capacity:
- A local SSD or low-latency block storage for
JENKINS_HOME. A slow network file system shows in the interface, at startup and in every build (08-05). - Nothing else on that disk: no builds on the controller (0 executors), no intermediate backups, no logs from other services.
- A red flag in thread dumps: many threads waiting on file operations (
FileOutputStream,fsync).
Fewer Plugins
Each plugin adds classes to load, extensions that run on every page or in every build, and sometimes periodic tasks. The plugin governance from 09-01 is also a performance measure: a controller with 80 plugins starts and responds faster than one with 250. When a thread dump repeatedly shows a specific plugin in the busy threads, you have a candidate to upgrade, configure better or remove.
Heavy Views and Pages
Some pages force the controller to load many builds from disk:
| Page or element | Why it is heavy | Alternative |
|---|---|---|
| The All view with hundreds of jobs | It calculates status and indicators for all of them | Views filtered by regular expression, such as TecnoShop (02-01) |
| Indicator columns (weather, last success, last failure, duration) | They can force the last builds of every job to be loaded | Few columns in views with many jobs |
| Very long build histories | More builds to load when opening the job | Retention (next section) |
| Consoles of several MB in the browser | The controller serves them in full | Shorter logs; the full console only when needed (Full Log) |
| Heavy alternative interfaces | Expensive queries to the internal API | Pipeline Graph View instead of Blue Ocean (02-01) |
Scripts that query the API with depth |
They walk the whole object tree | tree with just the fields needed (08-04) |
Build and Artifact Retention
The policy from 09-01 is also an optimization: fewer retained builds means less disk, faster backups, less data to load and faster startup. Two refinements:
- Artifacts outside
JENKINS_HOME: TecnoShop already publishes what matters to Nexus and archives only the last 5 in Jenkins. If an organization needs to archive large artifacts in Jenkins, there are external artifact managers: the Artifact Manager on S3 plugin, for example, makesarchiveArtifactsandstashstore data in S3-compatible object storage instead of on the controller disk, with the transfer going directly from the agent to the storage. It is an option to consider when artifacts are large and numerous; TecnoShop does not need it. - Small stashes: a
stashgoes through the controller (unless there is an external manager).stash name: 'jar', includes: 'target/*.jar'is correct;stash includes: '**'is an anti-pattern (04-07).
Log Size
Every console line is written to the controller disk and transmitted over the connection with the agent:
- Less verbose builds:
MAVEN_ARGS='-B -ntp'(no progress bars or download traces) since 04-03; the--quietor--no-progressoptions of the tools that have them. - No permanent
set -xand noenv | sortin every build: they are debugging tools (03-06). - Reports to files, not to the console: Dependency-Check, Trivy or gitleaks reports are archived; only the summary goes to the console.
Pipelines That Do Not Punish the Controller
Minimal Groovy: CPS Has a Cost
A pipeline's Groovy code runs on the controller, transformed by CPS, which saves the program's state at every step (03-02, 04-07). That Groovy is much slower than regular Groovy, and all of it competes with the other builds for the controller's CPU. The performance rule is the same as the maintenance rule: orchestrate in Groovy, do the work on the agent.
Fewer Steps and Less Noise
Every pipeline step creates execution nodes that are saved to disk and shown in the views. A pipeline with thousands of steps is slow to run, to save and to display.
// ANTI-PATTERN: one sh per file (hundreds of steps, each one with its own process and log entry)
script {
def files = findFiles(glob: 'reports/*.json')
for (f in files) {
sh "jq '.summary' ${f.path} >> summary.txt"
}
}
// BETTER: a single sh; the shell on the agent does the loop
sh label: 'Summarize reports', script: '''
for f in reports/*.json; do
jq '.summary' "$f"
done > summary.txt
'''- In the first block, each
shstarts a process on the agent, creates a temporary script in@tmp, logs its output separately and adds nodes to the execution. With 300 files, that is 300 steps and several minutes of overhead. On top of that, it interpolates${f.path}into the shell, which is a risk with unexpected file names. - In the second, there is a single step: the shell walks through the files at native speed and the pipeline is still readable. Quoting
"$f"protects against spaces in the names. - The same idea applies to
echoinside loops and toretry/waitUntilwith very short intervals.
Reading JSON and YAML: readJSON and readYaml
When the pipeline needs one value from a file (for example, the version in package.json in catalog-web), parsing it by hand in Groovy (with JsonSlurper or with regular expressions) is slow because of CPS, usually requires script approvals and produces objects that cause NotSerializableException (09-02). The Pipeline Utility Steps plugin offers steps for this:
readJSON file: ...: reads the file from the workspace and returns an object you can use to access its fields. There isreadYamlfor YAML (for example, to read a field fromci/pod-ci.yamlor from a manifest ink8s/).- The parsing is done by the plugin's compiled code, not by Groovy interpreted through CPS, and the result is serializable.
- A note on this: the step still runs on the controller (it reads the file from the agent and processes it there). For large files (reports with thousands of lines), the minimal Groovy rule wins: process them on the agent with
jqoryqand return only the value you need withsh(returnStdout: true). - Check that the plugin is in
plugins.txtbefore using its steps; if it is not, follow the onboarding process from 09-01.
durabilityHint, with Judgment
In 04-07 you learned about the three durability levels. As a performance lever:
PERFORMANCE_OPTIMIZEDgreatly reduces the controller's disk writes for each step. The benefit is real when the controller disk is the bottleneck, with many simultaneous builds of pipelines with many steps.- The cost: if the controller goes down abruptly, those pipelines do not resume.
- The criterion: measure it. If the dumps and the I/O metrics do not point to the disk, the gain will be a matter of seconds and is not worth the risk. If it is adopted, it should be for repeatable builds with no external effects (PRs), never for pipelines that deploy or wait for approvals. The installation's default value is in Manage Jenkins → System, in the pipeline speed and durability section; each pipeline's value goes in its
options.
Checkout: Only What Is Needed
| Technique | What it does | When to use it | Precautions |
|---|---|---|---|
| Lightweight checkout | The controller reads only the Jenkinsfile through the provider's API, without cloning |
Always in Pipeline script from SCM (03-01); in multibranch with GitHub Branch Source the API is used by default | Some configurations (for example, certain behaviors or submodules) force a full checkout |
skipDefaultCheckout + selective checkout scm |
Avoids the implicit checkout on every agent; each stage clones only if it needs to | Pipelines with several stages on different agents, such as ci/Jenkinsfile.cd, which only clones in Fetch release and distributes with stash |
A stage that needs the code and does not have it will fail clearly |
Shallow clone (depth: 1) |
Downloads only the latest commit | Repositories with a very large history | Breaks anything that needs history: the authorship information (blame) that SonarQube uses for new code, the gitleaks history scan, git describe |
| Sparse checkout | Only certain directories | Large repositories (monorepos) where each pipeline uses one part | The paths must be well defined (06-01) |
| Reference repository | Reuses the objects of a local clone as a reference | Permanent agents and large repositories | Keep the reference clone up to date; in ephemeral pods it only works if the clone is on a shared volume |
In orders-api, the repository is small and the checkout takes a few seconds: it is a good example of a technique that is not worth applying (section 9).
Faster Builds: Caches and Their Risks
Most of the time of a "cold" build usually goes into downloading: dependencies, tools, images, vulnerability databases. Caches avoid that.
| Cache | Where it lives at TecnoShop | What it avoids |
|---|---|---|
Maven repository (.m2) |
/cache/m2/repository on the cache-ci volume (08-02); MAVEN_OPTS on linux-agent-01 (05-01) |
Downloading dependencies on every build; behind it, Nexus's maven-public proxy |
| The wrapper's Maven distribution | MAVEN_USER_HOME=/cache/m2 |
./mvnw downloading Maven in every pod |
| npm cache | npm_config_cache |
Downloading packages on every npm ci (which deletes node_modules but takes advantage of the cache) |
| Dependency-Check database | Inside the Maven repository on cache-ci |
Downloading and updating the NVD |
| Trivy database | TRIVY_CACHE_DIR=/cache/trivy |
Hundreds of MB per build |
| Image layers | The build daemon (Docker) or the registry (Kaniko or BuildKit layer cache) | Rebuilding layers that do not change |
| Images of the pod's containers | Cluster nodes | Downloading maven, kaniko and linux-agent in every pod (section 8) |
The Risks of a Shared Cache
A cache speeds things up, but it introduces shared state between builds, which is exactly what ephemeral agents were meant to eliminate:
- Concurrent writes: two builds writing to the same Maven repository at the same time work almost always, but it is not guaranteed; the Dependency-Check database, on the other hand, does suffer from simultaneous updates (locks and, in the worst case, corruption).
- Cache poisoning: if a PR can write to the same cache that
mainand the releases use, a malicious PR could leave a tampered artifact in it that a later build would use without downloading it again. Mitigations: separate caches for PRs and formain/tags (or a read-only cache for PRs), and the Trust policy from 04-05 limiting who can open PRs that are built with their ownJenkinsfile. - Results that depend on the cache: a cache with an old SNAPSHOT dependency can produce a different build from the one a clean machine would produce. Releases should never depend on SNAPSHOTs, and the cache can be emptied without fear: it is an optimization, not a source of truth.
- Unlimited growth: the volume fills up with versions nobody uses. A periodic task that empties it (for example, once a month) is simpler than a selective cleanup.
The rule: a cache must be deletable at any time without anything breaking; the only effect should be that the next build is slower.
Faster Builds: Parallelism, Split Tests, Incremental Builds and Prebuilt Images
Parallelism, Used Wisely
The parallelism from 04-02 reduces the total duration if the branches are independent and there are resources for them:
- Parallelize what waits, not what competes: Dependency-Check (which waits on the network and the database) in parallel with the tests (which use CPU) is a good split. Two branches compiling at the same time in a pod with 1 reserved CPU only get in each other's way.
- The slowest branch sets the pace: optimizing a branch that is not the slowest in its
parallelblock shortens nothing. - Branches that share a workspace must not write to the same files (for example, Maven's
target/): in a pod, all the containers share the workspace. - Every parallel branch has overhead (steps, logging, sometimes an agent of its own): splitting a two-minute job into ten branches is not worth it.
Split Tests
When tests are the dominant stage, there are two levels:
- Inside Maven: Surefire can run the tests in several processes (
forkCount) or in several threads (parallelandthreadCount). It is the simplest option and is usually enough, as long as the tests are independent of each other (no shared static state, no fixed ports). - Across agents: with very large suites, the test classes are distributed among several agents in parallel branches, based on the times of previous builds (there are plugins that generate those splits). It multiplies the resources consumed and complicates the reports; it pays off with suites that take tens of minutes, not one minute.
Incremental Builds
- A single
clean:orders-apicleans inBuildand reusestarget/in the rest of the stages (07-02). Every additionalcleanrecompiles everything. - Between builds, there is no incremental compilation on ephemeral agents: the workspace is new. Tools with a build cache (for example, Gradle's build cache, local or remote) retrieve the results of tasks already run with the same inputs; Maven has extensions with a similar idea. Consider them for large, multi-module projects, knowing that they add infrastructure and one more cache to protect.
Agent Images with Preinstalled Tools
Installing tools on every build (apt-get install, downloading a binary with curl) is slow and fragile. TecnoShop solved this with tecnoshop/linux-agent:3 (gitleaks, Trivy, kubectl, crane, Docker client), built once and pinned by tag. The rule: what every build needs goes in the image; what one specific project needs goes in an additional container in its pod, with an official image and a pinned version.
Agents: Sizing and Startup
Sizing
- Ephemeral agents: one executor per agent. One pod per build is the natural unit; capacity comes from the number of pods.
- Permanent agents: executors according to resources. As a guideline, no more executors than cores available, for builds that compile; with
linux-agent-01at 2 executors, two simultaneous builds already compete for CPU and disk (05-01). - Realistic
requestsin the pods (08-02): if they are too low, the pod competes with others on the same node and takes longer; if they are too high, the pod waits inPendingfor a node with room. Tune them with the measured consumption (kubectl top pod, if the cluster has the metrics server). - JVM memory inside the container:
-XX:MaxRAMPercentagein Maven, with headroom for the test JVMs.
Pod Startup
The time from when the build enters the queue until it runs its first step in a pod is made up of: scheduling the pod, pulling the images, starting the containers and connecting the agent. The pull is usually the largest part:
| Measure | Effect | Precaution |
|---|---|---|
| Small images | Less to download and decompress | Do not sacrifice necessary tools for a few MB |
Fixed tags and imagePullPolicy: IfNotPresent |
If the image is already on the node, it is not pulled | With mutable tags (latest), IfNotPresent would use an old version: that is why you always use fixed tags |
| Few distinct images | A higher chance that they are already on the node | Reuse the same Maven image in all Java projects |
| Preloading images on the nodes | A DaemonSet, or a node image with the CI images already pulled | Keep the list in sync with the versions in use |
| A nearby registry | Pulls from the internal network (Nexus's image proxy) | Already in place at TecnoShop |
"Warm" pods (idleMinutes) |
The pod is reused for a few minutes for the next build | Loses strict isolation: a build inherits leftovers from the previous one. Only for trusted builds and with caches designed for it |
Case Study: The orders-api Pipeline
The Starting Point
At the end of module 8, orders-api builds do much more than in 07-02: Dependency-Check, gitleaks, trivy config, an image with Kaniko and a Trivy analysis, deployment to dev over SSH and to Kubernetes, all in ephemeral pods. Marta reports that some PRs take more than 12 minutes. Laura measures with wfapi/runs (twenty PR builds and twenty main builds) and gets this baseline, in the lab:
| Stage | PR (average) | main (average) |
|---|---|---|
Queue, pod, checkout and APP_VERSION |
1:50 | 1:50 |
Build |
0:40 | 0:40 |
Checks (slowest branch: Dependency analysis) |
3:10 | 3:10 |
Integration tests |
1:00 | 1:00 |
Package |
0:25 | 0:25 |
Smoke |
0:35 | 0:35 |
Image (Kaniko + Trivy) |
2:10 | 2:10 |
Quality analysis + Quality Gate |
- | 2:00 |
Publish |
- | 0:50 |
Deploy to dev |
- | 0:45 |
Deploy to Kubernetes (pilot) |
- | 1:10 |
| Total | ≈ 9:50 | ≈ 14:35 |
The PR average is right at the 10-minute target, but the 90th percentile, which is what the SLO from 09-01 sets, reaches 12:30: when a pod lands on a node without the images, or when Dependency-Check or Trivy decide to update their database, the build time shoots up. main sits close to 15 minutes on average up to dev and goes well beyond that at the 90th percentile (17:40).
Diagnosis by Stage
With the sorted table, Laura analyzes the top three candidates:
Dependency analysis(3:10): almost two thirds of the time is the incremental NVD update that every build performs on the database in the cache, and when two builds coincide, one waits for the other's lock.Image(2:10): the Kaniko build takes about 40 seconds; the rest is Trivy, which frequently downloads its database (and its configuration rules) before analyzing.- Startup (1:50): the nodes do not always have the pod's images, and the Kaniko and agent images are pulled from the registry.
The Optimizations Applied
1. Centralized vulnerability databases, updated at night. A new platform job, update-vulnerability-db (in jobs/ in jenkins-config, with a nightly cron), updates the Dependency-Check database and the Trivy database in cache-ci once. The builds use them without updating:
withCredentials([string(credentialsId: 'nvd-api-key', variable: 'NVD_API_KEY')]) {
mavenTecnoShop goals: 'dependency-check:check -DautoUpdate=false',
label: 'Known vulnerabilities (OWASP Dependency-Check, nightly database)'
}-DautoUpdate=false: the property of the Dependency-Check Maven plugin that disables updating in that build (check it in the documentation for the version you use). Only the nightly job performs the update, and it is the only one that writes to the database: the locks between builds disappear as well.- In
buildImage(tecnoshop-libv1.7.1, a compatible fix), Trivy receives the option not to update its database or its rules during the build (the exact names of those options change between Trivy versions; the library centralizes them, which is exactly what it is for). - The accepted risk: during the day, builds scan with a database up to 24 hours old. Laura accepts this because the CD scans each release's SBOM again before
staging(Vulnerability review, 07-05) and because the nightly job sends a warning to#ci-supportif it fails, so that nobody works with a days-old database without knowing it.
2. Pod startup. The CI pod's images (maven, kaniko and linux-agent) are pinned by version with imagePullPolicy: IfNotPresent in ci/pod-ci.yaml, and in TecnoShop's cluster they are preloaded on the CI nodes. Gain: from 1:50 to 0:50 on average, and above all the spikes disappear.
3. SonarQube scanner cache. On main, the analysis downloaded the components the scanner needs in every pod. With -Dsonar.userHome=/cache/sonar (on cache-ci), it only downloads them the first time: Quality analysis + Quality Gate goes from 2:00 to 1:20.
4. Unit tests in two processes. The orders-api tests are independent (no shared state or fixed ports, except for the integration tests, which run in another stage). With forkCount=2 in the Surefire configuration in pom.xml, Tests goes from 1:30 to 1:05. It is modest because the pod reserves 1 CPU; Laura does not raise the requests just for this: the autoscaler would pay the difference on every build.
The Result
| Stage | PR before | PR after | main before |
main after |
Optimization |
|---|---|---|---|---|---|
Queue, pod, checkout and APP_VERSION |
1:50 | 0:50 | 1:50 | 0:50 | 2 |
Build |
0:40 | 0:40 | 0:40 | 0:40 | - |
Checks |
3:10 | 1:10 | 3:10 | 1:10 | 1 and 4 (the slowest branch is now Dependency analysis, at 1:10; Tests, 1:05) |
Integration tests |
1:00 | 1:00 | 1:00 | 1:00 | - |
Package |
0:25 | 0:25 | 0:25 | 0:25 | - |
Smoke |
0:35 | 0:35 | 0:35 | 0:35 | - |
Image |
2:10 | 1:20 | 2:10 | 1:20 | 1 |
Quality analysis + Quality Gate |
- | - | 2:00 | 1:20 | 3 |
Publish |
- | - | 0:50 | 0:50 | - |
Deploy to dev |
- | - | 0:45 | 0:45 | - |
Deploy to Kubernetes (pilot) |
- | - | 1:10 | 1:10 | - |
| Total (average) | ≈ 9:50 | ≈ 6:00 | ≈ 14:35 | ≈ 9:55 | |
| 90th percentile | ≈ 12:30 | ≈ 7:00 | ≈ 17:40 | ≈ 11:10 |
The figures come from the lab and are only indicative, but the proportion is the usual one: the biggest gains come from no longer downloading things, not from micro-optimizing the pipeline. And the 90th percentile improves more than the average, because the spikes are eliminated.
What Was Ruled Out and Why
| Option | Estimated gain | Why not |
|---|---|---|
durabilityHint('PERFORMANCE_OPTIMIZED') on PRs |
Seconds | The controller disk is not the bottleneck (the metrics say so); it is not worth the risk (04-07) |
| Shallow clone | About 2 seconds | The repository is small, and SonarQube (authorship of new code) and the nightly gitleaks history scan need the full history |
Integration tests as a branch of Checks |
Up to 1 minute | They share target/ with the unit tests in the same workspace: a risk of race conditions when compiling the test classes. To be reconsidered if the integration tests grow |
Reading the version with readMavenPom instead of help:evaluate |
About 10 seconds | A small gain in exchange for a second way of reading the version, different from the one used by the wrapper and the library; and it adds a plugin to the onboarding process |
| Kaniko layer cache | About 15 seconds | The Dockerfile only copies the jar on top of the base image: there is little to cache, and it would be one more cache to protect |
Warm pods (idleMinutes) |
About 40 seconds | Loses the isolation between builds, which is the reason for using ephemeral pods |
Shortening the probes or the timeout of the Kubernetes deployment |
About 20 seconds | It would make the deployment less safe: the wait is the verification |
More CPU for the maven container |
Up to 1 minute | A cost on every build with autoscaling; the targets are already met |
Knowing what not to do is half of optimizing. Laura stores the table, with the figures, in docs/decisions/ in jenkins-config: six months from now, when the figures change, someone will be able to review each decision with data instead of repeating the discussion.
Common Mistakes and Tips
- Optimizing without a baseline: without the average from before, there is no way to know whether the change improved anything or whether it was just a day with less load.
- Optimizing the wrong stage: in a
parallelblock, only the slowest branch counts; and if the time goes into the queue, no faster stage will fix it. - Copying JVM options from an old article: some no longer exist and the JVM will not start; others make performance worse with G1. Only add what solves a measured problem.
- Sharing heap dumps: they contain decrypted credentials. Treat them as secrets.
- Caches that cannot be deleted: if emptying the cache breaks the builds, it is not a cache, it is a hidden dependency.
- A cache shared between PRs and releases: it opens the door to poisoning. Separate it, or make PRs read-only.
latestwithIfNotPresent: the nodes end up with an old version, a different one on each node. Always use fixed tags.- Parallelizing everything: branches that compete for the same CPU or the same files run slower and fail intermittently.
- Sacrificing security for speed: removing a scan, shortening a deployment check or disabling durability in the CD. The feedback target is met by speeding things up, not by cutting corners (07-02).
- Tip: repeat the
wfapi/runsmeasurement once a month and store it next to the capacity figures from 08-05. Pipelines degrade little by little, with every new test and every new scan; a monthly table detects it before the complaints do.
Exercises
Exercise 1. Measure your lab's baseline with the wfapi/runs script for orders-api/main and for a PR. Identify the three heaviest stages and, for each one, decide which part of the time is useful work and which part is downloading, waiting or startup. Does it match the case study?
Exercise 2. Rewrite this fragment to make it faster and safer, and explain each change:
script {
def text = readFile('target/dependency-check-report.json')
def report = new groovy.json.JsonSlurper().parseText(text)
for (dep in report.dependencies) {
if (dep.vulnerabilities) {
sh "echo 'Vulnerable: ${dep.fileName}' >> vulnerable.txt"
}
}
}Exercise 3. catalog-web takes 7 minutes on its PRs, and the catalog team proposes three measures: (a) disabling npm audit on PRs; (b) using durabilityHint('PERFORMANCE_OPTIMIZED'); (c) an npm cache shared among all builds. Evaluate each one with the criteria from this lesson and propose what you would measure before deciding.
Solutions
Solution 1. In the lab, the top three are usually Checks (because of Dependency-Check), Image, and either startup or Quality analysis on main. To separate useful work from downloading: open the console with Timestamper timestamps and look for the Dependency-Check and Trivy database update messages; compare a build run right after another one (warm caches) with the first one after emptying cache-ci or restarting the cluster (cold). For startup, kubectl describe pod shows in its events how long each Pulling image took. If the proportion matches the case study, the same measures (nightly databases, pinned and preloaded images) will give the biggest gain; if your lab has a single kind node that already has the images, startup will weigh less.
Solution 2.
sh label: 'Dependencies with vulnerabilities', script: '''
jq -r '.dependencies[] | select(.vulnerabilities != null and (.vulnerabilities | length) > 0) | .fileName' \
target/dependency-check-report.json > vulnerable.txt
echo "Dependencies with vulnerabilities: $(wc -l < vulnerable.txt)"
'''
archiveArtifacts artifacts: 'vulnerable.txt', allowEmptyArchive: trueChanges: (1) the report, which can be several MB, is no longer read and parsed on the controller with Groovy interpreted through CPS, but with jq on the agent; (2) JsonSlurper required script approval and produces maps that can cause NotSerializableException when the next step is reached; (3) a single sh instead of one per dependency: from hundreds of steps to one; (4) the Groovy interpolation of ${dep.fileName} inside the shell disappears, which was an injection risk with unexpected file names; (5) the console shows only a summary, and the details are archived. In addition, the Dependency-Check plugin that TecnoShop already uses (dependencyCheckPublisher) publishes the report and marks the build; before writing anything, check whether an existing step already covers the need.
Solution 3. (a) Disabling npm audit on PRs cuts security to gain speed, which is exactly what 07-02 advises against; first, measure how long it really takes (it is usually short: it queries a service and analyzes the lockfile) and, if it weighs a lot, speed it up with an npm proxy in Nexus instead of removing it. (b) PERFORMANCE_OPTIMIZED only helps if the controller disk is the bottleneck; measure the controller's I/O and compare the duration of a PR with and without the option over twenty builds: the likely outcome is a gain of a few seconds. (c) A shared npm cache usually is the measure with the biggest effect if most of the time goes into npm ci downloading; measure the time of npm ci with a cold and a warm cache. But it has to be designed with its risks in mind: separate for PRs and main (or read-only for PRs), deletable at any time, and with npm ci and the lockfile as the guarantee of versions. Before deciding, the per-stage table from wfapi/runs and the timestamped console of npm ci.
Conclusion
Optimizing starts with measuring: the average duration per stage with wfapi/runs, the trends in Prometheus and the baseline recorded before every change. On the controller, the JVM is tuned with caution (a heap sized by its floor after GC, G1 by default, GC logs, and heap dumps treated as secrets), JENKINS_HOME goes on a fast disk, plugins and heavy views are reduced, and retention and log size are kept under control, with large artifacts outside the controller. Pipelines do not punish the controller when they have little Groovy, few steps and little noise, when they parse with readJSON/readYaml or on the agent, and when they clone only what is needed. Builds get faster above all with caches (which must be deletable and must not be shared between PRs and releases), with parallelism between independent tasks, split tests when they pay off, and images with preinstalled tools; and agents get faster with realistic sizing and pinned, small, preloaded images. In orders-api, centralizing the vulnerability databases, speeding up pod startup and caching the scanner took PRs from almost 10 minutes on average (12:30 at the 90th percentile) to about 6, and main below 10, without removing a single control; and the table of what was ruled out is as valuable as the table of what was applied. With a mature, operable and fast platform, it is a good time to look up and compare Jenkins with the other options on the market, which is what you will do in Jenkins vs Other CI/CD Platforms.
