Advanced Pipeline Techniques: Retry, Timeout, Locks, Lazy Loading, Speed and Reliability Patterns
Reliability Steps
| Step | Use |
|---|---|
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()
}
| Option | Benefit |
|---|---|
disableConcurrentBuilds(abortPrevious: true) | Saves executors when many commits arrive quickly |
buildDiscarder | Controls disk usage on the controller |
timestamps() | Timing per log line to find slow steps |
durabilityHint | Trade 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
| Technique | How |
|---|---|
| Run in parallel | Split tests and independent stages across agents |
| Shallow clone | checkout with CloneOption(shallow: true, depth: 1) in the Git step |
| Cache dependencies | Persistent volumes, BuildKit cache, local mirrors or a repository manager |
| Build only what changed | when { changeset 'service-a/**' } in monorepos |
| Fail fast | Cheap checks (lint, unit tests) before expensive ones |
| Smaller images | Faster agent start. Pre-pull common images on agents |
| Avoid the controller | Run builds on agents. Keep the controller for orchestration (agent none at top) |
| Reduce log noise | Quiet 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.
| Gotcha | Advice |
|---|---|
| Heavy loops or large data in Groovy are slow | Do 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 pauses | Keep 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 code | Prefer a plain for loop for step calls |
| Scripts getting very long | Move 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
- Detect: record failures per test over time (the Test Results Analyzer or your test platform)
- Quarantine: move a flaky test to a separate, non-blocking job so it does not stop the team
- Fix the root cause: timing, shared state, external services, random data
- Retry only the failed tests (many frameworks support rerun on failure) and still report them as flaky
Practice Tasks
- Add
timeoutandretryaround a network step and observe what happens when it fails twice then succeeds - Use
waitUntilto wait for a service to answer on its health URL - Add a
lockand start two builds to see the second wait - Turn on
disableConcurrentBuilds(abortPrevious: true)and push two commits quickly - 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.

