Advanced Pipeline Techniques: Retry, Timeout, Locks, Lazy Loading, Speed and Reliability Patterns

CI CD Pipelines with Jenkins 35 min min read Updated: Nov 17, 2026 Advanced
Advanced Pipeline Techniques: Retry, Timeout, Locks, Lazy Loading, Speed and Reliability Patterns
Advanced Topic 2 of 2

Reliability Steps

StepUse
retry(3) { ... }Retry a block that may fail for network reasons
timeout(time: 10, unit: 'MINUTES') { ... }Stop a stuck block
waitUntil { ... }Poll until a condition is true (combine with a timeout)
sleep time: 5, unit: 'SECONDS'Pause
catchError(buildResult: 'UNSTABLE', stageResult: 'FAILURE') { ... }Continue after a failure but mark the result
warnError('message') { ... }Mark UNSTABLE and continue
lock('resource') { ... }One user of a resource at a time (Lockable Resources plugin)
groovy stage('Integration') { steps { timeout(time: 15, unit: 'MINUTES') { retry(2) { sh './wait-for-db.sh && ./run-integration-tests.sh' } } } } stage('Wait for service') { steps { timeout(time: 3, unit: 'MINUTES') { waitUntil(initialRecurrencePeriod: 2000) { script { return sh(script: 'curl -fs http://localhost:8080/health', returnStatus: true) == 0 } } } } }
Retry is a bandage: Use retry for network or infrastructure problems (a registry timeout). Do not hide a real test failure by retrying it until it passes. Track and fix flaky tests.

Pipeline-Level Options

groovy options { timeout(time: 1, unit: 'HOURS') // never hang forever disableConcurrentBuilds(abortPrevious: true) // newer commit cancels older build on same branch buildDiscarder(logRotator(numToKeepStr: '30', artifactNumToKeepStr: '5')) skipDefaultCheckout(true) // choose when and how to checkout timestamps() durabilityHint('PERFORMANCE_OPTIMIZED') // fewer disk writes; ok for non-critical builds parallelsAlwaysFailFast() }
OptionBenefit
disableConcurrentBuilds(abortPrevious: true)Saves executors when many commits arrive quickly
buildDiscarderControls disk usage on the controller
timestamps()Timing per log line to find slow steps
durabilityHintTrade a little safety for speed on busy controllers

Handle Resources Safely

groovy // Only one pipeline at a time may use the shared test database lock(resource: 'test-database', inversePrecedence: true) { sh './run-db-tests.sh' } // Limit how many builds of this job use the "performance" category at once throttle(['performance']) { sh './run-load-tests.sh' } // Pick any free resource with a label lock(label: 'device-farm', quantity: 1, variable: 'DEVICE') { sh "./run-on-device.sh ${env.DEVICE}" }

Speed Up Pipelines

TechniqueHow
Run in parallelSplit tests and independent stages across agents
Shallow clonecheckout with CloneOption(shallow: true, depth: 1) in the Git step
Cache dependenciesPersistent volumes, BuildKit cache, local mirrors or a repository manager
Build only what changedwhen { changeset 'service-a/**' } in monorepos
Fail fastCheap checks (lint, unit tests) before expensive ones
Smaller imagesFaster agent start. Pre-pull common images on agents
Avoid the controllerRun builds on agents. Keep the controller for orchestration (agent none at top)
Reduce log noiseQuiet flags on tools: mvn -B -q, npm ci --silent
groovy stage('Checkout') { steps { checkout([$class: 'GitSCM', branches: [[name: env.BRANCH_NAME]], userRemoteConfigs: [[url: 'https://git.example.com/team/shop.git', credentialsId: 'git-creds']], extensions: [[$class: 'CloneOption', shallow: true, depth: 1, noTags: true, timeout: 10]]]) } } stage('Service A') { when { changeset 'service-a/**' } steps { sh 'make -C service-a test' } }

Groovy Gotchas in Pipelines

Pipeline Groovy runs in a special engine (CPS) that can pause and resume your build across restarts. This brings a few rules.

GotchaAdvice
Heavy loops or large data in Groovy are slowDo the heavy work in sh with a real tool and return a small result
Non-serializable objects (for example a Matcher, an open stream) break when the pipeline pausesKeep such objects local inside a @NonCPS method
@NonCPS methods cannot call pipeline steps (sh, echo)Use @NonCPS only for pure computation
.each { } with steps inside can misbehave in older codePrefer a plain for loop for step calls
Scripts getting very longMove logic to a shared library or real scripts in the repository
groovy @NonCPS def parseVersion(String text) { def m = (text =~ /version=(\d+\.\d+\.\d+)/) return m ? m[0][1] : null // returns a String: serializable } stage('Version') { steps { script { def props = readFile('gradle.properties') env.APP_VERSION = parseVersion(props) echo "Version: ${env.APP_VERSION}" } } }

Clean Up After Yourself

groovy post { always { junit allowEmptyResults: true, testResults: '**/target/surefire-reports/*.xml' sh 'docker compose down -v || true' cleanWs(deleteDirs: true, notFailBuild: true) } }

Flaky Test Strategy

  1. Detect: record failures per test over time (the Test Results Analyzer or your test platform)
  2. Quarantine: move a flaky test to a separate, non-blocking job so it does not stop the team
  3. Fix the root cause: timing, shared state, external services, random data
  4. Retry only the failed tests (many frameworks support rerun on failure) and still report them as flaky

Practice Tasks

  1. Add timeout and retry around a network step and observe what happens when it fails twice then succeeds
  2. Use waitUntil to wait for a service to answer on its health URL
  3. Add a lock and start two builds to see the second wait
  4. Turn on disableConcurrentBuilds(abortPrevious: true) and push two commits quickly
  5. Measure the pipeline before and after shallow clone and caching

Conclusion

Make pipelines dependable with timeouts, targeted retries, locks and safe cleanup, and fast with parallel stages, shallow clones, caching and changeset conditions. Keep Groovy light, use @NonCPS only for pure computation, and fix flaky tests instead of retrying them forever.

Quick Summary: retry/timeout/waitUntil/catchError/lock/throttle; options abortPrevious, durability; speed table; CPS and @NonCPS; cleanWs; flaky test strategy.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators