Canary Deployment in Jenkins

Canary Deployment in Jenkins

A beginner-friendly introduction to releasing new software to a small slice of real users first: how a canary works, how Jenkins orchestrates it, how to decide whether to go on or roll back, and how to avoid the mistakes that turn a safety net into a trap.

For many years, coal miners carried small yellow birds called canaries down into the mine. Dangerous gases such as carbon monoxide would affect the tiny bird long before they harmed a person. If the canary became unwell, the miners knew to leave at once. The bird was not there to dig coal. It was there to warn the miners early, while the danger was still small and everyone could still walk out.

A canary deployment uses the same idea for software. Instead of sending a new version of your application to every user at once, you first send it to a very small group, perhaps one user in a hundred. You watch carefully. If that small group has a good experience, you widen the group step by step. If the small group runs into trouble, you pull the new version back, and only a handful of people ever noticed. Jenkins is the tool that runs the steps of this careful release. This guide explains the idea from zero, shows where Jenkins fits, and teaches you how to build a safe, simple canary release process.

1What Is a Canary Deployment?

We start with the simplest picture: two versions of the same application running side by side, with a dial that controls how many users see the new one.

Jenkins is a tool that automates building, testing, and delivering software. Deployment is the act of putting a new version of an application onto the servers where real users reach it. A canary deployment is a way of deploying in which the new version, called the canary, runs alongside the current version, called the stable or baseline version. A traffic router sends a small share of user requests to the canary, and the rest to the stable version. Nobody is asked to choose. Users simply land on one or the other.

While the canary serves its small share, the team watches metrics: how many requests fail, how slow they are, and whether business numbers such as orders or sign-ins are healthy. If the canary looks as good as the stable version, the share is increased in steps. If it looks worse, the share is set back to zero and the stable version carries on as if nothing had happened.

flowchart LR
  A["Users send requests"] --> B["Traffic router"]
  B -->|95 percent| C["Stable version"]
  B -->|5 percent| D["Canary version"]
  C --> E["Metrics are collected"]
  D --> E
    
Figure 1. A canary deployment. A small share of traffic goes to the new version, and metrics from both versions are compared.
Everyday analogy

A restaurant plans to change its most popular dish. Instead of switching the menu for every customer on Saturday night, the chef offers the new recipe to one table in twenty and asks the waiters to watch how it goes. If those diners smile and clear their plates, the chef offers it to more tables. If they push it away, the chef quietly returns to the old recipe, and most of the room never knew.

The four ideas in one sentence each

Idea 1

Small first

Start with a tiny share of users, so a mistake affects few people.

Idea 2

Measure

Compare the canary with the stable version, using real numbers and not feelings.

Idea 3

Widen or retreat

Increase the share when the numbers are good, and pull back at once when they are not.

Idea 4

Automate the routine

Jenkins runs the steps, so the process is the same every time and nobody forgets a check.

i
Note

This guide is an introduction. It describes the ideas and patterns in general terms, and mentions tools by kind. Products and plugins change, so check the current documentation of the tools you use before adopting any specific setting.

2Why Canary Deployments Exist

To see why teams bother with this extra care, imagine releasing without it.

The problem: big-bang releases

In a big-bang release, the new version replaces the old one for everybody at the same moment. If it works, all is well. If it hides a bug, every user meets that bug at once. The team learns about the problem from angry messages and alarms, then scrambles to undo the release while the damage grows by the minute.

Why testing cannot catch everything

Tests run in environments that only approximate production. They use small data, simple traffic, and a few machines. Real users behave in ways nobody predicted: unusual browsers, odd inputs, huge accounts, and bursts of traffic. Some bugs only appear under real load, or only with real data. A canary release accepts this truth. It treats production as the final test, but keeps that test small and reversible.

How the idea grew

Large internet companies were among the first to release to a small share of traffic before a full rollout, because with millions of users, even a small bug reaches a great many people. The approach became widely known as software delivery moved towards frequent releases, and as tools for splitting traffic, such as container platforms, service meshes, and cloud load balancers, made it practical for ordinary teams. Today it is often described as part of progressive delivery, which means releasing new features gradually and with measurement.

1 in 100
users may see the new version first
Minutes
is how quickly a bad canary can be pulled back
Small
is the blast radius of a mistake, compared with a big-bang release
Everyday analogy

A pharmaceutical company does not give a new medicine to the whole country on day one. It tests on a small group, then a larger one, then a much larger one, watching for harm at every step. The extra time is not wasted. It is the price of finding problems while they are small.

Find the problem while it still fits in a small room.

3Words You Need First

A handful of terms come up in every canary discussion. Learn them once here.

Word 1

Stable or baseline

The version currently serving most users. It is the standard the canary is compared against.

Word 2

Canary

The new version that receives a small share of traffic to prove it is safe.

Word 3

Traffic split

The rule that decides what share of requests goes to each version, such as ninety-five to five.

Word 4

Blast radius

How many users are affected if something goes wrong. Canaries keep it small.

Word 5

Bake time

How long the canary runs at a given share before a decision is made. Enough time is needed to collect meaningful data.

Word 6

Promotion

Moving the canary to full service, so it becomes the new stable version.

Word 7

Rollback

Returning all traffic to the stable version, and removing the canary.

Word 8

Health metrics

Measured numbers, such as error rate and response time, that show whether a version is behaving well.

The four golden signals

A well-known list of things to watch for any service is called the four golden signals. Latency is how long requests take. Traffic is how many requests arrive. Errors is how many requests fail. Saturation is how full the service’s resources are, such as processor, memory, and connections. A canary is judged mainly on these four, plus a few numbers that matter to the business.

A few Jenkins words too

The controller is the main Jenkins server that plans the work. An agent is a worker machine that runs commands. A pipeline is the ordered list of stages in a Jenkinsfile. A stage is one named phase, such as Build or Deploy. A credential is a stored secret, such as the key that lets a pipeline reach a cluster.

i
Tip

When a canary discussion gets tangled, ask three questions: who gets the canary, what do we measure, and what will we do if the numbers look bad? Every canary design is an answer to those three.

4Canary Versus Other Release Strategies

A canary is one of several ways to release software. Knowing the others helps you pick the right one.

StrategyHow it worksStrengthWeakness
RecreateStop the old version, start the new oneSimplest, uses no extra capacityDowntime, and everybody gets the risk at once
Rolling updateReplace instances of the old version a few at a timeNo downtime, little extra capacityNo clean way to pause at a small share and compare versions
Blue-greenRun two full environments, then switch all traffic from one to the otherInstant switch and instant switch-backNeeds double capacity, and the switch exposes everyone at once
CanarySend a small, growing share of traffic to the new versionSmall blast radius, real-user evidenceNeeds traffic splitting and good metrics, and takes longer
A/B testShow different features to different user groups to compare outcomesAnswers product questionsIs about learning, not safety, and needs statistical care
Shadow or mirrorCopy real traffic to the new version without returning its answers to usersNo user impact at allCannot test things that change data, and needs extra care
Feature flagShip code turned off, then switch the feature on for chosen usersSeparates deploying from releasingAdds code paths that need cleanup
Everyday analogy

Changing the road layout of a town can be done overnight (recreate), one street at a time (rolling), by building a whole new town centre and switching the signs (blue-green), or by opening the new layout to a few buses first to see if it works (canary). Each has its place, and the right one depends on the risk and the cost.

How they combine

These strategies are not enemies. Many teams use a rolling update inside each step of a canary. Others use feature flags together with canaries: the canary tests that the new build is healthy, and flags control when its new features reach users. A blue-green environment can host a canary too, by sending a small share of traffic to the new side before switching fully. Choose the combination that fits your system, and do not treat the names as rigid boxes.

i
Tip

If you cannot split traffic, or you have no useful metrics, a canary will not help you, and a simpler strategy plus strong testing is a better use of your effort. Build the ability to measure first, then add the canary on top.

5Where Jenkins Fits

An important point for beginners: Jenkins does not split traffic by itself. It is the conductor of the orchestra, not one of the instruments.

Jenkins is very good at running steps in order, on a schedule, with approvals and error handling. It is not a traffic router and not a monitoring system. A canary deployment therefore needs three kinds of tools working together.

Tool 1

Jenkins: the orchestrator

Builds and tests the code, publishes the artifact, starts the canary, waits, asks questions, and decides to promote or roll back.

Tool 2

A traffic layer

Sends the chosen share of requests to the canary. It might be a container platform, an ingress controller, a service mesh, or a cloud load balancer.

Tool 3

A monitoring system

Collects metrics from both versions and answers questions such as “what is the error rate of the canary?”.

Extra

An artifact repository

Stores the exact version being released, so the same tested file is used for the canary and the full rollout.

flowchart TD
  A["Developer merges code"] --> B["Jenkins builds and tests"]
  B --> C["Publish the artifact to the repository"]
  C --> D["Jenkins deploys the canary"]
  D --> E["Traffic layer sends a small share to the canary"]
  E --> F["Monitoring system collects metrics"]
  F --> G["Jenkins reads the results"]
  G --> H{"Is the canary healthy"}
  H -->|Yes| I["Increase the share or promote"]
  H -->|No| J["Roll back"]
    
Figure 2. Jenkins coordinates the build, the deployment, the waiting, and the decision. Other tools split traffic and measure health.
Everyday analogy

A film director does not play every instrument, run the cameras, and build the sets. The director tells each specialist when to start, checks the results, and calls “cut” or “again”. Jenkins is the director of the release. The traffic layer and the monitoring system are the specialists.

What Jenkins actually does in a canary

  • Builds and tests the change, as in any pipeline.
  • Publishes an immutable, versioned artifact to a repository.
  • Deploys the canary to the platform, by calling its tools or updating its configuration.
  • Sets the traffic share, again by calling the traffic layer’s tools or changing its configuration.
  • Waits for the bake time, without holding a build machine idle.
  • Reads metrics from the monitoring system, and applies the rules for success.
  • Asks a person, when the process needs human judgement.
  • Promotes or rolls back, and tells the team what happened.
!
Watch out

Some newer tools take over the traffic-shifting and metric-checking work themselves, so Jenkins only triggers the release and waits for the answer. This is a valid design. Either way, decide clearly which tool owns the decision, so that two systems never fight over the traffic share.

6Ways to Split Traffic

The traffic layer is what makes a canary possible. Here are the common ways to build it, from simple to sophisticated.

MechanismHow the split worksPrecisionGood for
Instance ratioRun, for example, nineteen stable instances and one canary behind one load balancer, so about five percent of requests land on the canaryCoarse, tied to instance countsSimple setups on container platforms or virtual machines
Ingress or gateway weightsThe entry point of the platform sends a set percentage of requests to each versionFine, such as one percentWeb applications on container platforms
Service meshA network layer between services shifts traffic by weight, header, or user groupVery fine, with rich rulesMany internal services, and precise control
Cloud load balancer weightsThe load balancer’s target groups carry weights that you changeFineApplications hosted with a cloud provider’s tools
Weighted DNSName-lookup answers are split by weightCoarse and slow to change, because of cachingSimple, wide-area setups
Feature flagsCode decides at run time who sees a featurePer user or groupFeature-level canaries, on top of any of the above
Everyday analogy

A traffic officer at a road junction can send every twentieth car down a new road, or open a new lane with an adjustable barrier, or use a smart signal that reads car types. A coarse method is easy to set up. A precise one gives finer control, but takes more equipment.

Stickiness: keeping a user on one version

Without care, one user could hit the stable version on one click and the canary on the next, seeing pages that change back and forth, or losing a shopping basket. Sticky routing keeps a user on the same version, usually by remembering a value in a cookie or a header. Stickiness gives a steadier experience and cleaner data, since each user is clearly in one group. The trade-off is that a few unlucky users stay on a bad canary until it is removed, so keep the canary group small.

Choosing who sees the canary

Choice

Random percentage

A simple share of requests, chosen at random. Good for general health checks.

Choice

Internal users first

Employees or testers use the canary before any customer does. Safe, and gentle.

Choice

Region or cohort

One country, one data centre, or one customer group gets the canary, which limits the effect and simplifies comparison.

Choice

Opt-in group

Volunteers who accept early versions, such as beta users, who tolerate small problems.

i
Tip

Start with the simplest mechanism your platform already gives you. A working canary at five percent by instance ratio is worth more than a perfect service mesh that nobody has finished setting up.

7Anatomy of a Canary Pipeline

Let us walk through the stages of a typical canary pipeline in Jenkins, from a commit to a fully released version.

1

Build and test

The pipeline compiles the code and runs the usual tests. Nothing reaches users unless these pass. A canary is a second line of defence, not a replacement for tests.

2

Publish an immutable artifact

The pipeline publishes the build output, for example a container image, with a unique version and a checksum, to an artifact repository. The same artifact will be used for the canary and for the full release.

3

Deploy to a test environment

Before any real user is involved, the artifact is deployed to a staging environment and checked with automated tests. Only a version that survives this moves on.

4

Deploy the canary

The pipeline starts the new version in production, alongside the stable one, with no traffic yet. It waits until the canary reports that it is ready.

5

Shift a small share of traffic

The pipeline asks the traffic layer to send a small share, such as one or five percent, to the canary.

6

Bake and analyse

The pipeline waits for the bake time, then reads metrics from both versions and applies the success rules.

7

Decide: widen, hold, or roll back

If the numbers are good, the share grows to the next step, and stages six and seven repeat. If they are bad, the canary is removed.

8

Promote and clean up

When the canary reaches full share and stays healthy, it becomes the stable version. The old version is scaled down, but its artifact stays in the repository so that a rollback is still possible for a while.

Everyday analogy

Opening a new shop follows a similar path. The owners test the recipes in a kitchen, prepare the shop, hold a quiet soft opening for friends and neighbours, watch the feedback, open to the street with a small sign, and only then announce the grand opening. Every step widens the audience only after the last step went well.

One pipeline or several?

Some teams keep everything in one long pipeline that runs for an hour or more. Others split it: one pipeline builds and publishes, and a second one handles the release, started automatically or by a person. The second style helps when the release needs its own permissions, its own approvals, or a different schedule. Whichever you choose, keep the release steps clear, named, and visible on the Jenkins screen so that anyone can see how far the canary has got.

i
Tip

Give each traffic step its own stage name, such as “Canary 5 percent” and “Canary 25 percent”. The Jenkins stage view then reads like a progress bar, and a failure shows exactly which step it happened at.

8Deciding: Metrics and Canary Analysis

The whole value of a canary depends on one question: how do we know the canary is healthy? This chapter answers it.

Compare, do not just measure

Looking at the canary’s error rate alone can mislead. If the whole website is having a bad afternoon, the canary will show errors too, and it would be wrong to blame the new version. The reliable method is to compare the canary with the stable version at the same time. Both run under the same conditions, so any difference between them is much more likely to come from the change itself.

flowchart TD
  A["Canary is running with a small share"] --> B{"Enough traffic and time to judge"}
  B -->|No| C["Keep waiting or lengthen the bake time"]
  B -->|Yes| D{"Errors and latency close to the stable version"}
  D -->|No| E["Roll back and investigate"]
  D -->|Yes| F{"Saturation and business metrics healthy"}
  F -->|No| E
  F -->|Yes| G["Increase the share to the next step"]
    
Figure 3. A decision path for one canary step. The canary must pass every check before the share grows.
Everyday analogy

A teacher trying a new teaching method with one class compares its exam results with a similar class taught the old way in the same term. If both classes did badly because the exam was hard, the method is not to blame. Comparison at the same time removes the noise that would fool a single reading.

What to compare

SignalWhat it showsExample rule
Error rateThe share of requests that failThe canary’s error rate must not exceed the stable version’s by more than a small margin
LatencyHow long requests take, especially the slowest ones, such as the ninety-fifth percentileSlow-request time must not rise by more than a set percentage
SaturationProcessor, memory, connections, and queue lengthsResource use must stay within the normal range
Restarts and crashesHow often the canary’s instances restartNo unexpected restarts during the bake time
Business metricsOrders, sign-ins, searches, or other outcomes that matter to the companyConversion must not fall below the stable version’s
Logs and alertsUnusual error messages or triggered alarmsNo new kinds of error, and no alerts from the canary

Enough data to judge

A canary with a tiny share of traffic may see only a few requests a minute. With so little data, one lucky or unlucky minute can look like a trend. Suppose the service handles ten thousand requests a minute and the canary gets one percent. That is one hundred requests a minute, or about a thousand in ten minutes. If the stable version’s error rate is half of one percent, we would expect about five errors in a thousand requests. If the canary shows thirty errors, the difference is large and clear. If it shows seven, it is hard to say. Low-traffic services may need a longer bake time, a larger share, or a different way of testing.

10,000
requests a minute in the example service
100
requests a minute reach a one percent canary
5 vs 30
expected errors in 1,000 requests versus a clearly bad canary

Manual or automatic analysis

  • Manual. A person looks at dashboards and decides. Simple to start, and good for learning what matters, but slow and subject to fatigue.
  • Scripted. A pipeline step queries the monitoring system, compares numbers with fixed rules, and returns pass or fail. Consistent and quick, but the rules must be chosen well.
  • Specialised analysis tools. Some platforms provide automated canary analysis that compares many metrics statistically, and gives a score. Powerful, but needs setup and tuning.
!
Watch out

Monitoring systems often lag by a minute or two. Read metrics only after enough time has passed for the data to arrive, and use a window long enough to be meaningful. Deciding on stale or empty data is the fastest way to promote a bad canary, or to roll back a good one.

9Gates: Approvals and Automated Checks

A gate is a point where the pipeline stops and asks, “May we continue?”. Canary pipelines use gates at each traffic step.

The manual gate

Jenkins has an input step that pauses the pipeline and waits for a person to click Proceed or Abort. It can be limited to named people or groups, so that only authorised users can approve. It can carry a message and a few questions, and it should carry a time limit, so that a forgotten approval does not leave a canary running for days.

Everyday analogy

A pilot cannot start the engines until the tower says “cleared for take-off”. That is a manual gate. On a routine flight the answer comes fast. On a stormy day, the wait is worth it, since someone with a wider view is making the call.

The automated gate

An automated gate is a stage that reads the metrics, applies the rules, and either continues or fails the pipeline. It has no waiting for a person. Because it is a script, it is repeatable and quick, and it works at any hour. Its weakness is that it can only check what you told it to check.

Choosing between them

Manual gates suit

  • The first weeks of a new canary process, while you learn what to measure.
  • High-risk changes such as payments or data migrations.
  • Steps where business judgement matters, such as the final promotion.

Automated gates suit

  • Frequent, low-risk releases, where waiting for a person is a bottleneck.
  • Early steps at small shares, with clear numbers.
  • Out-of-hours releases, when nobody is watching.

A common blend

Many teams automate the early steps and keep a person for the final one. The first steps at one, five, and twenty-five percent pass on numbers alone. Before going from twenty-five to a hundred percent, a person confirms that nothing else, such as an ongoing incident or a sales event, makes this a bad moment to finish.

i
Tip

Place the approval step outside any agent block, with a timeout around it. The pipeline then waits on the lightweight controller side, uses no build machine while it waits, and gives up cleanly if nobody answers.

!
Watch out

A gate that people always approve without looking is worse than no gate, because it gives a false sense of safety. If approvals become automatic clicks, either make the check automatic and reliable, or make the approver look at real numbers each time.

10Rollout Steps and Bake Times

How big should each step be, and how long should the pipeline wait? Here is a sensible way to think about it.

StepShare of trafficBake time in this examplePurpose
11 percent10 minutesCatch crashes and obvious failures with tiny impact
25 percent10 minutesConfirm behaviour under a little more load
325 percent15 minutesSee how the version handles serious load and varied users
450 percent15 minutesCheck capacity, as the canary now carries half the traffic
5100 percentWatch period afterwardsComplete the release, and keep the old version ready for a short time
Everyday analogy

Learning to swim, you wade in to your ankles, then your knees, then your waist, then your shoulders, checking the water at each step. Nobody jumps into the deep end on the first day. The steps get bigger only as confidence grows.

Choosing step sizes

  • Start smaller when risk is higher. A payment service may start at a fraction of a percent.
  • Grow faster when risk is lower. A small copy change on a page may go from five to a hundred in one move.
  • Watch capacity as the share grows. At fifty percent, the canary carries real load, and any weakness of scale appears.
  • Keep the number of steps small. Five or six steps give safety without stretching the release over days.

Choosing bake time

The bake time should be long enough for two things: to collect enough requests to judge, and to reveal problems that take a while to appear. Some faults show at once, such as a crash on start. Others, such as a slow memory leak, take hours. A short bake catches the first kind. For the second kind, plan a longer watch period after full rollout, and keep the old version and its artifact ready for a while.

i
Note

Also think about the rhythm of your business. Traffic at three in the morning may be one-tenth of noon traffic, and behaviour differs too. Running the important bake steps during normal business hours gives more realistic data, provided a person is around to respond.

11Rollback and Safety Nets

The promise of a canary is that failure is cheap. That promise holds only if rollback is fast, automatic, and well practised.

sequenceDiagram
  participant J as Jenkins Pipeline
  participant M as Monitoring
  participant T as Traffic Router
  participant C as Canary Version
  participant S as Stable Version
  J->>T: Send five percent of traffic to the canary
  T->>C: Requests for the canary
  M-->>J: Error rate is above the threshold
  J->>T: Set the canary share to zero
  T->>S: All traffic returns to the stable version
  J->>C: Scale the canary down
  J->>J: Mark the build failed and notify the team
    
Figure 4. A rollback. Traffic returns to the stable version first, and the canary is removed afterwards.

Rollback is about traffic first

The fastest and safest rollback moves the traffic. Set the canary’s share to zero, and the stable version, which never stopped running, serves everybody again within seconds or minutes. Only after users are safe should the pipeline remove the canary instances and collect their logs for investigation. Never delete the evidence before you have saved it.

What triggers a rollback

  • An automated gate fails, for example the error rate is above the limit.
  • A person aborts the pipeline at a manual gate, or at any time.
  • The pipeline itself fails during a deployment step, and cleanup logic runs.
  • An alarm fires from the monitoring system, which can be wired to trigger the rollback pipeline.
Everyday analogy

A theatre has a fire curtain that can drop in seconds, and rehearses the drill. Nobody hopes to use it, but everybody knows exactly how, and how long it takes. A canary rollback should be the same: a practised, simple move.

Making rollback reliable in Jenkins

NeedHow Jenkins helps
Rollback on any failureThe post section of a pipeline can run cleanup and rollback steps when a stage fails or the build is aborted
No hanging releaseTimeouts around waits, gates, and deployment steps, so a stuck canary is removed
Old version readyThe previous artifact stays in the repository, and its version is recorded in the pipeline
Rollback as its own pipelineA separate job that takes a version and shifts traffic back, usable by a person in an emergency
Clear alertsNotifications to the team when a canary fails or is rolled back
!
Watch out

Test your rollback regularly, on purpose, in a safe environment and occasionally in production during a quiet time. A rollback that has never been tried is a hope, not a plan. Also remember that some changes, such as database changes, cannot simply be undone. The next chapter covers them.

12Data and Compatibility: Two Versions at Once

During a canary, two versions of your application run at the same time and share the same data. That requires them to get along.

Why compatibility matters

Both versions read and write the same database, call the same services, and often use the same caches and message queues. If the new version changes the shape of data in a way the old version cannot read, then the stable version, which is still serving most users, may break, and a rollback may not fix it, because the data has already changed.

Area

Database changes

Make changes in small, backward-compatible steps, so both versions work with the database at every moment.

Area

Interfaces between services

New versions must still answer old requests, and still understand old answers, for as long as both are running.

Area

Messages and queues

Messages written by the canary must be readable by the stable version, and the reverse.

Area

Caches and sessions

Cached data and login sessions created by one version must be safe for the other to read.

The expand and contract approach

A widely used method for database changes is expand and contract. First, expand: add the new column or structure without removing the old one, so both versions work. Then release the new version through the canary. Once the new version is fully in place and stable, contract: remove the old structure in a later release. This turns one risky change into several safe ones, each of which can be rolled back on its own.

Everyday analogy

Building a new bridge beside an old one lets traffic keep flowing throughout. Only after the new bridge is open and trusted do the engineers close the old one. Breaking the old bridge first, and hoping the new one is ready in time, would strand everyone.

Changes that suit a canary

  • Adding an optional field or a new column.
  • Adding a new endpoint next to the old one.
  • Performance improvements with the same behaviour.
  • Changes behind a feature flag that is still off.

Changes that need extra care

  • Renaming or removing a column in one step.
  • Changing the meaning of existing data.
  • Changing message formats without versions.
  • Anything that cannot be undone if the canary fails.
i
Tip

Add a question to your release checklist: “Can the stable version still run correctly with the data this canary writes?” If the answer is no, redesign the change before releasing it, not after.

13How It Works Internally: Waiting Without Wasting

A canary pipeline may run for an hour or more, most of it waiting. Understanding how Jenkins waits keeps that time cheap and safe.

Two layers again

A Jenkins pipeline has a planning layer on the controller, which tracks where the pipeline has got to, and a doing layer on agents, where commands run. Waiting is planning-layer work. If the wait sits outside an agent block, Jenkins uses only a lightweight thread on the controller, and no build machine is tied up. If the wait sits inside an agent block, an executor is held the whole time, doing nothing.

Waiting methodWhat it doesHolds an executor if inside an agent block?Best for
sleepPauses for a fixed timeYesThe fixed bake time between steps, placed outside any agent
waitUntilRepeats a check until it succeeds, with growing pausesYesWaiting for a canary to become ready, or for metrics to arrive
inputWaits for a person to approveYesManual gates, always with a timeout
timeoutPuts a time limit around any of the aboveDepends on the blockEvery wait, so nothing lasts forever
Everyday analogy

You can wait for a table at the restaurant by standing in the kitchen, in the way of the cooks, or by sitting in the waiting area. The food is the same, but the kitchen keeps working only if you wait in the right place. Waiting outside an agent block is sitting in the waiting area.

The shape of a good pipeline

  1. The pipeline starts with no agent at the top.
  2. Build and test stages request an agent, use it, and give it back.
  3. Each deployment or traffic-shift stage requests an agent only for the short time the command needs.
  4. Bake times and approvals sit in their own stages, with no agent, guarded by timeouts.
  5. Metric checks that need a tool on a machine take an agent briefly, and release it.

Long waits and restarts

Jenkins saves the progress of a pipeline as it goes, so that a pipeline can carry on after the controller restarts. This makes a long, mostly idle canary pipeline practical. There are limits: the durability setting of a job trades speed for how completely progress is saved, and a restart in the middle of a command on an agent may still need a rerun. Design steps so that repeating them is safe. Setting a canary share to five percent twice should be the same as setting it once.

i
Tip

Make every deployment step idempotent, meaning that running it twice leaves the system in the same state as running it once. Ask the traffic layer for a target state, “the canary has five percent”, and not for a change, “add five percent”. Then retries and restarts cannot push the share beyond what you meant.

14Working with Other Jenkins Features

A canary pipeline is stronger when it uses the other safety tools Jenkins offers.

FeatureWhat it adds to a canaryWatch out for
Lock stepOnly one deployment to a given service at a time, so two canaries never fight over the traffic sharePlace the lock outside agent blocks, and add timeouts
Milestone stepAn older build can never start or continue a rollout after a newer one has passed, and outdated waiting builds are cancelledPlace milestones before the deployment, not before the tests
Artifact repositoryThe same immutable, versioned artifact is used for canary and full release, and the previous one is ready for rollbackDeploy by exact version or digest, never by a moving tag
Credentials and scopesThe cluster or cloud access needed to deploy is kept in a protected store, limited to the team’s folderBind the credential only around the steps that use it
Retry stepSmooths over brief network problems when calling platform or monitoring toolsKeep the count small, and never retry a step that is not safe to repeat
Timeout stepGuarantees that no wait, gate, or deployment runs foreverSet well above normal time, and make the timeout trigger a rollback
When conditionsRun the canary release only for the main branch or for tagsBranch conditions need a multibranch job
Post sectionCleanup and rollback that run when the pipeline fails or is abortedMake the steps safe to run even if the canary never started
ThrottlingLimits how many canary releases run across the whole company at once, protecting shared infrastructureDo not set the limit so tight that urgent fixes wait
Everyday analogy

A relay team uses a baton (the artifact), a lane for each runner (the lock), a rule that a slower runner from an earlier heat cannot finish after the winner (the milestone), and a stopwatch (the timeout). No single rule wins the race, but together they make it fair and safe.

Locks and milestones together

The combination described in the lock and milestone guide fits canaries very well. A milestone before the deployment cancels outdated builds waiting to release. A lock around the release, with the newest waiting build first, ensures only one canary per service at a time. A second milestone inside the lock catches any older build that slipped in before a newer one arrived. Together they guarantee that only the latest change is being rolled out, and only one rollout is under way.

i
Tip

Record the version, the commit, and the build link in the deployment itself, as labels or annotations. Anyone looking at the running system can then trace it back to the exact Jenkins build that released it.

15Performance, Scalability, Cost, and Reliability

A canary trades some extra time and capacity for safety. This chapter explains what it costs, and how canaries themselves can fail.

The cost of caution

A canary release takes longer than a big-bang release. With the example steps in this guide, the traffic steps alone take about fifty minutes. It also uses some extra capacity: the canary and stable versions both run for a while, and the canary needs enough resources to carry its share. Compared with blue-green, which needs a full second copy of the environment, a canary is usually cheaper, since it only adds capacity in proportion to the share.

CostWhere it comes fromHow to keep it small
Release timeBake times at each stepShort bakes for small shares, longer only where risk is high
Extra capacityCanary instances running beside stable onesScale the canary in line with its share, and remove it promptly
Monitoring loadMore metrics and queries during the releaseQuery only the few metrics that drive decisions
Engineering effortBuilding traffic splitting, metrics, and pipeline logicStart simple, and reuse tools your platform already provides
Executor timeWaiting inside agent blocksWait outside agent blocks, and hold agents only briefly
Everyday analogy

Wearing a seatbelt adds a few seconds to every journey and a small annoyance. Nobody thinks it a waste, because the rare bad day is so much worse without it. The extra minutes of a canary are the seatbelt of your release.

Scaling to many services

One canary is easy to watch. Fifty services releasing canaries in the same hour can overwhelm your monitoring, your on-call staff, and your platform. Standardise the release pipeline as a shared template, so every service follows the same steps and the same rules. Limit the number of simultaneous canaries where a shared platform is affected, and avoid releasing many dependent services at once, since problems then become hard to trace.

How canaries themselves fail

Failure

Too little traffic

The canary sees so few requests that real problems are invisible, and it passes by luck.

Failure

Wrong metrics

The rules check error rate, but the bug corrupts data quietly, or slows down only one rare page.

Failure

Problems that need scale

The canary is fine at five percent, and fails at a hundred, because of connection limits or cache behaviour.

Failure

Slow-burn faults

A memory leak takes hours to hurt, long after the bake time has ended.

Failure

Biased groups

The canary users are not typical, for example all internal staff, so their results do not represent customers.

Failure

Lagging data

Metrics arrive late, and the pipeline decides before the evidence is in.

Protections that help

  • Judge on enough data. Require a minimum number of requests before a decision is allowed.
  • Watch after promotion. Keep the old version and its artifact ready, and watch closely for a period after reaching a hundred percent.
  • Include several kinds of signal. Combine technical metrics with business ones and with log checks.
  • Test at scale before the last step. Load-test staging, or use a larger canary share before the final move.
  • Timeout everything. A stuck release must fail safely and clean up.
  • Make every step safe to repeat, so restarts and retries cannot leave a half-changed system.
!
Watch out

A passing canary is evidence, not proof. It lowers the chance of a bad release, but does not remove it. Keep alerts, on-call staff, and a quick rollback path in place even for releases that passed every gate.

16Security Considerations

A canary pipeline can change what real users see and touch production. That makes it a powerful tool, and a sensitive one.

Risk 1

Who can release

Anyone who can run or edit the release pipeline can change what production runs. Limit this to trusted people and protected branches.

Risk 2

Powerful deployment credentials

The access used to deploy is strong. Store it in the Jenkins credentials store, in a narrow scope, and bind it only around the steps that need it.

Risk 3

Tampered artifacts

If the artifact can be swapped between testing and release, what runs is not what was tested. Deploy by exact version or digest, and verify checksums or signatures.

Risk 4

Bypassing the gates

A change to the Jenkinsfile that removes the checks would let bad code reach everyone. Review pipeline changes like production code.

Risk 5

Untrusted pull requests

Builds from outside contributors must never reach the release stages or the deployment credentials.

Risk 6

Sensitive data in metrics and logs

Canary comparisons and debugging can expose customer data. Keep personal data out of metrics, and out of notifications.

Habits that protect you

  • Separate duties. The person who writes a change should not be the only approver of its release to all users.
  • Use approval rights. The manual gate should list who may approve, using groups from your security realm.
  • Keep a record. Log who started, approved, promoted, and rolled back each release, with the version and time.
  • Protect the traffic layer. Access to change routing weights is as sensitive as access to deploy.
  • Protect the rollback path. Make sure the rollback job works even if the normal release pipeline is broken.
  • Sign and scan artifacts. Check images for known vulnerabilities before the canary, not after.
Everyday analogy

Changing the switches of a railway is a job for trained staff with a logbook, and two people confirm a route before a train is sent. A canary release changes the “route” real users take, and it deserves the same care about who may throw the switch.

The power to release is the power to change what every user sees.

17Monitoring, Logging, and Troubleshooting

When a canary result is confusing, or a release fails, here is how to find out what really happened.

What to watch during a release

  • The Jenkins stage view. Shows which traffic step the release has reached, and which stage failed.
  • The console log. Shows the commands run, the metrics read, and the decision made at each gate.
  • Dashboards comparing canary and stable. Show the golden signals side by side, so a person can see the same picture the pipeline used.
  • Platform events. Show whether instances started, passed health checks, or restarted.
  • Traffic layer records. Show the real share each version received, which may differ from the intended one.
  • Notifications. Tell the team when a release starts, advances, is paused for approval, fails, or completes.
flowchart TD
  A["Canary result is confusing or failed"] --> B{"Did the canary receive real traffic"}
  B -->|No| C["Check routing rules, weights, and session stickiness"]
  B -->|Yes| D{"Are the metrics being read correctly"}
  D -->|No| E["Check queries, labels, time windows, and monitoring delay"]
  D -->|Yes| F{"Is the difference bigger than normal noise"}
  F -->|No| G["Extend the bake time or compare over a longer window"]
  F -->|Yes| H["Treat it as a real regression and roll back"]
    
Figure 5. A decision path for a confusing or failed canary.

Common symptoms and causes

SymptomLikely causeWhat to do
Canary passes, but there is no data for itTraffic was not routed to it, or its metrics carry different labelsCheck routing weights and metric labels before trusting the result
Canary fails on a noisy minuteWindow too short, or too little trafficUse a longer window and a minimum number of requests
Canary looks fine, users complainThe wrong metrics are watchedAdd signals for the failing behaviour, and review after each incident
Pipeline hangs at a gateNobody answered the approval, or a wait has no timeoutAdd timeouts, notify approvers, and set a default action
Rollback did not restore serviceData or interface change was not backward compatibleUse expand and contract, and fix the data problem
Two releases fight over the traffic shareNo lock, or two tools controlling weightsAdd a lock, and make one tool the owner of traffic weights
An old build overwrote a newer releaseNo milestone before the deploymentAdd milestones so older builds are cancelled
Executors are busy while releases waitWaits placed inside agent blocksMove waits and approvals out of agent blocks

Numbers worth tracking over time

Track how many releases went through the canary, how many were rolled back, and how quickly each rollback happened. Track the time from merge to full release. Track incidents that the canary missed, since each one shows a gap in the metrics you watch. A regular review of these numbers helps you tune bake times and rules, and shows whether the canary process is earning its cost.

18Design Patterns and Anti-patterns

Patterns are habits that keep releases calm. Anti-patterns are habits that turn a safety net into a false comfort.

Patterns that help

Pattern

Build once, canary the same artifact

One immutable artifact is tested, canaried, and promoted, with no rebuilds between the steps.

Pattern

Compare with the baseline

Judge the canary against the stable version at the same moment, not against fixed numbers alone.

Pattern

Automate early steps, human final step

Small shares pass on numbers. The last move to everyone gets a person’s confirmation.

Pattern

Rollback as a first-class job

A separate, tested pipeline that anyone on call can run, independent of the release pipeline.

Pattern

Expand and contract

Change data structures in backward-compatible steps, so both versions always work.

Pattern

Shared release template

All services use one standard pipeline, so rules and safety habits are the same everywhere.

Anti-patterns to avoid

ANTI-PATTERN 01 Avoid
Context

A team calls its release a canary, but sends five percent of traffic for one minute, with no comparison and nobody watching.

What goes wrong

The process gives a feeling of safety, but almost no evidence. Bad releases pass, and the team stops questioning the process because “we always use canaries”.

Better decision

Define what is measured, how long the bake lasts, what the pass rules are, and who acts on a failure. If those cannot be answered, the canary is theatre.

ANTI-PATTERN 02 Avoid
Context

The canary pipeline holds a build machine for the entire hour, with the bake times as sleeps inside the agent block.

What goes wrong

A few overlapping releases use up all the executors, and unrelated builds queue behind releases that are only waiting.

Better decision

Use no agent at the top, take agents only for short commands, and place bake times and approvals in stages with no agent.

ANTI-PATTERN 03 Avoid
Context

A release includes an irreversible database change, tested only through the canary.

What goes wrong

The canary fails, traffic goes back to the stable version, and the stable version cannot read the changed data. The rollback itself causes the outage.

Better decision

Split the change into expand and contract steps, each compatible with both versions.

ANTI-PATTERN 04 Avoid
Context

Two different tools both adjust the traffic weights: the Jenkins pipeline and an automated rollout controller.

What goes wrong

Each undoes the other’s changes. The traffic share jumps around, the metrics are meaningless, and nobody knows which tool is in charge.

Better decision

Choose one owner of traffic weights. Jenkins can trigger and wait, but not fight the controller.

19Advantages, Trade-offs, Best Practices, and Common Mistakes

A balanced view of canary deployment, and the habits that keep it working for you.

Advantages

  • Small blast radius for mistakes.
  • Real-user evidence before full release.
  • Fast rollback, by moving traffic back.
  • Less extra capacity than a full second environment.
  • Builds confidence, so teams can release more often.
  • Works with any language and application type that can split traffic.

Disadvantages and trade-offs

  • Needs traffic splitting and good metrics.
  • Takes longer than a big-bang release.
  • Two versions run at once, so compatibility matters.
  • Hard for services with little traffic.
  • Stateful services and irreversible changes are harder.
  • Adds engineering effort and moving parts.

Best practices in one place

  1. Test first. A canary supplements tests and never replaces them.
  2. Build once, and canary the same immutable artifact that will be promoted.
  3. Start with a tiny share, and grow in a few clear steps.
  4. Compare with the stable version at the same time, using the golden signals and one or two business metrics.
  5. Require enough data before any decision.
  6. Make rollback simple, fast, and practised.
  7. Keep changes backward compatible, using expand and contract for data.
  8. Wait outside agent blocks, and put timeouts on every wait and gate.
  9. Use a lock and milestones so only the newest change rolls out, one at a time.
  10. Own the traffic weights in one place, and make steps idempotent.
  11. Restrict who can release, and record every release and rollback.
  12. Review incidents, and add the signal that would have caught each one.

The mistakes seen most often

Mistake 1: no comparison group

The canary is judged against a fixed number, and a bad afternoon for the whole site blames the new version. The fix is to compare with the stable version at the same time.

Mistake 2: too little traffic and too short a bake

The canary sees a handful of requests, and passes by luck. The fix is a minimum number of requests, and a longer bake for small shares.

Mistake 3: rollback never tested

When it is needed, the rollback pipeline fails on an expired credential. The fix is regular drills.

Mistake 4: incompatible data changes

The new version renames a column, and the stable version breaks while the canary runs. The fix is expand and contract.

Mistake 5: waiting inside a build machine

A one-hour release holds an executor idle for an hour. The fix is to wait outside agent blocks.

20Worked Scenario: Adding a Canary to a Checkout Service

Let us follow one imaginary team as it replaces a nervous big-bang release with a calm canary, one step at a time.

The starting point

A team runs the checkout service of an online shop, which handles about ten thousand requests a minute. Releases are big-bang: Jenkins builds, tests, and replaces the old version everywhere in one go. Last quarter, a release contained a bug that made six percent of requests fail. The team noticed after forty-five minutes, from customer complaints, and needed another ten minutes to undo the release. About six hundred requests a minute failed for forty-five minutes, which is around twenty-seven thousand failed requests, some of them paid orders.

1

Choose the traffic mechanism

The service runs on a container platform, whose entry point supports weighted routing. The team decides to use it, and to make it the single owner of traffic weights.

2

Decide what to measure

They pick error rate, the ninety-fifth percentile of response time, memory use, restarts, and the number of completed orders per thousand sessions. Each is compared between canary and stable over the same ten-minute window, and at least five hundred requests are required before any decision.

3

Design the pipeline

Stages: build, test, publish an immutable image, deploy to staging, deploy the canary with no traffic, then one, five, twenty-five, and fifty percent steps, each followed by a bake and a check, and finally the full promotion. Bake times and approvals sit in stages with no agent.

4

Build a separate rollback job

A small job takes a version and moves all traffic back to it, removing the canary. The team practises it in staging, and once in production during a quiet hour.

5

Make changes compatible

The team adopts expand and contract for database changes, and adds a release checklist question about running both versions against the same data.

6

Add a lock and milestones

A lock allows only one checkout release at a time. A milestone before the release cancels outdated waiting builds, and a second one inside the lock stops any older build that slipped in.

7

Start with manual gates, then automate

For the first month, an engineer approves every step after looking at the comparison dashboard. Once the team trusts the numbers, the small steps become automatic, and only the final move to a hundred percent keeps a human approval.

What happens the next time a bug slips through

A later release again contains a bug that makes six percent of requests fail. This time it reaches only one percent of traffic, which is one hundred requests a minute, so about six failures a minute. After a few minutes, the comparison shows the canary’s error rate far above the stable version’s, the gate fails, and the pipeline moves all traffic back. At most about sixty requests failed in the whole ten-minute bake, and probably fewer. Nobody had to phone anybody at night.

MeasureBefore, big-bang releaseAfter, canary release
Users exposed to a bad release100 percent1 percent at first
Time to notice a problemAbout 45 minutes, from complaintsMinutes, from the comparison gate
Failed requests in the example incidentAbout 27,000At most about 60
Time to undoAbout 10 minutes, by redeployingSeconds to a minute, by moving traffic
Time from merge to full releaseAbout 20 minutesAbout 70 minutes, including bakes
Executors held during waitsWhole releaseNone, since waits have no agent
Everyday analogy

It is like swapping a firm’s annual all-staff software switchover for a pilot in one small office first. The pilot takes longer to reach the whole company, but when it hits a snag, one office of ten people notices, instead of the entire company on a Monday morning.

i
Tip

The numbers here are made up to show the pattern. Use your own traffic and error rates to work out how many users a bad release would reach at each step, and decide the sizes of the steps from that.

21Real-World Usage Patterns

Here is how canary releases tend to appear in real delivery pipelines. These are illustrative patterns in general terms, not claims about the private setups of any particular company.

Jenkins is one of the most widely used automation servers, and canary releases are a common companion to it in organisations that release often. What tends to be common is a habit of starting small, comparing with the stable version, keeping rollback simple, and letting the platform, not Jenkins, do the traffic shaping. The patterns below show that habit in practice.

Pattern: instance-ratio canary on a small platform

A small team runs twenty instances behind a load balancer. The pipeline replaces one instance with the new version, watches it for fifteen minutes, then replaces the rest in batches. It is simple, with no special tooling, and gives a five percent canary.

Pattern: weighted routing on a container platform

A team of a hundred engineers uses the platform’s ingress weights. Jenkins deploys the canary and sets weights of one, five, twenty-five, and fifty percent, reading error and latency numbers from the monitoring system at each step.

Pattern: a rollout controller does the shifting

A platform team installs a controller that runs canary steps and metric analysis inside the cluster. Jenkins builds, publishes, and updates the desired version, then waits for the controller to report success or failure.

Pattern: employees first, customers second

A company routes internal users to the canary for a day before any customer. Because stickiness keeps them on the canary, they use it normally and report problems, and the customer canary starts only after that quiet period.

Pattern: canary plus feature flags

A product team ships new features switched off. The canary checks that the new build is healthy with the flags off. Later, the flags are turned on for a small group, separately from the deployment.

i
Note

Jenkins is often used together with Docker, Kubernetes, service meshes, and cloud platforms, which supply the traffic splitting and much of the health checking. The best results come when each tool does what it is best at: Jenkins runs the process, the platform shifts traffic, and monitoring gives the truth.

22Frequently Asked Questions

Q1What is a canary deployment in one sentence?
It is a release method that sends a new version to a small share of real users first, compares its health with the stable version, and only widens the release if the comparison looks good.
Q2Can Jenkins do a canary deployment by itself?
Jenkins orchestrates the steps, but it does not split traffic or collect metrics. You need a traffic layer, such as a container platform, a service mesh, or a load balancer, and a monitoring system, with Jenkins coordinating them.
Q3How is a canary different from blue-green?
Blue-green runs two full environments and switches all traffic at once. A canary sends a small, growing share of traffic to the new version. A canary limits exposure during the release, while blue-green gives a fast switch and switch-back.
Q4How big should the first step be?
Small enough that a serious bug affects few people, and large enough to gather meaningful data. One to five percent is common, and higher-risk services may start lower. Low-traffic services may need a larger share or a longer bake.
Q5What should I measure?
The four golden signals of latency, traffic, errors, and saturation, compared between the canary and the stable version, plus restarts, log checks, and one or two business metrics such as completed orders.
Q6How long should each step last?
Long enough to collect enough requests to judge, and to show problems that take some time to appear. Ten to fifteen minutes is a common starting point, with a longer watch after full rollout for slow-burn faults.
Q7Should approvals be manual or automatic?
Many teams start manual while they learn what matters, then automate the early, small steps and keep a person for the final move to everyone. Whichever you choose, add timeouts and make the approver look at real numbers.
Q8How do I wait during the bake without holding a build machine?
Put the wait and the approval in stages that have no agent, guarded by timeouts. The pipeline then waits on the lightweight controller side, and executors are used only for short commands.
Q9What happens to the database during a canary?
Both versions use the same database at once, so changes must be backward compatible. Use the expand and contract approach: add new structures first, release, and remove old ones in a later release.
Q10How do I stop two releases from clashing?
Use a lock so only one release per service runs at a time, and milestones so older builds are cancelled when a newer one passes. Also make sure only one tool controls the traffic weights.
Q11What if a canary passes but the full release fails?
Some problems only appear at scale or over time. Keep the old version and its artifact ready, watch closely after reaching a hundred percent, use larger steps for the final stages, and keep rollback simple and practised.
Q12Is a canary worth it for a small team?
If you can split traffic and measure health, even a simple version, such as one instance in twenty, gives real protection. If you cannot, focus first on tests, monitoring, and fast rollback, and add the canary when those are in place.

23Summary and Key Takeaways

Key Takeaways

  • A canary releases to a few users first. A small share of traffic goes to the new version, and the rest stays on the stable one, so a mistake reaches few people.
  • Jenkins conducts, other tools play. Jenkins builds, publishes, deploys, waits, decides, and rolls back, while a traffic layer splits requests and a monitoring system supplies the numbers.
  • Compare, do not just measure. Judge the canary against the stable version at the same time, using latency, errors, saturation, and a business metric, with enough data to be sure.
  • Make rollback fast and practised. Move the traffic back first, then remove the canary, and keep the previous artifact ready in the repository.
  • Keep two versions compatible. Change data in expand and contract steps, so both versions work against the same database at every moment.
  • Wait cheaply and safely. Place bake times and approvals outside agent blocks, add timeouts, make steps safe to repeat, and use a lock and milestones so only the newest change rolls out, one at a time.
  • Guard the power to release. Restrict who can release and approve, keep deployment credentials narrow, deploy immutable artifacts by exact version, and record every release and rollback.