Multibranch Pipeline in Jenkins
An in-depth guide to the Jenkins job type that discovers your branches and pull requests by itself and builds each one with its own pipeline: how it works, how to set it up wisely, and how to run it safely at scale.
Imagine a busy team of twenty developers. Every day new branches appear, pull requests are opened, old work is merged and deleted. If someone had to create a Jenkins job by hand for each of these, the setup would never keep up. Jobs would be missing for new work, and dead jobs would clutter the screen for old work.
The Multibranch Pipeline removes that chore. You point Jenkins at a code repository once. From then on, Jenkins looks inside it, finds every branch and pull request that contains a pipeline file, creates a job for each, and removes the jobs when the branches disappear. The pipeline instructions live in the code itself, so every branch can carry its own version of the build.
This guide starts from zero and goes deep. Every new word is explained when it first appears, everyday pictures make the ideas easy to hold, and later chapters cover what experienced engineers care about: how scanning really works, how to handle pull requests from strangers safely, how to keep API limits and disk space under control, and how to design branch-specific behavior without creating chaos.
1What Is a Multibranch Pipeline?
A plain-language first look before any details.
Jenkins is a free, open-source automation server that builds, tests and delivers software. Its work is written as a pipeline, a recipe stored in a text file called the Jenkinsfile. A pipeline is divided into stages, such as Build, Test and Deploy, and each stage contains steps, the single actions Jenkins performs.
Developers use branches in version control, usually Git. A branch is a separate line of work: a copy of the code where someone can experiment without disturbing the main line. A pull request is a request to merge a branch into another, and it is where teammates review changes before they are accepted.
A Multibranch Pipeline is a special kind of Jenkins job. Instead of running one pipeline, it acts like a manager that watches a whole repository. For every branch, and optionally every pull request and tag, that contains a Jenkinsfile, it creates a child job and runs that branch’s own pipeline.
Think of a school principal who hires a teaching assistant for every new class that opens. When a new class starts, an assistant appears with the class’s own lesson plan. When the class ends, the assistant is sent home. The principal never fills in forms; she just watches the timetable. The Multibranch Pipeline is that principal, branches are the classes, and the Jenkinsfile in each branch is the lesson plan.
A Multibranch Pipeline does not build anything itself. It is a folder-like manager that creates and maintains many ordinary pipeline jobs, one per branch or pull request.
This idea has become the standard way to run Jenkins for modern teams. Companies with dozens or hundreds of repositories rely on it because it scales with the code, not with the number of people available to click buttons in a web page.
2Why It Exists
The problem it solves and how the idea grew.
The problem: branches come and go
In older setups, a Jenkins job was tied to one branch. A team would create a job for the main branch, maybe another for a release branch. But modern workflows create short-lived branches for every feature and fix. Teams tried copying jobs by hand, or writing scripts that called the Jenkins interface to clone jobs. These approaches broke constantly. Jobs were forgotten, settings drifted between copies, and nobody knew which jobs were still needed.
There was a deeper problem too. When the job configuration lives in the Jenkins web page, the branch cannot change its own build. If a developer adds a new test stage in a branch, the job on the server does not know about it until an administrator edits the job. Build logic and code lived in different places and fell out of step.
One job per branch, by hand
Administrators cloned jobs manually. Slow, error-prone and quickly out of date.
Scripted job creation
Helper tools generated jobs from templates. Better, but still a separate system to maintain.
Pipeline as code
Jenkins 2.0, released in 2016, made the Jenkinsfile a headline feature, so build logic could live with the code.
Multibranch Pipeline
Jenkins learned to discover branches and create jobs automatically, using each branch’s own Jenkinsfile.
Branch source plugins and organization folders
Plugins for GitHub, Bitbucket, GitLab and others added pull request discovery, and folders that scan a whole organization of repositories.
3Core Concepts You Need First
A handful of small ideas that make everything else easy.
Source control server
The place where code is stored, for example GitHub, GitLab or Bitbucket. Jenkins asks it questions such as “which branches exist?” and “what changed?”
Branch source
The Multibranch Pipeline’s connection to a repository. It holds the address of the repository, the credentials to access it, and rules about what to discover. A job can have one or several branch sources.
Behaviors
Small switches attached to a branch source that decide what to discover: branches, pull requests from the same repository, pull requests from forks, and tags. They also decide filters and how pull requests are built.
Indexing, or scanning
The act of asking the source control server for its current list of branches and pull requests, comparing it with Jenkins’ list, and creating, updating or removing child jobs. Jenkins calls this branch indexing, and shows a log of each run.
Child job
The individual pipeline job created for one branch, pull request or tag. It has its own build history, its own workspace and its own page.
Orphaned item
A child job whose branch has disappeared. Jenkins keeps it for a while according to a rule, then removes it.
| Term | Simple meaning | Why it matters |
|---|---|---|
| Branch source | Connection to a repository | Decides where Jenkins looks |
| Behavior | A discovery rule | Decides what Jenkins finds |
| Indexing | A scan of the repository | Creates and removes child jobs |
| Child job | One job per branch or pull request | Holds its own history and workspace |
| Orphaned item | A job whose branch is gone | Needs a cleanup rule |
| Jenkinsfile | The pipeline recipe in the code | Its presence makes a branch eligible |
4Architecture and Components
Which parts of a Jenkins setup work together.
A Multibranch Pipeline is made of a few cooperating pieces. There is the job itself, which behaves like a folder. There are branch source plugins that know how to talk to particular code hosting services. And there are the child jobs, which run on agents like any other pipeline.
flowchart LR
DEV["Developers push branches and open pull requests"] --> SCM["Source Control Server"]
SCM -->|"webhook event"| CTRL["Jenkins Controller"]
CTRL --> MB["Multibranch Pipeline job"]
MB --> BS["Branch Source Plugin"]
BS -->|"list branches and pull requests"| SCM
MB --> J1["Child job: main"]
MB --> J2["Child job: feature login"]
MB --> J3["Child job: PR 42"]
J1 --> AG["Build Agents"]
J2 --> AG
J3 --> AG
AG --> REP["Reports and Artifacts"]
AG -->|"status back"| SCM
Read the diagram from left to right. Developers push code, and the source control server sends a webhook, an automatic message telling Jenkins that something happened. The controller wakes the Multibranch job, which uses the branch source plugin to list the current branches and pull requests. Child jobs appear or update. Each child job runs on an agent, produces reports and artifacts, and sends its status back to the code host, so the pull request page shows a green tick or a red cross.
Controller
Runs the indexing, holds all child jobs and their history, and schedules builds.
Multibranch job
The folder-like parent. Holds branch sources, behaviors and cleanup rules.
Branch source plugin
Knows how to talk to one kind of code host and understands branches, pull requests and tags there.
Child job
An ordinary pipeline job running one branch’s Jenkinsfile.
Agents
The machines or containers where the builds really run.
Status reporting
Sends build results to the pull request so reviewers see them without opening Jenkins.
5Anatomy of the Configuration
The main sections you fill in when creating the job.
You create a Multibranch Pipeline by choosing that job type in Jenkins and giving it a name. The configuration page is short compared with older job types, because most of the real logic lives in the Jenkinsfile. The important sections, in the order they usually appear, are these.
Branch Sources
Choose the kind of repository host, give the repository or owner, and select credentials. This is where Jenkins learns where your code lives.
Behaviors
Choose what to discover: branches, pull requests, forks, tags. Add filters by name if you want only certain branches.
Build Configuration
Mode is normally “by Jenkinsfile,” and the script path defaults to a file named Jenkinsfile in the root. Change the path if your file lives elsewhere.
Scan Triggers
Optionally rescan periodically as a safety net in case a webhook is missed.
Orphaned Item Strategy
Decide how long jobs for deleted branches are kept.
Property strategies and libraries
Set optional rules for branch properties, and attach shared pipeline libraries available to every branch.
The job’s configuration page controls where to look and what to discover. What actually happens in a build is decided by the Jenkinsfile in each branch. Keep this split in mind and much confusion disappears.
Example: a small team’s first setup
A team of eight has one repository for their booking service. They create a Multibranch job, connect it to their code host with a read-only credential, enable branch and pull request discovery, keep the default script path, and set a daily safety-net rescan. Within a minute Jenkins lists eleven branches and four pull requests and starts building each of them.
6Branch Sources and Behaviors
Deciding what Jenkins should discover.
Kinds of branch sources
Plugins exist for the popular code hosts, such as GitHub, Bitbucket, GitLab and Gitea. There is also a generic Git source that works with any Git server but knows less about pull requests. Choosing the specific plugin for your host gives you richer features, especially pull request discovery and status reporting.
Behaviors in detail
Branches
Finds branches in the repository. You can choose to discover all branches, or only those that are not also pull requests, to avoid building the same code twice.
Pull requests from the same repository
Creates jobs named after the pull request number. Trusted teammates push branches in the same repository, so these are usually safe.
Pull requests from forks
Handles pull requests from copies of the repository owned by other people. Needs a trust rule to decide whose changes may run.
Tags
Creates jobs for version tags, useful for release builds. Should be used deliberately because tags can be numerous.
Filter by name
Includes or excludes branches matching a pattern, such as only main and names starting with release.
Repository and user filters
In organization folders, restrict which repositories are scanned, for example by name pattern or by whether they are archived.
Why filters matter
Without filters, every personal experiment branch becomes a job. In a large team that can mean hundreds of jobs, each consuming build time, disk space and controller memory. A simple naming convention, such as building only main, develop, release branches and pull requests, keeps the system calm and the queue short.
Prefer discovering pull requests over discovering every feature branch. The pull request is the moment a change is ready for review, so building it gives the useful signal without building every half-finished experiment.
7How Scanning Works Internally
What Jenkins does during a branch indexing run.
flowchart TD
T["Trigger: webhook, timer or manual scan"] --> L["Ask code host for branches, pull requests, tags"]
L --> F["Apply behaviors and filters"]
F --> C{"Has Jenkinsfile at script path?"}
C -->|"No"| S["Skip this item"]
C -->|"Yes"| K{"Child job exists?"}
K -->|"No"| N["Create child job and build it"]
K -->|"Yes"| U{"Revision changed?"}
U -->|"Yes"| B["Trigger a build"]
U -->|"No"| I["Leave as is"]
F --> O["Compare with existing children"]
O --> R["Mark missing ones as orphaned"]
List
Jenkins asks the code host for its current branches, pull requests and tags. This uses the host’s programming interface and counts against its request limits.
Filter
Behaviors and name filters remove anything you did not ask for.
Check for a Jenkinsfile
For each remaining item Jenkins looks for the pipeline file at the script path. Where the code host allows it, Jenkins fetches only that file rather than the whole repository, which is called a lightweight checkout.
Create or update
New items get child jobs. Items whose latest revision changed get a new build.
Orphan detection
Existing children that no longer appear in the list are marked orphaned and handled by the cleanup rule.
Log
Jenkins writes a scan log listing what it found, what it created and what it skipped. This log is the first place to look when something is missing.
An important consequence follows: a branch without a Jenkinsfile is simply invisible to Jenkins. That is by design. It lets a repository hold old branches, documentation branches or experiments that never need a build, without any special configuration.
8Triggers: Webhooks and Periodic Scans
Two ways to make Jenkins notice new work.
Jenkins does not magically know when someone pushes code. Something has to tell it, or it has to ask. There are two ways, and good setups use both.
| Method | How it works | Speed | Cost | Weakness |
|---|---|---|---|---|
| Webhook | The code host sends Jenkins a message on each push or pull request event | Seconds | Very low | Fails silently if the network blocks it |
| Periodic scan | Jenkins rescans on a timer, such as hourly or daily | Minutes to hours | Uses API requests each time | Slow and wasteful if used alone |
Webhooks first, timer as a safety net
The best practice is to rely on webhooks for speed and keep a slow periodic scan, often once a day, as a safety net. If a webhook is lost because of a network glitch or a restart, the next scan catches up. Polling every minute instead of using webhooks is a classic mistake: it wastes request quota, loads the controller, and still reacts slower.
flowchart LR
P["Push or pull request event"] --> H["Code host sends webhook"]
H --> J["Jenkins receives event"]
J --> Q["Targeted scan of that branch only"]
Q --> B["Build starts within seconds"]
T["Daily safety-net timer"] --> F["Full scan of whole repository"]
F --> B
Webhooks need the code host to reach Jenkins over the network. If Jenkins sits inside a private network, you may need a proxy or a relay. When builds start only after the timer fires, a broken webhook is the usual reason.
9The Job Tree, Names and Workspaces
How Jenkins organizes everything it creates.
flowchart TD
ORG["Jenkins root"] --> MB["Multibranch job: booking-service"]
MB --> M["main"]
MB --> D["develop"]
MB --> R["release-4.12"]
MB --> FL["feature login page"]
MB --> P1["PR-41"]
MB --> P2["PR-42"]
M --> MH["Own build history and workspace"]
P2 --> PH["Own build history and workspace"]
Names
Branches become child jobs named after the branch. Because a slash is used in web addresses, a branch called feature/login appears with its slash encoded, so the address contains a percent-two-F sequence. This surprises people who build addresses by hand. Pull requests appear as PR- followed by their number.
History
Each child keeps its own build numbers, logs, test results and artifacts. Build number 1 of one branch has nothing to do with build number 1 of another. That separation is useful: a failing feature branch never pollutes the record of the main branch.
Workspaces
Every child job gets its own workspace on the agent, named from the job path. Long branch names can create very long folder paths, which cause problems on some operating systems. Jenkins shortens the path with a hash when needed, but very long names remain a risk on machines with strict path limits.
Illustration: the long path
A team names branches after full ticket titles, giving names of more than eighty characters. Their Windows build agents start failing with “path too long” errors. A simple naming convention, ticket number plus a short word, solves the problem and also makes job pages easier to read.
10Writing a Branch-Aware Jenkinsfile
The variables and conditions that let one file behave differently per branch.
The same Jenkinsfile is usually shared by all branches, because it lives in the code and branches are copies of the code. To behave differently, the pipeline reads information that Jenkins provides about the current build.
| Variable | What it holds | Available for |
|---|---|---|
| BRANCH_NAME | Name of the branch, or PR-number for a pull request | All child jobs |
| CHANGE_ID | Number of the pull request | Pull requests only |
| CHANGE_TARGET | Branch the pull request wants to merge into | Pull requests only |
| CHANGE_BRANCH | The source branch of the pull request | Pull requests only |
| CHANGE_AUTHOR | Who opened the pull request | Pull requests only |
| CHANGE_TITLE and CHANGE_URL | Title and web address of the pull request | Pull requests only |
| TAG_NAME | Name of the tag being built | Tag builds only |
The when conditions
Declarative pipelines have a when directive that decides whether a stage runs. Three conditions are made for multibranch work: branch, which matches a branch name or pattern; changeRequest, which is true only for pull requests and can be narrowed by target or author; and tag, which matches tag names. Using them, one file can say “run the deploy stage only on main,” “run the preview stage only on pull requests,” and “run the release stage only on tags.”
Checking out the right code
Inside a multibranch child, a special variable named scm describes exactly which branch and revision Jenkins is building. A checkout step that uses it always fetches the right code. Writing a checkout with a hard-coded branch name is a frequent mistake that makes every child job build the same branch.
Let the pipeline decide by asking “what kind of build is this?” using the branch, change request and tag conditions, instead of writing different Jenkinsfiles for different branches. One file, many behaviors, is easier to keep correct.
11Pull Requests in Depth
The most valuable and most delicate part of multibranch builds.
What Jenkins actually builds
A pull request has two interesting pieces of code: the changed branch as it is, and what the target branch would look like after the merge. Building the first tells you whether the change works alone. Building the second tells you whether it works together with the latest main. Branch source plugins let you choose, commonly offering to build the merged result, the pull request head alone, or both as separate jobs.
| Strategy | What is built | Advantage | Risk |
|---|---|---|---|
| Merged with target | Pull request combined with the latest target branch | Catches conflicts and interactions early | Result changes when the target moves |
| Head only | The pull request branch alone | Stable and reproducible | May pass alone but fail after merging |
| Both | Two jobs per pull request | Most information | Double the build cost |
Pull requests from forks
A fork is a personal copy of a repository, often owned by someone outside your team. Their pull requests contain code you have not reviewed, and possibly a modified Jenkinsfile. Running that automatically with access to your servers and secrets would be dangerous.
Branch source plugins therefore offer a trust policy, which decides whose pull requests are treated as trusted. Policies range from trusting nobody, to trusting only people with write access, to trusting everyone. For untrusted pull requests, the safe approach is to use the Jenkinsfile from the target branch, not from the pull request, so the outsider cannot change the build recipe. Some setups also refuse to build untrusted requests until a maintainer approves them.
flowchart TD
PR["Pull request opened"] --> W{"From the same repository?"}
W -->|"Yes"| TR["Trusted: use PR Jenkinsfile"]
W -->|"No, from a fork"| TP{"Author trusted by policy?"}
TP -->|"Yes"| TR
TP -->|"No"| UT["Untrusted: use target branch Jenkinsfile"]
UT --> NS["No secrets, limited stages, or wait for approval"]
TR --> FULL["Full pipeline with normal access"]
FULL --> ST["Status shown on the pull request"]
NS --> ST
Never give secrets, deployment credentials or production access to builds of untrusted pull requests. Assume that any code that runs can read whatever the build can read.
12Tags and Release Builds
Building versions that have been officially labeled.
A tag is a permanent label on one exact point in the history, usually a version such as v4.12.0. Unlike branches, tags do not move. That makes them perfect for releases: the code labeled v4.12.0 is the same today and in three years.
When you enable tag discovery, Jenkins creates a child job for each tag it finds. Inside that job the variable TAG_NAME holds the label, and the tag condition lets a stage run only for tag builds. A common design is that the normal pipeline builds and tests everything, while a release stage that publishes packages runs only when the build is for a tag whose name matches a version pattern.
Reproducible releases
The release is always built from the exact labeled code, and the tag job keeps its own history for audits.
Clear intent
Creating a tag is a deliberate human act, so it is a natural trigger for publishing.
Too many jobs
Repositories with years of tags can produce hundreds of tag jobs on the first scan. Use name filters or age limits to include only recent tags.
Accidental releases
Anyone who can create a tag may trigger a publish. Limit who may create release tags at the code host.
Match tags with a strict pattern such as a version number, and let the release stage check that pattern itself. A stray tag called “test” should never publish anything.
13Orphaned Items and Cleanup
What happens when branches are merged and deleted.
Branches are short-lived. After a pull request is merged, the branch is usually deleted. The next scan notices that the branch is gone and marks its child job as orphaned. Jenkins then applies the orphaned item strategy you chose.
| Setting | Meaning | Typical choice |
|---|---|---|
| Days to keep old items | How long an orphaned job remains before removal | A few days to a few weeks |
| Maximum number of old items | Upper limit on how many orphans are kept | A modest number such as 10 to 50 |
| Keep forever | Never remove orphaned jobs | Rarely a good idea |
Why to keep them briefly
Keeping orphans for a few days lets people look at the logs of a build from a branch that was just merged, for example to investigate a strange failure after the fact. Removing them quickly reduces clutter and disk use. A short retention with a maximum count is the usual balance.
Two levels of cleanup
The orphaned item strategy removes whole child jobs. A separate setting inside each Jenkinsfile, the build discarder, removes old builds within a job, keeping only a chosen number. Use both: the first stops job clutter, the second stops history from growing endlessly inside long-lived branches such as main.
Illustration: the growing disk
A team with 30 developers averages 25 pull requests per week. With no orphan cleanup and no build discarder, each pull request leaves a workspace, logs and artifacts behind. After a year they have 1,300 dead jobs and a controller disk that is almost full. A two-week orphan rule and a limit of 20 builds per job brings the disk use down by more than 90 percent.
14Organization Folders: One Level Higher
Scanning a whole organization instead of a single repository.
A Multibranch Pipeline watches one repository. If you have fifty microservices in fifty repositories, creating fifty Multibranch jobs is exactly the chore we wanted to avoid. An organization folder solves this. It scans all repositories belonging to an organization or user on the code host, and for every repository containing a Jenkinsfile it creates a Multibranch Pipeline automatically. It is a Multibranch job for the entire organization.
flowchart TD
OF["Organization folder: acme-company"] --> R1["Repository: booking-service"]
OF --> R2["Repository: payments-service"]
OF --> R3["Repository: notification-service"]
R1 --> B1["main"]
R1 --> B2["PR-12"]
R2 --> B3["main"]
R2 --> B4["feature refund"]
R3 --> B5["main"]
Two scanning levels
There are now two kinds of scan. The organization scan discovers repositories. Each repository’s own scan discovers branches and pull requests. A new repository with a Jenkinsfile appears in Jenkins minutes after it is created, with no one visiting the Jenkins page at all.
When to choose it
Use it when
- You have many repositories with similar needs.
- New services appear regularly.
- You want new repositories to get builds automatically.
- Standard settings suit most repositories.
Think twice when
- Each repository needs very different settings.
- The organization is huge and API limits are tight.
- Some repositories are sensitive and need separate permissions.
- You cannot filter out archived or experimental repositories.
15Branch-Specific Behavior and Environments
Using branch names to decide what each build does.
The greatest strength of multibranch pipelines is that one Jenkinsfile can deliver different results depending on where the code came from. A popular convention maps branches to environments.
| Build type | Stages that run | Where it goes |
|---|---|---|
| Pull request | Build, unit tests, static checks, optional preview environment | Temporary preview environment, removed when the pull request closes |
| Develop branch | Build, all tests, package | Shared development or staging environment |
| Release branch | Build, all tests, security scan, package | Pre-production environment |
| Main branch | Everything above plus deployment gate | Production, often behind an approval |
| Version tag | Publish packages and release notes | Package registry or download site |
flowchart LR
C["Code pushed"] --> Q{"Build type"}
Q -->|"Pull request"| A["Build and unit tests"]
A --> PV["Preview environment"]
Q -->|"develop"| D["Build, full tests, package"]
D --> ST["Staging"]
Q -->|"main"| M["Build, full tests, scan"]
M --> AP["Approval gate"]
AP --> PR["Production"]
Q -->|"tag"| T["Publish release packages"]
Keep the safe path as the default. A stage that touches production should run only when a condition is explicitly true, such as the branch being main. If the condition is written the other way round, “run unless it is a pull request,” a new kind of branch could accidentally reach production.
Preview environments deserve a special mention. Creating a short-lived copy of the application for each pull request lets reviewers click through the change before merging. The catch is cleanup. Tear the environment down when the pull request closes or when the job is removed, or the bills will keep growing.
16Parameters, Triggers and the First-Run Effect
A subtle behavior that surprises almost everyone once.
A Jenkinsfile can declare properties such as build parameters, timer-based triggers and options like the build discarder. These are registered on the child job when a build of that branch runs. Before the first build, Jenkins does not know about them.
What this means in practice
- A brand-new branch with a parameter in its Jenkinsfile will build once with default values, because the parameter form does not exist yet. After that first run the form appears.
- A timer-based trigger declared in a Jenkinsfile starts working only after the branch has built at least once.
- If you change a parameter definition, the new form appears only after the next build.
Example: the confusing first build
A team adds a “target environment” parameter to their Jenkinsfile. A developer opens a pull request and expects a form. Instead the first build runs at once with the default value. Only the second build shows the form. The team learns to give every parameter a safe default so the automatic first build never does anything dangerous.
In multibranch pipelines most builds are triggered by code changes, not by people filling forms. Use parameters sparingly, and choose defaults that are safe when nobody is there to change them.
17Credentials, Folders and Permissions
Who can see what, and which secrets each build can use.
Folder-scoped credentials
A Multibranch job behaves like a folder, and folders can hold their own credentials. Storing a deployment key in the folder means only jobs inside it can use it, rather than every job on the server. This limits the damage if one job is misused.
Permissions
Permissions set on a folder flow down to its children unless changed. Teams commonly give developers permission to view and build, give release managers permission to approve deployments, and reserve configuration rights for a small group of administrators. Each child job inherits this, so a new branch is covered instantly without any extra steps.
Repository access credential
Lets Jenkins list branches and read the code. Give it read-only access, and status-writing rights only if you want tick marks on pull requests.
Deployment credentials
Used only by stages that publish or deploy. Bind them for the shortest possible time, and only in trusted build types.
Folder or global
Prefer folder scope. Global credentials are visible to every job and are harder to reason about.
Role-based access
Use roles or groups, not individual names, so changes to the team do not require edits in many places.
Anyone who can change the Jenkinsfile in a trusted branch can make the build use any credential that the build is allowed to see. Protect important branches at the code host, require reviews, and treat the Jenkinsfile like deployment code.
18Security in Depth
Because every branch can carry its own build recipe, the trust model matters.
Pipeline as code is powerful precisely because the code controls the build. It also means that whoever can push a branch can change what the build does. Security therefore rests on three ideas: know who can push, limit what unreviewed code can reach, and keep secrets away from untrusted builds.
Control who can push
Restrict who may push to your repository. Require pull requests and reviews for important branches.
Use the trust policy wisely
For fork pull requests, trust only people who have earned it, and run the Jenkinsfile from the target branch for everyone else.
Separate secrets from tests
Pull request builds should run tests without any deployment secrets. Only builds of protected branches or tags should receive them.
Isolate the agents
Run untrusted builds on disposable agents such as containers, so leftover files or processes cannot affect later builds.
Audit and review
Keep logs of who changed the Jenkinsfile, which builds used which credentials, and who approved releases.
Illustration: the curious contributor
An outside contributor opens a pull request that quietly changes the Jenkinsfile to print environment variables into the log. If Jenkins used the contributor’s Jenkinsfile with access to secrets, those secrets would appear in a public log. Because the team’s trust policy makes untrusted requests use the target branch’s Jenkinsfile, and because pull request builds never receive secrets, the trick reveals nothing.
Also remember that the branch names and pull request titles are text controlled by outsiders. Never paste them unchecked into commands. A branch name can contain characters that confuse shell commands, so treat these values as untrusted input and validate them before use.
19Monitoring, Logging and Metrics
How to know that your multibranch setup is healthy.
The scan log
Every indexing run writes a log accessible from the Multibranch job page. It lists each branch and pull request found, whether it has a Jenkinsfile, and what Jenkins decided to do. This is the first place to look when a branch does not appear, and a beginner’s best friend for understanding what the system is doing.
Metrics worth watching
| Metric | Why it matters | Warning sign |
|---|---|---|
| Scan duration | Shows how heavy indexing is | Scans that take many minutes |
| Code host request quota left | Scans and status updates use limited requests | Quota reaching zero before the hour ends |
| Number of child jobs | Measures clutter and controller load | Growing every week without shrinking |
| Queue wait time | Shows whether agents are enough | Pull requests waiting many minutes to start |
| Build time by build type | Reveals slow pull request pipelines | Pull requests slower than main builds |
| Webhook delivery failures | Missing webhooks mean delayed builds | Repeated failures reported by the code host |
| Disk used by workspaces | Catches missing cleanup | Free space shrinking steadily |
Monitoring plugins can expose these numbers to systems such as Prometheus, and dashboards make them visible to the whole team. The code host’s own webhook page also shows recent deliveries and their responses, which quickly reveals connection problems.
20Performance and Scalability
What changes when you have hundreds of repositories and thousands of branches.
Every child job is a real Jenkins job with its own record on the controller. A few hundred are no trouble. Many thousands begin to weigh on memory, on the loading time of pages and on scan duration. The main levers are to create fewer jobs, scan less often and make each build lighter.
Filter branches
Build only the branches that matter, and discover pull requests instead of every feature branch.
Webhooks over timers
Targeted scans on events cost far less than full scans on timers, and save request quota.
Cache and share
Cache dependencies between builds, and use shared libraries so pipelines stay short and fast to load.
Elastic agents
Use agents that start on demand, such as containers, so a burst of pull requests does not wait in a long queue.
Aggressive cleanup
Short orphan retention and build discarders keep the controller lean.
More than one controller
Very large organizations divide teams across several Jenkins controllers so no single one becomes a bottleneck.
Those figures are only an illustration, but they show how quickly numbers multiply. Two hundred repositories with fifteen active branches each produce three thousand child jobs. Cutting active branches to five per repository by filtering and quick cleanup cuts the load by two thirds.
21Useful Design Patterns
Reliable ways of arranging multibranch setups.
Pattern 1: Pull requests build, main deploys
Every pull request runs the fast build and tests. Only main builds run the deployment stages. Contributors get quick feedback, and production access is limited to one protected branch.
Pattern 2: One shared library, many repositories
Put the common pipeline steps into a shared library, a reusable code module that Jenkinsfiles can call. Each repository’s Jenkinsfile then becomes a few lines saying “use the standard pipeline with these settings,” and one fix helps every repository.
Pattern 3: Safe defaults by build type
Write stage conditions so anything unknown does the least dangerous thing. Deploy stages run only on explicitly named branches.
Pattern 4: Preview environments with automatic teardown
Create a temporary environment per pull request, and remove it in the post section and through cleanup when the pull request closes. Reviewers see real behavior without leaving costly resources behind.
Pattern 5: Cancel outdated builds
When a new commit arrives on the same branch, cancel the older build still running. This saves agents and avoids reporting results for code that no longer exists.
Pattern 6: Status checks as merge gates
Configure the code host to require a successful Jenkins status on a pull request before it can be merged. The tick mark becomes a real gate, not just decoration.
22Anti-patterns to Avoid
Habits that look fine at first and hurt later.
What people do
They let every branch deploy, because the deploy stage has no condition.
Why it hurts
A half-finished experiment can overwrite a shared environment or even production.
Better approach
Write positive conditions such as “only on main” and keep deploy credentials out of other build types.
What people do
They poll the repository every minute instead of using webhooks.
Why it hurts
It burns request quota, loads the controller and still reacts slowly, sometimes leading to blocked access.
Better approach
Use webhooks for speed and a daily scan as a safety net.
What people do
They trust all fork pull requests with full access.
Why it hurts
Outsiders can change the Jenkinsfile and read secrets or reach internal systems.
Better approach
Use a strict trust policy, run the target branch’s Jenkinsfile for untrusted changes and withhold secrets.
What people do
They copy a long Jenkinsfile into every repository and edit each copy.
Why it hurts
Copies drift apart, fixes must be repeated everywhere and no two services build the same way.
Better approach
Move shared logic into a library, and keep each Jenkinsfile short.
What people do
They ignore cleanup, keeping every old job and every old build.
Why it hurts
Disk fills, pages slow down and scans take longer each month.
Better approach
Set an orphaned item strategy and a build discarder from day one.
What people do
They edit child jobs in the Jenkins web page.
Why it hurts
Child jobs are regenerated from the parent and the Jenkinsfile, so manual edits are lost or cause confusion.
Better approach
Change the Jenkinsfile for build logic and the parent job for discovery rules.
23Best Practices and Common Mistakes
A checklist to apply to any Multibranch setup today.
Do this
- Use webhooks for speed and a slow timer as a safety net.
- Discover pull requests, and filter branches by name.
- Set an orphaned item strategy and a build discarder.
- Use a strict trust policy for fork pull requests.
- Keep deployment credentials in folder scope, and only for protected builds.
- Make deploy stages run only on explicitly named branches or tags.
- Keep Jenkinsfiles short by using a shared library.
- Use the scan log as your first debugging tool.
- Give parameters safe defaults.
Avoid this
- Building every experimental branch.
- Polling every minute.
- Trusting all pull requests with secrets.
- Hard-coding branch names in checkout steps.
- Leaving old jobs and builds forever.
- Editing child jobs by hand.
- Copying long Jenkinsfiles into many repositories.
- Very long branch names that break file paths.
- Publishing releases from any tag without checking its name.
Mistakes people make when they are new
Forgetting the Jenkinsfile. A branch without the pipeline file at the expected path is invisible. New teams often wonder why a branch never appears, when the answer is simply that the file is missing or named differently.
Wrong script path. If the Jenkinsfile lives in a subfolder, the script path must say so. Otherwise every branch is skipped.
Expecting instant pull request builds without webhooks. Without a working webhook, builds appear only at the next scan, which can be hours.
Ignoring the first-run effect. Parameters and triggers appear only after a branch has built once.
Not thinking about forks. Public repositories receive pull requests from strangers. Decide your trust policy before opening the door.
Building the same code twice. If a branch has an open pull request and both are discovered, the same code can build twice. Choose discovery options that avoid duplicates, unless you truly want both results.
24Advantages, Disadvantages and Trade-offs
An honest look at what Multibranch Pipelines do well and where they strain.
Advantages
- Jobs appear and disappear automatically with the branches.
- Build logic lives with the code and evolves with it.
- Pull request feedback appears right where reviewers work.
- Each branch has its own history, keeping failures separate.
- Consistent setup across many repositories through organization folders.
- Permissions and credentials inherit from the folder.
Disadvantages
- Many child jobs can burden the controller.
- Scans consume code host request limits.
- Trust and secrets need careful design.
- First-run effects with parameters and triggers can confuse.
- Every branch needs a Jenkinsfile, or it is ignored.
- Debugging spans two places: the parent settings and the Jenkinsfile.
Trade-offs to weigh
| Choice | Benefit | Cost |
|---|---|---|
| Discover all branches | Feedback on every push | Many jobs and wasted builds |
| Discover only pull requests | Calm, focused builds | No feedback until a pull request exists |
| Build merged result | Catches integration problems early | Result shifts as the target moves |
| Build head only | Stable and reproducible | Can miss conflicts with the target |
| Short orphan retention | Lean controller | Less time to inspect old branches |
| Organization folder | Zero-touch onboarding of repositories | Less per-repository control |
There is no universally right answer. The right settings depend on your team size, how fast branches appear, and how much risk you accept. Choose on purpose and write down why.
25Real-World and Industry Examples
How the ideas look in the kinds of organizations that run Jenkins at scale.
A company with many microservices
Organizations that split their software into dozens or hundreds of services typically use an organization folder so that every new service gets a build the moment its first Jenkinsfile lands. A shared library gives all services the same stages, so security scans and test reports look identical everywhere.
An open-source project
Projects that accept contributions from strangers rely heavily on pull request builds with strict trust rules. Outsiders get automatic feedback on their changes, while only maintainers can trigger anything that touches release infrastructure.
A bank with change control
In regulated industries, the main branch builds run the full set of checks and stop at an approval gate. Every tag build records who approved the release. The Multibranch structure gives auditors a clean history per release line.
A mobile app team
Mobile builds are slow and use costly machines. The team builds pull requests with a fast test subset, runs the long device tests only on develop and release branches, and uses tag builds to publish the app to the stores.
A startup with one repository
A small team sets up one Multibranch job, enables pull request discovery and adds a webhook. They spend one afternoon on setup, and afterwards never create a job by hand again.
26Multibranch Versus Other Job Types
Where the Multibranch Pipeline fits among its relatives.
| Job type | What it watches | Best for | Weakness |
|---|---|---|---|
| Freestyle job | One branch set in the web form | Very simple tasks and legacy work | Config lives outside the code, hard to review or copy |
| Single Pipeline job | One branch, one Jenkinsfile | A fixed process with one main line | No automatic branches or pull requests |
| Multibranch Pipeline | All branches, pull requests and tags of a repository | Modern branch-based development | Job count and trust design need attention |
| Organization folder | All repositories of an owner | Many repositories with similar needs | Less per-repository control; API limits |
| Generated jobs from a seed | Whatever a script defines | Highly custom layouts | Extra system to maintain |
If your code lives in a repository with branches and pull requests, start with a Multibranch Pipeline. Move up to an organization folder when you have many similar repositories. Use a single Pipeline job only when there is truly one line of work and nothing else to discover.
27A Complete Story: From Push to Production
Follow one imaginary team through a working day.
A team owns a booking service. Their organization folder scans the company’s repositories. The booking repository has a Jenkinsfile that uses a shared library. Pull requests are discovered from the same repository and from forks with a strict trust policy. Branches are filtered to main, develop and release names, and old jobs are removed after two weeks.
A branch and a pull request
Maya creates a branch for a new checkout feature and opens a pull request numbered 57. The code host sends a webhook to Jenkins.
Discovery
Jenkins runs a targeted scan, finds the Jenkinsfile in the pull request, creates a child job named PR-57 and queues a build.
Pull request build
The pipeline sees that this is a change request. It runs build, unit tests and static checks, and skips deployment stages. No secrets are available.
Feedback
Jenkins reports a green tick to the pull request. Reviewers see it without leaving their page, and approve the change.
Merge
The pull request merges into main. A webhook fires again, and the main child job starts a build.
Main pipeline
Because the branch is main, the pipeline also runs the full tests, a security scan and deploys to staging. It then pauses at an approval gate for production.
Release
A release manager approves, production is updated, and a tag v4.12.0 is created. The tag build publishes the packages.
Cleanup
The feature branch is deleted. The next scan marks PR-57 orphaned, and after two weeks Jenkins removes it. The team never touched the Jenkins pages.
28Troubleshooting Guide
Symptoms, likely causes and calm fixes.
| Symptom | Likely cause | What to do |
|---|---|---|
| No jobs are created | Wrong script path, missing Jenkinsfile, or bad credentials | Open the scan log and read what it says for each branch |
| One branch is missing | Filtered out by name, or no Jenkinsfile in that branch | Check the filters and the branch contents |
| Pull requests from forks never appear | Fork discovery not enabled | Add the fork pull request behavior with a trust policy |
| Builds start only after long delays | Webhook not reaching Jenkins | Check delivery history at the code host and network access |
| Scan fails with rate limit messages | Too many requests to the code host | Use webhooks, lengthen timers, and filter repositories |
| Every job builds the same code | Hard-coded branch in a checkout step | Use the scm variable for checkout |
| Parameters missing on a new branch | First-run effect | Run one build, then the form appears |
| Deleted branch job still there | Orphaned item retention | Shorten retention or remove manually |
| Path too long errors | Very long branch names | Shorten names or use a shorter workspace root |
| Deploy ran from a feature branch | Missing branch condition | Add a positive branch condition to the deploy stage |
A calm debugging routine
- Open the scan log of the Multibranch job and find the branch in question.
- Read the decision Jenkins made: no Jenkinsfile, filtered, or created.
- Check the code host’s webhook page if the trouble is timing.
- Read the child job’s console log to see which revision was built.
- Change one thing at a time and rescan.
29Plain-English Glossary
Every important word in this guide in one place.
| Word | Simple meaning |
|---|---|
| Jenkins | A free automation server that builds, tests and delivers software. |
| Pipeline | A written recipe of the steps Jenkins follows. |
| Jenkinsfile | The text file holding the pipeline, stored in the code. |
| Branch | A separate line of work in version control. |
| Pull request | A request to merge a branch, used for review. |
| Fork | A personal copy of a repository owned by someone else. |
| Tag | A permanent label on one exact version of the code. |
| Multibranch Pipeline | A job that creates a child job per branch, pull request or tag. |
| Organization folder | A job that creates a Multibranch job per repository. |
| Branch source | The connection to a code repository. |
| Behavior | A discovery rule inside a branch source. |
| Indexing | A scan that discovers branches and creates or removes jobs. |
| Orphaned item | A job whose branch no longer exists. |
| Webhook | An automatic message from the code host to Jenkins. |
| Trust policy | The rule deciding whose pull requests are trusted. |
| Shared library | A reusable code module many Jenkinsfiles can call. |
| Agent | A worker machine or container that runs builds. |
| Controller | The main Jenkins server that manages everything. |
30Frequently Asked Questions
Short answers to the questions that come up most often.
31Summary and Key Takeaways
The whole story in a few lines.
A Multibranch Pipeline is a manager job. You connect it to a repository once, and it discovers branches, pull requests and tags that have a Jenkinsfile, creating and removing child jobs automatically. Each child runs its own pipeline and reports back to the code host. Organization folders extend the same idea to many repositories. Used well, with webhooks, filters, trust policies, cleanup rules and branch-aware pipelines, it gives fast feedback with almost no manual upkeep. Used carelessly, it multiplies jobs, exhausts request limits and exposes secrets to strangers.
Key Takeaways
- One setup, many jobs. The parent discovers branches, pull requests and tags and creates a child job for each one that has a Jenkinsfile.
- The Jenkinsfile decides the build. The parent decides what to discover; the file in each branch decides what happens, using the branch, change request and tag conditions.
- Webhooks first, timers as a safety net. This gives fast builds and protects request limits.
- Pull requests need a trust model. Use strict trust policies, the target branch’s Jenkinsfile for untrusted changes and no secrets in those builds.
- Clean up from day one. Use an orphaned item strategy and build discarders so jobs, disk and scans stay small.
- Keep deployment explicit. Deploy stages run only on named branches or tags, with credentials scoped to folders and protected builds.
- Scale by shrinking. Filter branches, share pipeline code through a library, and use organization folders only where similar repositories justify them.