Pull Request Builder in Jenkins

Pull Request Builder in Jenkins

Test every change before it reaches your main branch. Learn how Jenkins builds pull requests automatically, reports the result back to your team, and keeps the whole process fast, safe, and reliable.

Imagine a bakery where every new recipe goes straight onto the shop shelf. Some cakes are wonderful. Some are burnt. Some contain the wrong ingredient, and customers find out only after they have eaten them. A sensible bakery bakes a small test batch first, lets a colleague taste it, and only then puts it on sale.

A pull request is a test batch for code. A developer proposes a change, teammates review it, and only then does it join the main code. A Pull Request Builder is the automatic taster: the moment a pull request appears or changes, Jenkins builds it, runs the tests, and reports “safe to merge” or “please fix” right on the pull request page.

In this guide you will learn what a pull request builder is, how Jenkins finds pull requests, how it decides what code to test, how it reports results, how to keep it secure and fast, and which mistakes cost teams the most time. We assume you know nothing about Jenkins yet, and we explain each new word the first time it appears.

1What Is a Pull Request Builder?

A pull request builder is an automatic checker that builds and tests proposed code changes before anyone merges them.

First, the basics

Jenkins is a free automation server. Teams use it to build software, test it, and deliver it. A build is one run of that automation: fetch the code, compile it, run the tests, and report the result.

Most teams keep their code in Git, a system that tracks every change. Work usually happens on a branch, a separate line of changes that does not disturb the main code. When the work is ready, the developer opens a pull request, often shortened to PR. It is a formal request that says, “please review my branch and merge it into the main branch.” On some platforms, such as GitLab, the same thing is called a merge request.

So what is the builder?

The pull request builder is the part of your Jenkins setup that notices pull requests and builds them automatically. Whenever a PR is opened, updated with new commits, or reopened, Jenkins starts a build. When it finishes, Jenkins reports the outcome back to the pull request as a green tick or a red cross.

Everyday Analogy

Think of airport security. Every passenger, no matter how important, walks through the scanner before boarding. The scanner does not decide who is allowed to fly by asking nicely. It checks. A pull request builder is the scanner between a developer’s change and the main branch of your code.

What does it give you?

  • Early warning: broken code is caught before it is merged, not after.
  • Fast feedback: the developer learns about a problem minutes after pushing, while the change is still fresh in mind.
  • Reviewer confidence: a reviewer sees a green check and can focus on design, not on wondering whether it even compiles.
  • A protected main branch: the platform can refuse to merge until the check passes.
Before merge
Problems are found while they are cheap to fix
Minutes
Feedback arrives while the change is fresh
Green or red
A clear verdict shown on the pull request itself
i
Remember

“Pull Request Builder” is a job, not one single product. It can be a classic plugin, or a modern feature of multibranch pipelines. Both are explained in this guide, along with how to choose.

2Why It Exists: The Problem and the History

Teams learned, often painfully, that testing only after merging is testing too late.

The old way

In the early days of continuous integration, developers pushed changes straight to a shared branch. Jenkins built that branch after every push. If the build failed, the whole team was blocked, everyone’s next change was built on top of the broken one, and somebody had to stop work to find out who had broken what.

The pull request workflow

Hosting platforms such as GitHub popularised pull requests around 2008 onwards. Suddenly there was a natural checkpoint: a proposal that has not been merged yet. It was the perfect place to run tests. The first Jenkins answer was a community plugin named the GitHub Pull Request Builder, often called ghprb. It watched a repository for pull requests, built each one, and posted the result as a comment and a status.

The modern way

As Jenkins moved toward Pipeline as code, a newer approach appeared: the multibranch pipeline together with a branch source plugin, such as the GitHub Branch Source plugin. Instead of one special job that reacts to pull requests, Jenkins scans the repository, finds branches and pull requests itself, and creates a pipeline for each one, using the Jenkinsfile stored in the code. The older ghprb plugin is no longer the recommended path for new setups, and many teams have migrated away from it.

Testing after merge

  • A broken main branch blocks everybody.
  • Finding the guilty change takes detective work.
  • Reverting causes noise and delays.

Testing at the pull request

  • Only the author is affected by a failure.
  • The failing change is obvious.
  • The main branch stays healthy.
Everyday Analogy

Proofreading a book after it is printed means recalling every copy. Proofreading the manuscript means changing a file. A pull request builder is proofreading at the manuscript stage.

Real-world motivation

Large open-source projects receive changes from hundreds of strangers. Without automatic checks on every proposal, maintainers would spend all day compiling other people’s code by hand. Pull request builders turn that chore into a background service, and this is why they are standard practice in both open-source and company projects today.

3Core Concepts: The Words You Must Know

A handful of ideas explain almost everything about pull request builds.

Idea

Pull request head

The latest commit on the developer’s branch. Building only the head answers, “does this branch work on its own?”

Idea

Merge result

The code you would get if the pull request were merged right now into the target branch. Building this answers the better question, “will the main branch still work after the merge?”

Idea

Target branch

The branch the change wants to join, usually main. It keeps moving as other people merge their work.

Trigger

Webhook

A small message the code host sends to Jenkins the moment something happens, such as a new pull request. It is the doorbell that wakes Jenkins.

Report

Commit status

A coloured mark that Jenkins attaches to a commit on the code host: pending, success, or failure, plus a link back to the build.

Rule

Branch protection

A setting on the code host that refuses merging until required checks pass and reviewers approve.

Safety

Trust

Jenkins must decide how far to trust the author of a pull request. Code from strangers can be dangerous to run.

Job type

Multibranch pipeline

A Jenkins job that creates one pipeline per branch and per pull request, discovered automatically from the repository.

Vocabulary table

WordMeaningExample
ForkA personal copy of a repository, often used by outside contributorsA stranger forks your project and proposes a change from the fork
CommitOne saved set of changes with a unique identifier“Fix login bug”
RefspecA rule telling Git which remote references to downloadFetch all pull request references
CheckAn automated verdict attached to a pull requestUnit tests passed
RescanJenkins re-reading the repository to find new branches and pull requestsA periodic safety net
i
Good to know

A pull request keeps existing while the developer keeps pushing new commits to the same branch. Each push creates a new head, so Jenkins may build the same pull request many times during its life.

4Architecture and Components

Four parties cooperate: the developer, the code host, the Jenkins controller, and the agents that do the work.

The players

The developer pushes commits and opens the pull request. The code host, such as GitHub, Bitbucket, or GitLab, stores the repository and shows the pull request page. The controller is the Jenkins brain: it receives notifications, decides what to build, and reports results. An agent is a worker machine or container that actually compiles and tests the code.

flowchart LR
    DEV["Developer"] -->|"Push and open PR"| HOST["Code Host"]
    HOST -->|"Webhook"| CTRL["Jenkins Controller"]
    CTRL -->|"Scan repository"| HOST
    CTRL --> Q["Build Queue"]
    Q --> AG["Agent"]
    AG -->|"Clone PR code"| HOST
    AG --> TESTS["Build and Tests"]
    TESTS --> CTRL
    CTRL -->|"Status check"| HOST
    HOST --> PRPAGE["PR Page shows green or red"]
    PRPAGE --> DEV
Fig 1. A pull request travels from developer to code host to Jenkins, and the verdict comes back to the same page

Reading the diagram

The developer pushes code and opens a pull request. The code host immediately sends a webhook to Jenkins. Jenkins may scan the repository to learn the details, then places a build in the queue. When an agent is free, it downloads the pull request code, builds it, and runs the tests. The controller collects the result and sends a status to the code host. The pull request page then shows a green tick or a red cross, and the developer sees it without leaving the page.

Everyday Analogy

Think of a school exam. A student hands in a paper (pull request). The office (code host) rings the marker (webhook). The marker (Jenkins) sends the paper to a marking room (agent), gets the score, and writes it on the front of the paper for everyone to see.

Where the settings live

With the modern approach, the pipeline steps live in a file called a Jenkinsfile inside the repository, so each pull request can carry its own changes to the pipeline. The connection details, such as which repository to watch and which credentials to use, live in the Jenkins job configuration.

5How It Works Internally

There is no magic here. Jenkins follows a short, predictable routine for every pull request.

Step one: hearing about the pull request

Jenkins learns about a pull request in one of two ways. Either the code host sends a webhook the moment something happens, or Jenkins asks the code host on a schedule, a practice called polling. Webhooks are faster and lighter. Polling is a safety net for the times when a webhook gets lost.

Step two: discovering the details

Jenkins asks the code host for facts about the pull request: its number, its title, its author, the branch it comes from, the branch it targets, and the latest commit. It records these details so the build can use them later.

Step three: choosing what code to test

A pull request has two useful versions. The head is the developer’s branch exactly as pushed. The merge result is what the target branch would look like after merging the pull request. Code hosts such as GitHub keep a special reference for the merge result and update it automatically. Jenkins can build the head, the merge result, or both. Building the merge result is usually the most honest test, because it shows what will really exist after the merge.

Step four: the checkout

The agent downloads the chosen version of the code. To do this, it asks Git for special references that the code host provides for pull requests. Ordinary branch downloads do not include them, so the job must be told to fetch them.

Step five: running the pipeline

The agent runs the steps: compile, test, analyse, package. Jenkins gives the pipeline extra information about the pull request through environment variables, which are named values available to every step, such as the pull request number and the target branch.

Step six: reporting

Jenkins sends status messages to the code host: “pending” when the build starts, then “success” or “failure” when it ends. The code host shows them next to the pull request and can use them to allow or block the merge.

Everyday Analogy

Imagine a chef judging a new dish. There are two questions. First, “does this dish taste good alone?” (the head). Second, “does it still taste good when served with the rest of tonight’s menu?” (the merge result). A careful chef asks both, and the second question catches the surprises.

!
Why this matters

A pull request that passes on its own can still break the main branch if someone else merged a conflicting change an hour earlier. Building the merge result catches this. Building only the head can miss it.

6Data Flow and Lifecycle of a Pull Request Build

Follow one pull request from the first push to the final merge and see every message that passes between the systems.

sequenceDiagram
    participant D as Developer
    participant H as Code Host
    participant J as Jenkins Controller
    participant A as Agent
    participant R as Reviewer
    D->>H: Push branch and open pull request
    H->>J: Webhook with PR details
    J->>H: Set status pending
    J->>A: Queue and start build
    A->>H: Clone PR merge result
    A->>A: Compile and run tests
    A-->>J: Result and logs
    J->>H: Set status success or failure
    H-->>D: Show check on PR page
    R->>H: Review and approve
    H->>H: Merge allowed only if checks pass
    D->>H: Push a fix
    H->>J: New webhook and new build
Fig 2. Lifecycle of a pull request that goes through one failure and one fix

The lifecycle in plain steps

1

Open

The developer opens the pull request. The code host sends a webhook to Jenkins.

2

Queue

Jenkins marks the commit as pending and places the build in the queue.

3

Build

An agent downloads the code, builds it, and runs the tests.

4

Report

Jenkins sends success or failure. The check appears on the pull request page.

5

Update

If the developer pushes more commits, the process repeats. Older builds of the same pull request become useless and can be cancelled.

6

Merge or close

After approval and green checks, the pull request merges. Jenkins later removes the finished pull request job to keep things tidy.

What happens when the target branch moves

While a pull request waits for review, other changes merge into the target branch. The pull request is now behind. Depending on your settings, Jenkins may build the pull request again when the target changes, or may leave the old result in place until the next push. Teams often require pull requests to be up to date before merging, so that the final check matches the final state.

i
Tip

Show the pull request number and target branch at the top of the build log, for example “Building PR 482 into main.” When a build fails at a late hour, this line prevents a lot of confusion.

7Approach One: The Classic GitHub Pull Request Builder Plugin

The plugin known as ghprb was the first popular answer. You will still meet it in older Jenkins installations.

How it works

You create an ordinary Jenkins job, often a freestyle job, and switch on the pull request trigger. The plugin then checks the GitHub repository on a schedule or through a webhook. When it sees a new or updated pull request, it starts your job, passes pull request details as parameters, and afterwards posts the result as a comment and a commit status.

Access lists

Because building a stranger’s code is risky, the plugin uses lists of people:

  • Admin list: people who may approve builds and manage the trigger through comments.
  • Whitelist: people whose pull requests are built automatically.
  • Organisation whitelist: everyone in a named GitHub organisation is trusted.

Pull requests from anyone else wait until a trusted person approves them with a comment such as “ok to test.” Other typical comment phrases include one to build once (“test this please”) and one to rebuild (“retest this please”).

Strengths and weaknesses

Strengths

  • Easy to understand for simple jobs.
  • Comment commands let reviewers control builds from the pull request page.
  • Works with freestyle jobs, which many teams already have.

Weaknesses

  • Configuration lives in the Jenkins job, not in the repository.
  • One job handles all pull requests, so each build overwrites shared job state.
  • It is not the recommended path for new pipelines and has seen little maintenance.
  • Only supports GitHub.
Everyday Analogy

The classic plugin is like a single security guard at the front door with a clipboard of approved visitors. It works for a small building. When the building grows to hundreds of tenants with different rules, one guard and one clipboard become a bottleneck.

!
Watch out

If you inherit a Jenkins that uses this plugin, do not panic and do not rip it out overnight. Learn how it is used, then plan a careful migration. The migration chapter later in this guide shows how.

8Approach Two: Multibranch Pipelines with a Branch Source

This is the modern, recommended way. Jenkins discovers branches and pull requests by itself and builds each one with the Jenkinsfile stored in the code.

The pieces

A multibranch pipeline is a job that manages a whole family of pipelines. Given a repository, it creates one child pipeline for every branch and, if enabled, for every pull request. A branch source plugin teaches Jenkins how to talk to a specific code host. Examples include GitHub Branch Source, Bitbucket Branch Source, and GitLab Branch Source. An organisation folder goes one level higher: it scans an entire GitHub organisation or account and creates a multibranch job for each repository that contains a Jenkinsfile.

How discovery works

Jenkins scans the repository and lists its branches and pull requests. For each one, it checks whether a Jenkinsfile exists. If so, it creates a child pipeline, named after the branch or, for pull requests, in the form “PR-” followed by the number. Scans happen when a webhook arrives, and can also happen on a timer.

Discovery settings

SettingWhat it does
Discover branchesBuilds ordinary branches in the same repository
Discover pull requests from originBuilds pull requests whose branch lives in your own repository
Discover pull requests from forksBuilds pull requests from personal copies, with a trust rule deciding how far to trust them
StrategiesChooses head, merge result, or both
Orphaned item strategyDecides how long to keep jobs for closed pull requests

Why teams prefer it

Code

Pipeline as code

The Jenkinsfile lives in the repository. A change to the pipeline is reviewed in the same pull request as the change to the application.

Isolation

One pipeline per pull request

Every pull request has its own job with its own history, so builds do not overwrite each other.

Auto

Zero manual setup per repository

With an organisation folder, a new repository with a Jenkinsfile gets builds automatically.

Support

Actively maintained

Branch source plugins are the mainstream path and support several code hosts.

Everyday Analogy

A multibranch pipeline is like a building manager who walks the halls, notices every new tenant, and opens a personal file and a personal mailbox for each one. Nobody has to fill in a registration form. The tenant just moves in, and the manager takes care of the rest.

9Choosing Between the Approaches

Both approaches work. Which one fits your team depends on where your code lives and how your builds are defined.

flowchart TD
    S["Need automatic builds for pull requests"] --> P{"Do you use Pipeline as code with a Jenkinsfile?"}
    P -->|"Yes"| M["Use multibranch pipeline with a Branch Source plugin"]
    P -->|"No, old freestyle jobs"| Q{"Can you move to a Jenkinsfile?"}
    Q -->|"Yes, plan migration"| M
    Q -->|"No, not for now"| G{"Code host is GitHub?"}
    G -->|"Yes"| C["Keep the classic plugin and plan to migrate"]
    G -->|"No"| O["Use the host specific plugin or a generic webhook trigger"]
Fig 3. A simple decision path for choosing a pull request build approach

Side by side

QuestionClassic pluginMultibranch with Branch Source
Where do steps live?In the Jenkins jobIn the Jenkinsfile in the repository
One job or many?One job for all pull requestsOne pipeline per pull request
New repository setupCreate and configure a job by handAutomatic with organisation folders
Code hostsGitHub onlyGitHub, Bitbucket, GitLab, Gitea and others
Comment commandsBuilt inAvailable through extra plugins or custom logic
Long-term outlookLegacyMainstream and maintained

A simple rule of thumb

If you are starting fresh, choose multibranch pipelines. If you have an old setup that works, keep it running while you plan a step-by-step migration. Do not begin a new project on a legacy plugin.

i
Tip

The rest of this guide focuses on the multibranch approach, because it is the one you should use today. Where the classic plugin differs, we say so.

10Webhooks, Polling, and Rescans

How quickly Jenkins learns about a pull request decides how quickly developers get feedback.

Webhooks: the doorbell

A webhook is a message that the code host sends to a web address you provide. You register a Jenkins address in the repository or organisation settings, and choose which events to send: pull request opened, updated, or closed, and pushes to branches. When one of these events occurs, the code host immediately notifies Jenkins, and the build starts within seconds.

Polling and periodic scans: the safety net

Polling means that Jenkins asks the code host, “anything new?” at fixed intervals. It is slower, and on large installations it can create heavy traffic, so most teams use it only as a backup. Webhooks can fail. A firewall may block them, Jenkins may be restarting at that moment, or the code host may have an outage. A periodic rescan, for example once every few hours, catches whatever the webhooks missed.

Webhooks

  • Builds start within seconds.
  • Very little wasted traffic.
  • Scales well to many repositories.

Webhook risks

  • Jenkins must be reachable from the code host.
  • A missed message means a missed build.
  • Extra security care is needed for the public address.

Reaching Jenkins safely

If Jenkins lives inside a private network, the code host cannot reach it directly. Teams solve this with a reverse proxy in front of Jenkins that exposes only the webhook path, or with a relay service that forwards messages into the private network. Whatever you choose, restrict the exposed address so that only the webhook endpoint is public, and use the code host’s secret feature to verify that messages really come from it.

Everyday Analogy

A doorbell tells you at once when a visitor arrives. Checking the porch every ten minutes finds the visitor eventually, but wastes effort and keeps the visitor waiting. Most homes use a doorbell, plus a habit of glancing outside now and then in case the bell is broken.

!
Watch out

Never rely on webhooks alone. A silent failure means a pull request that never gets built, and nobody notices until a reviewer asks where the check is. Always keep a periodic rescan as a backup.

11What Code Gets Tested: Head, Merge, or Both

This single setting changes what your green tick actually means.

The three choices

Option 1

Current pull request revision

Builds exactly what the developer pushed, ignoring anything new in the target branch. The result depends only on the author’s work.

Option 2

Merged with the target branch

Builds the code as it would look after merging into the latest target branch. The result predicts the state of main after the merge.

Option 3

Both

Creates two builds for each pull request, one for the head and one for the merge result. You get both answers, at double the cost.

Which should you choose?

For most teams, the merge result is the best default, because it tests what matters: the code that will really exist. The head-only choice is faster to reason about and never changes because of other people’s work, which can be helpful for very large or slow builds. Building both is useful while you learn, since a difference between the two tells you the target branch has moved in a way that affects the change.

SituationResultMeaning
Head passes, merge passesGreenSafe to merge
Head passes, merge failsRed on mergeThe change conflicts with newer work on main; update the branch
Head fails, merge failsRed on bothThe change itself is broken
Head fails, merge passesRareSomething on the target branch already fixed it; investigate

Names of the checks

When Jenkins reports both builds to GitHub, it uses two distinct check names, one for the head build and one for the merge build. You can then choose which one your branch protection rule requires. Requiring the merge check gives the strongest protection.

The moving target problem

The merge result changes whenever the target branch changes, even if the developer does nothing. A pull request that was green yesterday can turn out to be stale today. Some teams close this gap by requiring branches to be up to date before merging, and some use a merge queue, a feature of certain code hosts that tests the final combination one change at a time before it lands.

Everyday Analogy

Trying on a jacket in the shop tells you it fits you. Trying it on over your winter sweater tells you it fits you in real life. The merge result is the winter sweater test.

i
Tip

Whatever you choose, tell your team what the green tick means in one sentence. Confusion about whether a pass covers the merge is the source of many “but it passed!” arguments.

12Pull Request Information Inside the Pipeline

Jenkins hands the pipeline a set of facts about the pull request, so your steps can behave differently for pull requests than for ordinary branches.

Useful environment variables

VariableMeaning
BRANCH_NAMEFor pull requests this looks like PR-482, for ordinary builds it is the branch name
CHANGE_IDThe pull request number
CHANGE_TARGETThe branch the pull request wants to merge into
CHANGE_BRANCHThe name of the source branch
CHANGE_AUTHORThe user name of the person who opened the pull request
CHANGE_URLThe web address of the pull request page
CHANGE_TITLEThe title of the pull request

These variables exist only for builds that come from a pull request, which gives you an easy way to detect one: if CHANGE_ID has a value, this build belongs to a pull request.

Stage conditions

Declarative Pipeline lets a stage carry a condition. One common condition is changeRequest, which is true only in pull request builds. Another lets you test the target branch or the branch name. With these, you can shape the pipeline:

  • Run quick tests and static analysis on every pull request.
  • Run slow, expensive tests only on the main branch or before release.
  • Deploy only from the main branch, never from a pull request.
  • Publish artifacts, meaning built packages, only after merge.

Changed-file conditions

A pipeline can also ask which files a change touched, and skip stages that do not apply. A pull request that edits only documentation may not need the full integration test suite. This is helpful but must be used carefully, so that a path rule never silently skips an important check.

Everyday Analogy

A hospital triage nurse looks at each patient’s card before deciding which department to send them to. The card here is the set of pull request variables. The pipeline reads it and picks the right route.

!
Watch out

Do not put deploy-to-production logic where a pull request build can reach it. Guard every deployment step with a condition on the branch name, and add a second protection such as separate credentials that pull request builds cannot access.

13Reporting Results: Statuses, Checks, and Branch Protection

A build that nobody sees is a build that nobody trusts. Reporting closes the loop.

Commit statuses

The simplest report is a commit status. Jenkins sends the code host a small message: this commit, this check name, this state (pending, success, failure, or error), and a link to the build. The pull request page then shows a line such as “continuous-integration/jenkins” with a coloured icon. Clicking it opens the Jenkins build.

Rich checks

Some code hosts also support richer checks, which can show a title, a summary, annotations on specific lines of code, and details inside the pull request page itself. Jenkins can publish these through a checks plugin. Annotations are especially helpful: a failing test or a style warning can appear directly on the line that caused it, so the developer never needs to open Jenkins.

Branch protection: making checks count

A check that can be ignored will be ignored. Branch protection rules on the code host make the checks mandatory. You can require that specific checks pass, that reviewers approve, that conversations are resolved, and that the branch is up to date. Only then does the merge button turn on. Without protection, the pull request builder is only advice. With protection, it is a gate.

Report

Status

A simple coloured mark and a link. Works everywhere and is easy to require.

Report

Check with details

A richer panel with a summary and line-level notes, shown right in the pull request.

Report

Comment

A written message from Jenkins on the pull request, such as a test summary or a link to a preview site.

Rule

Required checks

Marks certain checks as mandatory, so merging is blocked until they pass.

Naming and stability

Required checks are matched by name. If you rename a check in Jenkins, the protection rule may wait forever for a check that no longer exists, and every pull request becomes unmergeable. Treat check names like a public contract. Rename only with a plan, and update the protection rules at the same time.

Everyday Analogy

A concert ticket check is only useful if the door stays shut without a ticket. A pull request builder without branch protection is a ticket booth beside an open door.

i
Tip

Report early and often. Send “pending” at the very start, so the pull request shows that a build is on its way. A silent pull request makes reviewers guess.

14Security: Trust, Forks, and Secrets

A pull request builder runs somebody else’s code on your machines. That is the most dangerous sentence in this guide.

The core risk

Building a pull request means compiling and running whatever the author wrote, including the test code and, in the modern approach, the Jenkinsfile itself. A malicious or careless author could add a step that steals passwords, mines cryptocurrency, or attacks your internal network. Any credential visible to the build is visible to the author’s code.

Trust policies

Branch source plugins let you define how far to trust pull request authors. Typical levels are:

PolicyWho is trustedRisk level
NobodyNo forks are built as trustedLowest
CollaboratorsUsers with write or admin permission on the repositoryLow
ContributorsPeople who already have merged contributionsMedium
EveryoneEvery author, including strangersHighest

Untrusted pull requests use the trusted Jenkinsfile

For an untrusted pull request, Jenkins builds the code but reads the Jenkinsfile from the target branch, not from the pull request. This stops a stranger from rewriting the pipeline to steal secrets. It does not stop tests or build scripts inside the changed code from doing harm, which is why untrusted builds should run in a strongly isolated place.

Protecting secrets

  • Give pull request builds access to as few credentials as possible, ideally none.
  • Keep deployment and publishing credentials in separate jobs or folders that pull request builds cannot use.
  • Use short-lived, narrowly scoped credentials for anything a build must reach.
  • Never print secrets to the log, and remember that a build script can print them anyway.

Isolation of the machines

Run pull request builds on disposable agents, such as fresh containers deleted after each run. Give them no route to internal databases or management networks. If a build gets compromised, the damage then ends when the container disappears.

Safer habits

  • Trust only collaborators, and review outside pull requests first.
  • Use disposable, network-limited agents.
  • Keep production credentials away from pull request builds.
  • Require approval before the first build from a new contributor.

Risky habits

  • Building every stranger’s fork automatically.
  • Reusing long-lived agents with saved credentials.
  • Exposing production secrets to all builds.
  • Giving build machines access to internal networks.
Everyday Analogy

A mail room opens envelopes from strangers in a special room with a glove box, not on the desk beside the company safe. Pull requests from strangers deserve the glove box.

15Performance and Scalability

A busy team can open dozens of pull requests an hour. The builder must keep up, or feedback turns slow and developers lose trust.

Where time and money go

Every push to a pull request may start a build. If a developer pushes ten times an hour and each build takes twenty minutes, one person alone can occupy several agents. Multiply by a team of fifty and the queue explodes.

Practical remedies

Cancel

Stop superseded builds

When a new commit arrives, the older build of the same pull request is now pointless. Configure Jenkins to abort it, so agents work only on the latest commit.

Cache

Reuse dependencies

Keep downloaded libraries in a cache shared by agents, so builds do not download the same files again and again.

Split

Parallel stages

Run independent test groups at the same time on different agents to cut waiting time.

Tier

Fast checks first

Run cheap checks such as formatting and unit tests early, so obvious mistakes fail within a minute instead of after twenty.

Scale

Elastic agents

Start extra agents automatically during busy hours, using containers or cloud machines, and remove them afterwards.

Trim

Skip what does not apply

Use changed-file rules so a documentation edit does not run the whole test universe.

Concurrency and the queue

Set sensible limits so one repository cannot take over every agent. Use labels to send heavy builds to strong machines and light builds to small ones. Watch the average time a build waits in the queue. If waiting grows longer than building, you need more capacity.

Scanning cost

Scanning a large organisation with thousands of repositories and branches can put load on both Jenkins and the code host, and can run into the host’s rate limits. Prefer webhooks over frequent scans, restrict discovery to repositories that really contain a Jenkinsfile, and stretch the periodic scan interval.

Cancel
Abort old builds when new commits arrive
Cache
Share downloaded dependencies
Parallel
Split tests across agents
Everyday Analogy

A busy restaurant kitchen does not keep cooking a dish the customer has already changed. It throws away the old ticket and starts the new one. Cancelling superseded builds is that same sensible habit.

16High Availability and Reliability

When the pull request builder fails, developers cannot merge. It deserves the care of a production service.

What can go wrong

  • Lost webhooks: a pull request never gets built.
  • Jenkins down: pending checks never finish, and merging is blocked.
  • Code host outage: Jenkins cannot download code or report results.
  • Agent shortage: builds wait in the queue for hours.
  • Flaky tests: tests that fail randomly make good code look bad.

Defences

1

Rescan as a safety net

A periodic scan finds pull requests whose webhooks were lost.

2

A manual re-run path

Give developers a clear, simple way to rebuild a pull request, for example through the Jenkins page or a comment, without asking an administrator.

3

Backups and rebuildable setup

Keep Jenkins configuration in code and back up its data, so a lost controller can be rebuilt quickly.

4

Timeouts everywhere

A build that hangs forever holds an agent and leaves a pending check. Set time limits on the whole build and on risky stages.

5

Tame flaky tests

Track tests that fail and pass on the same code. Quarantine them, fix them, or retry them in a controlled way, because trust in the check is the whole point.

A fallback plan

Decide in advance what happens when Jenkins is down for a long time. Some teams allow trusted maintainers to merge urgent fixes without the check, but only with a written record. Having the rule before the outage prevents panic decisions during it.

!
Watch out

Flaky tests are more dangerous than failing tests. A test that always fails gets fixed. A test that fails one time in ten teaches everybody to click “re-run” without reading, and soon real failures are ignored as well.

Everyday Analogy

A smoke alarm that beeps for no reason gets its battery removed. Then, when there is a real fire, nobody hears anything. Flaky tests are false alarms, and they end up disabling the whole alarm system.

17Monitoring, Logging, and Metrics

You cannot improve what you cannot see. A pull request builder produces plenty of numbers worth watching.

The numbers that matter

Time to feedback
Minutes from push to green or red
Queue wait
How long builds sit before an agent starts
Failure rate
Share of builds that fail, and why

Time to feedback is the most important measure of all. It is the total delay between a developer pushing code and learning the verdict. When it grows past about ten minutes, developers switch to other tasks, lose context, and stop caring about the result. Many teams set a target and treat a slow build like a bug.

More measures worth tracking

  • Flaky test rate: how often the same code passes and fails.
  • Rebuild count: how many times developers press re-run on the same commit. High numbers reveal instability.
  • Stage duration: which stage takes the longest, so you know where to invest.
  • Agent utilisation: whether machines are idle or overloaded.
  • Webhook delivery: whether messages from the code host are being received.
  • Scan duration and errors: how long repository scans take, and how often they hit rate limits.

Good logs

Write log lines for humans in a hurry. Begin each build by printing the pull request number, the author, the target branch, and the version of the code being tested. Mark the beginning and end of each stage. When a test fails, print a short reason near the end of the log, not buried in ten thousand lines. Use Jenkins features that gather test results into a summary page, so people find failures in one click.

Alerts

Alert the owning team when the queue grows abnormally, when scans fail repeatedly, when webhook traffic drops to zero during working hours, or when the failure rate of the main branch suddenly rises. Do not alert individual developers about their own red builds by message storm; the pull request page is already telling them.

i
Tip

Put a weekly chart of median time to feedback on a shared screen or dashboard. Teams begin to protect a number that everybody can see.

Everyday Analogy

A pizza shop tracks how long each order takes from the phone call to the doorstep. Watching only the oven time would miss the ten minutes an order waits for a driver. Time to feedback is the doorstep time for developers.

18Designing the Pull Request Pipeline

The best pull request pipeline is fast, honest, and easy to understand. It answers one question: is this change safe to merge?

Think in tiers

1

Tier one: seconds to a minute

Format checks, code style rules, and a quick compile. These catch typing mistakes almost instantly.

2

Tier two: a few minutes

Unit tests, which check small pieces of code in isolation, and static analysis, which reads code for likely bugs without running it.

3

Tier three: several minutes

Integration tests that check parts working together, dependency vulnerability scans, and packaging checks.

4

Tier four: after merge

Long end-to-end tests, performance tests, and deployment. These run on the main branch or on a schedule, not on every push.

Fail fast

Order the stages so that the cheapest checks come first and the slowest come last. A missing semicolon should fail in thirty seconds, not after fifteen minutes of compiling. Where stages do not depend on each other, run them in parallel.

Honest tests

A pull request pipeline is only useful when its verdict can be trusted. Tests must be repeatable: the same code should give the same result every time. They must not depend on the order of other tests, on the current time, or on shared external services that go down. Use fresh test data, disposable databases in containers, and fake versions of outside services.

Keep the pipeline in the repository

Store the Jenkinsfile beside the code. When a developer adds a new test type, the same pull request updates the pipeline. Reviewers see both changes together, and the pipeline always matches the code it builds.

Reuse through shared libraries

If many repositories need the same steps, keep them in a Jenkins shared library, so each repository’s Jenkinsfile stays short. A central change then improves every pull request builder at once.

CheckSpeedRuns on pull requests?
Formatting and styleVery fastAlways
Unit testsFastAlways
Static analysisFast to mediumAlways
Integration testsMediumUsually
End-to-end testsSlowOften only after merge, or on request
DeploymentVariesNever to production
Everyday Analogy

A car factory checks a part at several stations. Quick visual checks come first, because it is silly to spend an hour testing a door that has an obvious dent. Only parts that pass the cheap checks move on to the expensive ones.

19Deployment, Cloud, and Configuration as Code

A pull request builder is infrastructure. Treat its setup as code, so you can rebuild it, review it, and grow it.

Describe Jenkins in files

The Jenkins Configuration as Code plugin lets you describe the Jenkins system in a text file: security settings, credentials references, agent definitions, and even job creation. The Job DSL plugin lets you define jobs, such as the organisation folder that watches your repositories, in code. Keeping these files in source control means a lost controller can be rebuilt from the repository, and every change goes through review.

flowchart LR
    CODE["Configuration as Code Files"] --> JC["Jenkins Controller"]
    ORG["Organisation Folder Definition"] --> JC
    HOST["Code Host with Webhooks"] --> JC
    JC --> K["Elastic Container Agents"]
    K --> ISO["Isolated Network Zone"]
    K --> CACHE["Shared Dependency Cache"]
    JC --> STAT["Status and Checks back to Code Host"]
    JC --> MON["Metrics and Alerts"]
Fig 4. A pull request builder defined by code, with elastic isolated agents and monitoring

Elastic agents in the cloud

Modern setups often start a fresh container for every build, using a container platform such as Kubernetes or a cloud provider’s virtual machines. The container has the tools the build needs, does its job, and disappears. This gives three benefits: builds do not disturb each other, there are no leftover files or secrets, and capacity grows during busy hours and shrinks at night, which saves money.

Preview environments

Some teams go a step further and create a temporary running copy of the application for every pull request, called a preview environment. Reviewers can click a link in the pull request and try the change live. The environment is deleted when the pull request closes. This is powerful for web applications, but it needs careful cost controls and automatic cleanup.

Secrets in the cloud

Use a secret store or Jenkins credentials, and give pull request builds only the narrow, short-lived access they need. Prefer identities that the platform issues for a single build, rather than long-lived passwords copied into settings.

Use case: a busy Monday morning

On Monday at nine o’clock, forty developers push changes at once. The cloud platform starts forty extra containers within minutes, each builds one pull request, and by ten they are gone. The team pays only for that hour. On a fixed set of machines, the same rush would have created a two-hour queue.

20Advantages, Disadvantages, and Trade-offs

Pull request builds are one of the highest-value practices in software delivery, and they still have costs.

Advantages

  • Broken changes are caught before they reach the main branch.
  • Developers get feedback while the code is fresh in mind.
  • Reviewers can trust that the change at least builds and passes tests.
  • The main branch stays releasable at all times.
  • New contributors get instant, impartial feedback.
  • Rules such as style and security scanning apply equally to everyone.

Disadvantages

  • Every push consumes build capacity, which costs money.
  • Slow builds slow the whole team.
  • Flaky tests cause noise and mistrust.
  • Running outside code is a security risk.
  • Scanning and webhooks add operational work.
  • A green check gives false comfort if the tests are weak.

Speed versus thoroughness

ChoiceLeans toward speedLeans toward thoroughness
What runsOnly fast checksFull test suite on every push
Code testedHead onlyMerge result, or both
ForksTrust few, build fewerBuild all with strong isolation
Rebuild on target changeNeverAlways

The false comfort problem

A green tick means only that the tests you wrote did not fail. If the tests are thin, the tick tells you very little. A pull request builder is a machine for enforcing your standards, and it can enforce only the standards you have actually written down as checks. Invest as much in the quality of the tests as in the quality of the plumbing.

There is no universal answer. A small team with a fast test suite can afford full checks on every push. A large organisation with slow tests must choose carefully which checks belong before merge and which belong after.

21Design Patterns and Anti-patterns

A pattern is a solution many teams discovered independently. An anti-pattern is a trap many teams fell into.

Patterns worth copying

Pattern

Fast gate, slow follow-up

Only quick, reliable checks are required before merge. Slower checks run after merge and report through a different channel.

Pattern

Supersede and cancel

A new push cancels the older build of the same pull request, so capacity serves only the latest code.

Pattern

Disposable agents

Every build runs in a fresh container that is deleted afterwards. No leftovers, no leaks.

Pattern

Trusted Jenkinsfile for outsiders

Builds of untrusted pull requests use the pipeline from the target branch, so strangers cannot rewrite the rules.

Pattern

Required merge check

Branch protection requires the merge-result check, so the main branch is tested in its future state.

Pattern

Comment with links

Jenkins posts a summary comment with test totals and links to reports or a preview site.

Anti-patterns to avoid

ANTI-PATTERN 01Avoid
The Twenty-Minute Gate

Requiring a full, slow test suite on every push. Developers batch their changes into giant pull requests to avoid waiting, which makes reviews worse.

Better approach

Keep the required checks fast. Move slow tests after merge or run them on request.

ANTI-PATTERN 02Avoid
Secrets Open to Everyone

Making deploy keys and production passwords available to every pull request build, including those from forks.

Better approach

Separate credentials by purpose. Pull request builds get almost none. Deployment happens only from protected branches.

ANTI-PATTERN 03Avoid
The Re-Run Habit

Accepting flaky tests and telling developers to “just press build again.” Real failures then hide among false ones.

Better approach

Measure flakiness, quarantine the worst tests, and fix them on a schedule.

ANTI-PATTERN 04Avoid
Unprotected Branch

Running a builder that nobody has to obey. The main branch has no required checks, so red pull requests merge anyway.

Better approach

Turn on branch protection and make the important checks mandatory.

ANTI-PATTERN 05Avoid
Pipeline Copies Everywhere

Every repository carries its own hand-copied Jenkinsfile that slowly drifts away from the others.

Better approach

Use a shared library and a starter template so improvements reach all repositories.

22Best Practices and Common Mistakes

These are the lessons that teams usually learn the hard way. You can learn them the easy way.

Best practices

  • Use multibranch pipelines with a branch source plugin for new setups.
  • Use webhooks, and keep a periodic rescan as a safety net.
  • Test the merge result, not only the branch head.
  • Keep the required checks fast, ideally under ten minutes.
  • Cancel superseded builds to save capacity.
  • Report a pending status immediately and a final status always, even on failure or timeout.
  • Turn on branch protection so checks are mandatory.
  • Trust as few outside authors as possible, and isolate their builds.
  • Keep secrets away from pull request builds.
  • Set timeouts on builds and stages.
  • Track flaky tests and time to feedback.
  • Keep Jenkins configuration in code, so it can be rebuilt.

Common mistakes and their fixes

MistakeWhat happensFix
Relying on webhooks aloneSome pull requests are never builtAdd a periodic rescan
Forgetting to fetch pull request references in an old-style jobCheckout fails with “reference not found”Add the pull request refspec, or use a branch source plugin
Requiring a check by an old nameMerging is blocked foreverUpdate protection rules whenever check names change
Building all forks with full trustOutside code can steal secretsUse a stricter trust policy and disposable agents
Never cleaning old pull request jobsJenkins fills with dead jobsSet an orphaned item strategy to remove closed ones
Deploying from pull request buildsUnreviewed code reaches real systemsGuard deployments by branch name and separate credentials
No timeout on buildsHung builds hold agents and leave pending checksAdd global and stage time limits
Ignoring rate limitsScans fail, and statuses are not postedPrefer webhooks, reduce scan frequency, and use proper credentials for API calls
!
A classic trap

A pull request that shows “pending” forever usually means Jenkins crashed or timed out before it could send the final status. Always make sure the last step of a pipeline reports a result, even when something fails, and use timeouts so that stuck builds end.

23A Worked Example: Setting Up Pull Request Builds for a Team

Let us walk through a complete setup for a fictional team, step by step, without writing any code.

The situation

BrightCart is a company with twelve repositories on GitHub. Each has a web service written in a common language. Developers open around thirty pull requests a day. So far, testing happens by hand before merging, and twice last month a broken change reached the main branch. The team asks you to set up automatic pull request builds.

Step by step

1

Choose the approach

The team is new to Jenkins pipelines and uses GitHub, so you pick a GitHub organisation folder with the GitHub Branch Source plugin. Every repository with a Jenkinsfile will be discovered automatically.

2

Set up authentication

You create a dedicated GitHub app or a service account with the minimum permissions to read code, post statuses, and read pull requests. You store its credentials safely in Jenkins.

3

Configure discovery

You enable discovery of branches and pull requests from the same repository, and pull requests from forks with a strict trust policy that trusts only collaborators. You choose to test the merge result.

4

Register webhooks

In the GitHub organisation settings, you register a webhook to Jenkins for pull request and push events, and protect it with a shared secret. You also schedule a rescan every few hours as a safety net.

5

Design the Jenkinsfile

A short file with three tiers: quick style check, unit tests, and a dependency scan. Deployment stages are guarded so they run only on the main branch.

6

Prepare the agents

You define disposable container agents with the language toolchain installed. They have no access to production networks and only a read-only dependency cache.

7

Turn on protection

In GitHub, you enable branch protection on main: the Jenkins merge check is required, one reviewer must approve, and branches must be up to date.

8

Pilot, then expand

Two friendly repositories go first. After a week of good results, all twelve repositories get the same setup.

The result after one month

MeasureBeforeAfter
Broken changes reaching mainTwo per monthNone
Time to know if a change worksManual, hours to daysAbout eight minutes
Reviewer effort on basic mistakesHighLow, since the machine catches them
Setup for a new repositoryA day of workAdd a Jenkinsfile
i
Lesson

The team began with two repositories and a small pipeline. It measured, fixed what hurt, and only then expanded. A staged rollout is kinder to developers and to the Jenkins servers.

24Migrating from the Classic Plugin

Many teams still run pull request builds through the older plugin. Here is how to move to multibranch pipelines without disruption.

What is different

The classic plugin keeps its configuration in a Jenkins job and stores build steps there too. Multibranch pipelines keep the steps in a Jenkinsfile in the repository and create a separate pipeline for every pull request. The move therefore has two parts: turning job steps into a Jenkinsfile, and replacing the trigger with automatic discovery.

A safe migration path

1

Write down what the old job does

List every build step, parameter, environment setting, credential, and notification. Include hidden behaviour that only a few people remember.

2

Create the Jenkinsfile

Translate the steps into a pipeline file in a branch of the repository. Keep behaviour identical at first, and improve later.

3

Run both side by side

Create the multibranch job while the old job still runs. Compare their verdicts on real pull requests, using a different check name for the new job.

4

Recreate the trust rules

Map the old admin list and whitelist to a trust policy. Decide how outside contributors should be treated, and write the decision down.

5

Provide replacements for comment commands

If people relied on comments such as “retest this please,” offer a clear replacement, such as a rebuild button in the pull request check or a documented way to trigger a rebuild.

6

Switch the required check

Change branch protection to require the new check, and remove the old one. Announce the date to the team.

7

Retire the old job

Disable it first, keep it for a short safety period, and delete it later.

!
Watch out

The most common migration mistake is forgetting to update the required check name in branch protection. If the old check is still required and the old job is gone, no pull request can merge. Plan the switch carefully and do it at a quiet time.

The reward

After migration, pipeline changes are reviewed with the code, each pull request has its own build history, new repositories join automatically, and the setup uses actively maintained plugins.

25Team Agreements: Living with the Builder

A pull request builder is a tool, but it works best when the team agrees on how to use it.

Agree on what green means

Write a short sentence, such as: “A green check means the merged code compiles, passes unit and integration tests, and has no new security warnings.” Put it in the contributing guide so that everyone shares one understanding.

Agree on time

Set a target for time to feedback, for example under ten minutes for required checks. When builds exceed it, treat the slowdown as a problem worth fixing, just like a bug.

Agree on red builds

  • The author owns a red pull request and fixes it or asks for help quickly.
  • Reviewers do not review pull requests with failing checks, except to help diagnose.
  • Nobody merges around a red check without a written reason and a second person’s approval.
  • A broken main branch is fixed or reverted first, before any other work.

Agree on flaky tests

Decide how a flaky test is reported, who owns fixing it, and how long it may stay quarantined. A shared list of flaky tests with owners prevents them from being forgotten.

Agree on outside contributors

Decide who reviews pull requests from strangers, how they are approved to build, and what extra checks apply. Write this down publicly if your project is open source, so contributors know what to expect.

Rule

Small pull requests

Small changes build faster, review faster, and break less. Encourage them.

Rule

Rebuild responsibly

Re-run only after checking why a build failed. Blind re-runs waste capacity and hide problems.

Rule

Keep the pipeline healthy

Treat changes to the Jenkinsfile like code: reviewed, tested, and documented.

Rule

Own the platform

A named team owns Jenkins, answers questions, and tracks the numbers that matter.

Everyday Analogy

A traffic light works only when drivers agree that red means stop. A pull request builder works only when the team agrees that red means “fix it first.” The technology tells you the colour; the culture gives it meaning.

26Real-World and Industry Examples

These scenarios show how organisations use pull request builders. They are illustrative, so you can map them to your own situation.

Scenario: the open-source project with strangers

A popular open-source project receives pull requests from hundreds of contributors. Maintainers configure the builder to build only after a maintainer approves a first-time contributor. Trusted contributors build automatically. All builds use disposable agents with no secrets. Maintainers spend their time reviewing ideas instead of compiling code by hand.

Scenario: the company with a hundred services

A large company keeps one Jenkinsfile template in a shared library and uses an organisation folder. When a team creates a new repository from a template, pull request builds start working on the first commit. The platform team can add a new security check for everybody by releasing a new library version.

Scenario: preview environments for a web team

A web team’s pipeline deploys each pull request to a temporary environment and posts a link in a comment. Designers and product managers click the link and try the change before it merges. When the pull request closes, the environment is removed automatically. Feedback arrives before the change reaches customers.

Scenario: the regulated industry

A financial company must show that every change was reviewed and tested. Branch protection requires a green Jenkins check plus two approvals. Jenkins stores build logs and test reports for years, and the pull request history becomes the audit trail. Auditors examine one workflow instead of many.

Scenario: the monorepo

A company keeps many services in one large repository. The pull request pipeline looks at which folders changed and builds and tests only the affected services. A change to the payment service does not run the tests for the search service, and feedback stays fast even as the repository grows.

What these examples share

In each case, the pull request builder is part of a wider agreement: automatic checks, mandatory protection, careful trust, and quick feedback. The tool is important, but the habits around it are what produce a healthy main branch.

Test the change where it is cheap to fix: before it merges.

27How Other CI Tools Handle Pull Request Builds

Every modern CI system offers some way to test proposals before merging. Comparing them shows what is essential.

ToolHow pull request builds workNotable difference
JenkinsMultibranch pipelines with a branch source plugin, or older trigger pluginsSelf-hosted and highly customisable; you run and secure it yourself
GitHub ActionsWorkflows triggered by pull request eventsBuilt into the code host; secrets handling for forks is a built-in feature
GitLab CI/CDPipelines for merge requestsBuilt into the same product as the repository
CircleCIPipelines triggered by pull request pushesHosted service with settings for building forks
Bitbucket PipelinesPipelines with pull request triggersIntegrated with Bitbucket

What Jenkins does differently

Jenkins does not come bundled with the code host. You connect the two through plugins, webhooks, and credentials. That gives freedom: you can choose any code host, run builds on your own machines, and shape the process however you like. The cost is responsibility for plugins, upgrades, scaling, and security. Hosted tools carry more of that burden for you.

What is universal

The lessons apply everywhere: test the merge result, keep required checks fast, mark checks as mandatory, isolate untrusted code, protect secrets, watch flaky tests, and measure time to feedback. If you learn these habits with Jenkins, you can carry them to any tool.

28Advanced Topics: Comment Commands, Monorepos, and Merge Queues

Once the basics feel comfortable, these features help larger teams.

Comment commands

Some teams like to control builds from the pull request page by typing short commands in comments, such as a request to rebuild or to run an extra test suite. The classic plugin offered this out of the box. In the modern approach, you can get similar behaviour with extra plugins or with a small service that listens to comment events and asks Jenkins to start a build. Restrict such commands to trusted people, since a comment that starts a build spends real capacity and may run untrusted code.

Monorepos

A monorepo holds many projects in one repository. Running everything for every pull request would take too long. Two common answers exist. First, use changed-file rules to run only the stages that matter for the touched folders. Second, use a build tool that understands dependencies between projects and rebuilds only the affected ones. Both need care, because a wrong rule can skip a test that should have run.

Merge queues

When many pull requests are ready at the same time, each one may be green on its own but conflict with the others once merged together. A merge queue, offered by some code hosts, lines up approved pull requests and tests each on top of the ones ahead of it before merging. Jenkins can take part by building the queue’s combined state and reporting a check. This keeps the main branch always green, at the cost of extra builds.

Required approvals before building

For public projects, a first-time contributor’s pull request can wait for a maintainer’s approval before any build starts. This costs a little time and protects capacity and secrets from abuse.

Pull request labels and skipping builds

Some teams allow labels to change behaviour: a label that requests an extra slow test suite, or a label that marks a documentation-only change. Make such rules visible and limited. If labels can skip important checks, they must be controlled by people with the right authority.

Cleaning up

Closed pull requests leave jobs and workspaces behind. Set an orphaned item strategy so old ones are removed after a number of days or after a fixed count. Also clear workspaces on agents. Without cleanup, disks fill up and Jenkins slows down.

i
Tip

Introduce advanced features one at a time, and measure their effect. A monorepo rule that saves twenty minutes is worth it. A clever label system that nobody understands is not.

29Troubleshooting Pull Request Builds

When something feels wrong, walk through these questions in order.

1

Did Jenkins hear about the pull request?

Check the webhook delivery log on the code host. Look for failed deliveries, wrong addresses, or blocked networks. If webhooks are missing, run a manual scan.

2

Was the pull request discovered?

Open the scan log of the multibranch job. Look for messages such as “no Jenkinsfile found” or “not trusted.” They explain why a pull request was skipped.

3

Is the author trusted?

For pull requests from forks, check the trust policy. Untrusted authors may need approval, or may be built with the target branch’s Jenkinsfile.

4

Is the status stuck on pending?

Check whether the build finished, timed out, or was aborted, and whether Jenkins could post the final status. Credentials or rate limits may be blocking it.

5

Does the check name match the protection rule?

A renamed check leaves the old required name waiting forever.

6

Does it fail only in Jenkins?

Compare the environment: tool versions, environment variables, and network access. Differences between a developer laptop and a clean agent explain many surprises.

7

Is it flaky?

Rebuild the same commit once. If the result differs, treat it as a flaky test and report it, rather than trusting either result.

i
Tip

Keep a short troubleshooting page for developers that explains the most common red and pending situations in plain language. It reduces support questions dramatically.

30Glossary of Terms

Every important word from this guide in one place, explained in plain language.

TermPlain meaning
AgentA worker machine or container that compiles and tests code for Jenkins.
BranchA separate line of changes that does not disturb the main code.
Branch protectionCode host rules that require checks and approvals before merging.
Branch sourceA Jenkins plugin that teaches multibranch jobs to talk to a code host.
BuildOne run of the automation: fetch, compile, test, and report.
CheckAn automated verdict attached to a pull request.
Commit statusA pending, success, or failure mark that Jenkins attaches to a commit.
ControllerThe central Jenkins server that receives events and schedules builds.
ForkA personal copy of a repository, often used by outside contributors.
Flaky testA test that sometimes passes and sometimes fails on the same code.
HeadThe latest commit on the branch of a pull request.
JenkinsfileThe text file that defines a pipeline, stored in the repository.
Merge queueA code host feature that tests approved pull requests one after another before merging.
Merge resultThe code as it would look after merging the pull request into the target branch.
MonorepoOne repository that contains many projects.
Multibranch pipelineA job that creates one pipeline per branch and per pull request.
Organisation folderA job that scans a whole account or organisation and creates multibranch jobs.
PollingRepeatedly asking the code host whether anything is new.
Preview environmentA temporary running copy of the application for one pull request.
Pull requestA formal request to review and merge a branch into another branch.
RescanJenkins re-reading a repository to find new branches and pull requests.
Target branchThe branch that a pull request wants to merge into.
Trust policyThe rule that decides which pull request authors are trusted to run builds.
WebhookA message sent by the code host to Jenkins the moment something happens.

31Frequently Asked Questions

Short answers to the questions people ask most.

Q1What is a pull request builder in one sentence?
It is the part of your Jenkins setup that automatically builds and tests every pull request and reports the result back to the pull request page.
Q2Should I use the classic plugin or multibranch pipelines?
For new setups, use multibranch pipelines with a branch source plugin. The classic plugin is legacy. Keep it only while you plan a migration.
Q3Why is my pull request not being built?
Most often the webhook did not arrive, the repository has no Jenkinsfile on that branch, or the author is not trusted. Check the webhook delivery log and the scan log, then run a manual scan.
Q4Is it better to build the head or the merge result?
The merge result usually gives the more honest answer, because it shows how the code will behave after merging. Head-only builds are simpler but can miss conflicts with newer changes on the target branch.
Q5Is it safe to build pull requests from forks?
It can be, with care. Use a strict trust policy, isolate builds on disposable agents with no secrets, and let untrusted pull requests use the target branch’s Jenkinsfile.
Q6Why does my pull request show pending forever?
Jenkins probably could not post the final status. The build may have timed out, crashed, or hit a credentials or rate-limit problem. Add timeouts and make sure the final report always runs.
Q7How do I make the check mandatory?
Use branch protection on the code host and mark the Jenkins check as required. Then the merge button stays disabled until the check passes.
Q8How do I rerun a build?
Use the rebuild option on the Jenkins page for that pull request, push a new commit, or use whatever comment-based command your team has set up. Always look at why it failed before re-running.
Q9How can I make pull request builds faster?
Cancel superseded builds, cache dependencies, run tests in parallel, put cheap checks first, and skip stages that do not apply to the changed files.
Q10Should pull request builds deploy anything?
Never to production. Preview environments for reviewers are fine if they are isolated and cleaned up. Real deployments should run only from protected branches.
Q11What environment variable tells me a build is a pull request?
The variable named CHANGE_ID holds the pull request number and exists only for pull request builds. The branch name also looks like PR followed by a dash and the number.
Q12Do I still need periodic scans if I have webhooks?
Yes. Webhooks can be lost during outages or network problems. A periodic scan is a cheap safety net that finds anything missed.

32Summary and Key Takeaways

A pull request builder turns code review from a hopeful process into a checked one.

You started with a bakery that put untested cakes on the shelf and finished with a full tasting process. Along the way you learned how Jenkins discovers pull requests, decides which code to test, reports the result, protects itself from untrusted code, scales with demand, and stays reliable. The main rules are simple: use multibranch pipelines, test the merge result, keep the required checks fast, make them mandatory, isolate untrusted builds, and watch time to feedback.

Key Takeaways

  • A pull request builder tests changes before they merge. It builds each pull request automatically and reports green or red on the pull request page.
  • Choose multibranch pipelines for new setups. A branch source plugin discovers pull requests and uses the Jenkinsfile from the repository. The classic plugin is legacy.
  • Test the merge result. It shows what the main branch will really look like after the merge.
  • Make checks count. Branch protection with required checks turns the builder from advice into a gate.
  • Treat outside code as dangerous. Use strict trust policies, disposable agents, and no production secrets in pull request builds.
  • Keep feedback fast and trustworthy. Cancel old builds, cache, parallelise, and fix flaky tests before people learn to ignore red.
  • Use webhooks with a rescan safety net, keep Jenkins configuration in code, and measure time to feedback.