High Availability (HA) controllers run as multiple replicas that synchronize state, adopt each other’s Pipeline builds, and coordinate agent connections. These internals matter for advanced troubleshooting, support, and plugin development. For an introduction to HA capabilities and a high-level architecture diagram, refer to High Availability (active/active) fundamentals.
Architecture overview
The following diagrams compare a controller that is not running in HA mode with an HA controller that runs multiple replicas under normal conditions.
Non-replicated architecture
In a non-replicated architecture, web traffic reaches a single controller instance, optionally through a load balancer. The instance reads from and writes to a file system.
Replicated architecture
In a replicated architecture, a load balancer is required to distribute the traffic across the replicas.
Because replicas run on different machines, $JENKINS_HOME must be stored on a shared file system so that every replica has the same view of the data.
Hazelcast synchronizes parts of the live state between running replicas, such as HTTP sessions and information about which replica owns each running build. It provides replicated data structures that allow the replicas to remain in sync.
HA implementation
Most HA-specific functionality is implemented in a Cloudbees High Availability (Active/Active) plugin. It implements a number of extension points and other hooks to customize many Jenkins functions. In certain cases, special "beta" APIs, such as extension points, are defined in Jenkins core, Remoting, Stapler, or certain foundational plugins. These APIs allow HA to work without the need to maintain extensive patches to Jenkins code.
A custom servlet listener packaged in the Cloudbees CI WAR file implements a few specialized behaviors that must run before Jenkins starts. For example, the servlet listener ensures that only one replica of a given controller is allowed to start at a time. The servlet listener is packaged for both Kubernetes and traditional platforms.
The implementation also packages and customizes Jetty’s distributed session clustering system based on Hazelcast.
Setup wizard
When a controller running in HA mode starts for the first time, one of the controller replicas acquires a lock in the shared $JENKINS_HOME.
This replica is the only one available, and the lock remains while the setup wizard is active, even after Jenkins initialization is complete.
When the setup wizard is finished, the remaining replicas continue the startup process. During this process, the remaining replicas automatically acquire the lock, start, and release the lock one by one until all of them are available.
However, if the controller is created using a Configuration as Code (CasC) bundle, the setup wizard is not displayed, and all the replicas automatically follow the same process described above without any human confirmation. One by one, they acquire the lock, start, and release the lock until all of them are up and running.
Horizontal scaling
A controller runs as multiple replicas that share UI traffic and distribute workloads. The UI is eventually consistent between replicas.
All persistent state continues to be kept in the $JENKINS_HOME file system in the same format as in a non-HA controller.
Since multiple replicas access this file system concurrently, you must use a network file system, typically NFS.
File collisions
Only one replica of a given controller is permitted to start at a time; others wait until the first replica finishes. This serializes startup when several replicas are scheduled at once, for example after a scale-up event or a crash, or when Kubernetes is configured to add multiple pods at once. The same applies on traditional platforms. This mutual exclusion, implemented in a WAR hook, avoids possible file corruption from startup code.
After startup, all replicas use $JENKINS_HOME concurrently and must avoid clashes.
The layout of $JENKINS_HOME is mostly unchanged compared to a single-replica controller.
There are a few folders inside $JENKINS_HOME that are HA-specific, such as those holding per-replica queue information or stored logs used in support bundles.
These folders are only written by a single replica or otherwise kept distinct.
Some other folders, such as caches, do not need to be shared between replicas and are kept on a temporary volume.
This is an option for non-HA controllers but mandatory for HA controllers.
For both types of folders, the location is configured by system properties. Some of those properties are automatically set by the HA servlet listener. For deployments on traditional platforms, you must set others yourself; for deployments on Kubernetes, the startup script in the image sets them. The same applies to some Winstone (Jetty) options for caching unpacked WAR files and plugin archives. To configure these properties and options on traditional platforms, refer to Install the HA controllers.
Kubernetes deployments
For Kubernetes installations, managed controllers can be configured in the UI or CasC with a replica count of one or more.
A non-HA managed controller creates a StatefulSet.
An HA managed controller creates a Deployment with one or more replicas instead.
The replica count may be managed using Horizontal Pod Autoscaling (HPA) to dynamically adjust to load.
Restart gestures from inside the controller trigger a Kubernetes rolling restart. This typically increases the replica count temporarily by one as pods are replaced. With a count of one, a rolling restart ensures availability for controllers that do not otherwise require scaling. Administrators can also initiate a rolling restart from operations center and view its progress.
All changes to managed controller configuration affecting just the Deployment specification trigger an immediate rolling restart.
A non-HA controller requires a Reprovision gesture, which entails a loss of availability.
If there is a change to the container image (Cloudbees CI version), the event is known specifically as a rolling upgrade, which triggers some additional behaviors described in Rolling upgrades.
Hazelcast
Hazelcast runs embedded in the Jenkins JVM to enable replicas to coordinate in various ways. The client library is bundled in the Cloudbees High Availability (Active/Active) plugin, which is the only component that uses it. The protocol is peer-to-peer, with no distinguished "leader" replica. Internally, Hazelcast assigns slices of data structures to cluster members, but this is mostly transparent to the application except for timing considerations. Where Cloudbees CI functionality requires a single replica to perform some task or maintain some socket, the plugin picks one replica for that purpose arbitrarily or according to some simple heuristic.
Cloudbees CI uses the OSS Hazelcast Community Edition, not the Hazelcast Enterprise Edition. While the Hazelcast OSS project and Enterprise product support numerous features, the plugin deliberately uses only a few of the core capabilities. For example, it does not use the CP subsystem. The plugin mainly uses the distributed data structures (maps and queues) and the corresponding listeners to detect changes in these structures or changes in the membership of the cluster. The distributed execution service is also used for some purposes, such as asking another replica to run a specific task. The Jetty servlet container’s session clustering is also implemented using Hazelcast.
The Hazelcast Enterprise Edition persistence feature is not used. The file system remains the source of truth for all valuable data. As long as at least one replica remains running, the cluster state is maintained. If all replicas are restarted, the Hazelcast cluster is reconstituted from scratch. The plugin errs on the side of availability rather than consistency, so it supports "split brain" scenarios only on a best-effort basis.
The Hazelcast cluster is not statically preconfigured via XML or YAML; data structures are created dynamically as needed.
Session management
The load balancer is asked to make sessions sticky. This ensures consistency while browsing the instance, since replicas are eventually consistent.
Hazelcast is additionally used to cluster sessions across replicas, so that you do not need to sign in again after a replica exits. The session object is stored in a distributed map that is replicated across nodes of the Hazelcast cluster. The built-in Jetty servlet container is configured to use this map as a session store, and other containers are not supported in HA mode. The Jenkins cross-site request forgery (CSRF) defense crumb is compatible with the distributed session and load balancer.
Persisted objects
Various persisted objects are automatically synchronized across replicas, most notably:
-
Itemobjects, when created, updated, or deleted. -
Runobjects, only when complete (refer to Builds). -
Userobjects, only when updated. -
Any configuration backed by a
Descriptor, when created, updated, or deleted.
When a change to an XML file corresponding to such an object inside $JENKINS_HOME is made on one replica, a message is sent to other replicas prompting them to reload from disk.
The actual file content is not transmitted over Hazelcast, only the relative file path.
Since some file systems, such as Amazon Elastic File System (Amazon EFS), are only eventually consistent, the message includes the timestamp of the actual change; other replicas wait, up to a limit, until they also observe a change at least as new.
Replicas also track the checksums of XML files to avoid sending notifications when a save did not in fact change the file.
Builds
Each Pipeline build is owned by one replica, and this association is recorded in a map in Hazelcast. A simple "heartbeat" algorithm is used to indicate that the owner still lives, by repeatedly touching this map entry. If the owner shuts down gracefully, it proactively offers the build for adoption by another replica. Another live replica that currently has the least load immediately adopts the build. If the owner crashes, another replica detects an expired heartbeat and adopts the build after a few minutes. The build is resumed according to the saved program state, similar to a simple Jenkins restart. Adoption is only possible for Pipeline builds, not for Freestyle builds, as with non-HA restarts.
The owning replica also maintains a file lock in the build directory as a safeguard to prevent concurrent modifications by other replicas in case Hazelcast-based ownership tracking fails for any reason. A replica attempting to adopt a build must acquire the lock before proceeding.
The definitive state of a build is stored in the file system underneath a single directory in the usual format. This includes:
-
The log file, except when you archive Pipeline build logs with Cloudbees Pluggable Storage. For more information, refer to Archive Pipeline build logs with Cloudbees Pluggable Storage.
-
The
build.xmlfile. -
XML files for each step.
-
A
program.datfile with the serialized program state. -
Other files, depending on usage.
In an HA controller, you must set the Default Speed/Durability Level option to Maximum survivability/durability but slowest, which ensures that all metadata changes are written to disk and flushed at every checkpoint.
Controllers use this value by default.
For more information, refer to Audit your jobs for compatibility with High Availability (active/active).
As in Jenkins generally, some live information is also kept on agents. There is no special HA logic for agents beyond what Pipeline normally offers:
-
If an agent remains running but the Remoting connection is lost, the agent reconnects automatically and resumes its work without loss.
-
If the agent as a whole is lost, the
nodestep fails and might be retried. -
A running
nodeblock may be resumed without loss after a build adoption, like a controller restart without HA.
For performance reasons, HA controllers enable a "push" mode for steps such as sh.
In this mode, the log text is streamed to the controller rather than the controller polling the agent for updates.
At the Jenkins API level, a replica only has a WorkflowRun object if the build is completed or owned by this replica.
The build history widget and other higher-level UI elements present an aggregate view based on information from Hazelcast.
REST API requests for the list of builds for a given job are automatically intercepted and replaced with an aggregated list.
Any Jenkins core or plugin features that rely on the existence or details of a Run in project history do not work correctly if the build is owned by another replica unless specifically overridden.
Once a build completes, all replicas are permitted to load it, but are not proactively asked to do so.
The cluster allocates the next build number atomically, rather than trusting the nextBuildNumber used for non-HA controllers.
When a build is transferred to another replica, the agent should reconnect to it. You can write the Pipeline to tolerate bugs in this logic and many classes of infrastructure error by using a special retry mode.
The set of running Pipeline builds is kept in Hazelcast and also persisted to disk. In case of a full cluster restart, this list is loaded from disk, and builds resume incrementally on the replica with the least load, up to any configured limit on the total controller load.
Internal reverse proxying
For certain Jenkins features, it is not possible to predict which replica is able to handle a request. Mainly this applies to HTTP(S) requests from the load balancer (ingress). This can also apply to WebSocket requests on the same port, and even TCP connections from non-WebSocket agents.
In a few cases, it is possible to request the client to connect directly to a particular replica. For example, a TCP inbound agent running in the same LAN, such as a cluster, is directed to the IP address of the replica that owns the associated build. This is done by overriding the headers in the HTTP handshake used to prepare for the real connection.
For other cases, a connection is made to some load balancer, whether the L7 reverse proxy used for HTTP(S) and WebSocket, or sometimes an L4 load balancer for TCP agents running in another network. If the replica handling the request can handle it, it does so. However, the request cannot be handled locally if the connection pertains to:
-
An agent needed for a specific build.
-
A running build that is owned by another replica.
-
Certain other cases related to rolling upgrades.
In these cases, the replica acts as a reverse proxy to the replica that can handle the request. There are three types of reverse proxies implemented in the plugin: HTTP(S), WebSocket, and (agent) TCP. The initial replica looks up the IP address of the target replica based on information in Hazelcast, and then forwards the request to that replica.
HTTP(S) requests are short-lived, and so the reverse proxy collects the headers and body, makes a corresponding request to the target replica, and forwards the response headers and body. Agent WebSocket and TCP connections are long-lived, and so the reverse proxy must maintain a connection to the target replica. If the connection is dropped, the client attempts to reconnect and is directed to an arbitrary replica by the load balancer.
If the HTTP port exposed by the controller is plain text (HTTP) rather than encrypted (HTTPS), which is mandatory in the Kubernetes environment, the internal reverse proxy correspondingly uses a plain-text connection to the target replica. Any encryption applied by a service mesh would be transparent to the application. On traditional platforms, the controller commonly terminates TLS, sometimes with a certificate distinct from the load balancer certificate. In that case, the internal reverse proxy makes an HTTPS connection to the target replica. It uses the same certificate as its own termination point, adds the corresponding certificate authority to its trust store, and sets the Subject Alternative Name (SAN) header on the request. The same encryption considerations apply to WebSocket connections. For TCP connections, bespoke logic in the agent protocol handles the TLS encryption, and the internal reverse proxy forwards the TCP packets opaquely. It does use an extension to the agent protocol to indicate the name of the agent outside the TLS envelope, so the correct target replica can be selected.
Agents
The Hazelcast cluster tracks which, if any, replica is currently using a given agent. The Remoting protocol is only able to communicate between one agent JVM and one controller (replica) JVM at a time, so an HA controller must ensure that only one replica is using a given agent.
Permanent agents
Permanent agents, whether outbound or inbound (using TCP or WebSocket), are supported.
Permanent agents are connected to a single replica at a time, though all replicas can load the Slave object.
An ownership lock is stored in Hazelcast to ensure only one replica at a time can use a given permanent agent.
Inbound logic
When idle, an inbound permanent agent initially connects to an arbitrary replica.
A Kubernetes Service, an ingress or reverse proxy, or another load balancer picks the replica, depending on the transport type (TCP or WebSocket) and the network configuration.
If a replica has a node step or Freestyle build blocked waiting for an agent with a certain name or label, and a matching inbound permanent agent is attached to another replica and idle, that replica is asked to disconnect.
After the usual reconnection delay of a few seconds, the agent should be guided to reconnect to the replica that needed it.
This does not occur when the agent is already in use.
HA controllers only support agents with one executor, so an agent is either disconnected, connected but idle, or in use by one build.
If a build requests a label and an agent with that label is already connected to the build’s replica, the build can run immediately.
Outbound logic
When you configure permanent outbound agents, you must select Cloudbees High Availability (outbound agents) for the retention strategy. This strategy keeps the agent disconnected when idle. When needed, it runs the agent’s launcher on the current replica, like the Bring this agent online when in demand, and take offline when idle Jenkins strategy, but only if no other replica is using the agent. For instructions, refer to Configure a permanent agent manually from the UI.
Multiple executors
Only agents with a single executor are supported. Attempting to manage a multi-executor agent would dramatically complicate the connection logic. It might even introduce a deadlock, for example if two replicas each run a build, and each build already uses one executor on each of two agents.
Cloud agents normally define only a single executor anyway.
Multi-executor permanent agents running on large computers, typically VMs, can be reconfigured as multiple agents at the expense of a larger number of running JVMs.
To make it easier to do this, you can configure a permanent agent with the HA agent with multiple executors option.
The controller then automatically adds, removes, or reconfigures read-only clones of the original agent, all of which have one executor and use a subdirectory for the agent home.
An outbound launcher automatically has any -workDir settings adjusted accordingly.
For the inbound launcher, the primary agent detects its own launch arguments and starts clones inside the same JVM.
For instructions, refer to Configure permanent agents as multi-executor agents for HA.
Cloud agents
Like permanent agents, cloud agents are connected to only one replica at a time: the owner of the associated build.
Unlike with permanent agents, only that replica is permitted to load the Slave object into memory.
Agent reconnection
The agent-to-controller connection is point-to-point, so if a replica dies, the remaining replicas arrange for the agent to reconnect to another replica, the new owner. This ensures build continuity. The actual process differs depending on the launch method, as follows.
Inbound TCP reconnection
A mapping is kept in Hazelcast from (agent) nodes to IP addresses and TCP ports. When an agent is defined, the IP address and port of the current replica are recorded. When a build is resumed, any agents listed in its Pipeline step history are updated with the IP address of the now-current replica.
Unlike in "direct" mode, which is not recommended for HA, the agent in its default mode starts by making an HTTP request to the controller to find a host and port to use for the actual TCP connection.
The /tcpSlaveAgentListener/ endpoint expects to receive an HTTP header with the node name, which the agent includes in its preparatory request.
The endpoint serves host and port headers in its response corresponding to the recorded owner IP and port rather than the default response of the IP and port of the responding replica.
HA also supports connecting an inbound TCP agent through a load balancer.
For example, you can set allowExternalAgents: true to create a NodePort service, or specify the tcp configuration section to the ingress-nginx chart.
Typically, you configure the tunnel option on the inbound launcher in this case.
In this mode, the agent may initially connect to an arbitrary replica.
If another replica owns the agent, a reverse proxy is established to the owner.
This system relies on a special Remoting transport, JNLP4-connect-proxy, with the client side implemented in the standard agent.jar and the server side in the Cloudbees High Availability (Active/Active) plugin.
Inbound WebSocket reconnection
Similar to inbound TCP agents, a mapping is kept from agent nodes to IP addresses of owning replicas.
When an agent connects to /wsagents/ on a replica other than the owner of the node, the receiving replica serves as a WebSocket reverse proxy to the owning replica.
As a special optimization, a Kubernetes agent from a cloud using WebSocket transport with an overridden Jenkins URL can connect directly to the owning replica. Overriding the URL is the typical setup for agents running in a different cluster than the controller. Connecting directly to the owning replica avoids the overhead, latency, and possible instability of the WebSocket reverse proxy. This optimization is possible when the load balancer (ingress) is configured with sticky sessions, by sniffing the session cookies for all replicas and configuring new pods to set this cookie. An existing agent may also be asked to disconnect after adding the cookie header to its reconnection options.
Agent and executor display
A custom widget displays agents and their executors across all replicas. Selecting an online agent forwards the resulting page to the replica to which it is connected. REST API requests for the list of agents are automatically intercepted and replaced with an aggregated list.
Queue
There is no distributed queue, and each replica maintains its own queue persistence file.
Any outstanding queue items left behind by a terminated replica are picked up by another one automatically.
For Pipeline, this includes top-level queue items for the project as a whole, and node blocks from particular build stages that have not yet started.
Top-level queue items are typically only relevant for a project configured to disable concurrent builds.
If only cloud agents are used, the local queue suffices. This includes Cloudbees CI shared agents, which from the controller perspective are a kind of cloud. The replica running a build creates an agent, establishes a connection, uses the agent, and then deletes it.
If permanent agents are used, other hooks are activated to ensure the agent connects to the appropriate replica when needed. A replica can post a request for an agent matching some label, and another replica can post an offer to transfer an agent to it.
A custom widget displays the state of the queue across all replicas.
Load balancing
The load factor for each replica is the sum of the number of running builds, items in queue, and executors.
When a build is triggered, a queue item is initially added to one of the replicas, typically the one that processed the event that triggered the build. However, the build is not necessarily run on this replica. If the build cause belongs to an allowlist of causes that are compatible with load balancing, a new queue item with the same ID is created on the least loaded replica at that time. The initial queue item is discarded.
Whether a cause is compatible with HA depends on whether the trigger looks at the build result or not.
For example, a build triggered by a webhook can be load balanced, because the HTTP response only reports that the build was scheduled and, at most, its queue ID.
By contrast, when you run a build with the Jenkins CLI build command and the options to watch the build progress live, the build runs on the replica that handles the WebSocket CLI connection.
However, the Cloudbees CI triggerRemoteJob step has an asynchronous implementation to follow the build status of the downstream build and is compatible with load balancing.
For more information, refer to Schedule builds and explicit load balancing.
Rolling upgrades
If Jenkins core and/or plugins are upgraded, and not all replicas are restarted together (which would imply a temporary outage), some replicas may temporarily be running different software versions.
This would be the normal case for a Kubernetes Deployment rollout triggered by an update to the container image.
Jenkins code normally strives to be backward-compatible for persisted settings (usually XML formats), but is not always forward-compatible.
If a post-upgrade replica writes some data, a pre-upgrade replica could fail to read it properly.
In practice, such cases are unusual, and the damage is most commonly limited to a warning in Manage Old Data.
However, the situation should be avoided if possible.
A managed controller replica detects whether it was part of an outdated ReplicaSet.
Such replicas are made available for new builds only if no newer replica is available, to avoid starting a build only to have it be adopted a few minutes later.
A Replica scheduled to be replaced warning is also displayed in the footer.
Any replica (even of a client controller) also detects whether its Cloudbees CI version is older than some other replicas. An Outdated replica—avoid configuration changes warning is displayed in the footer, but a reverse proxy is also enabled which redirects all configuration pages to newer replicas. An older replica does not load a build that completed on a newer replica, nor does it try to adopt a build last running on a newer replica. An older replica ignores a configuration change saved from a newer replica. A replica also refuses to start if it determines that newer replicas have been running recently.
Taken together, these behaviors make it unlikely that controller code would ever encounter metadata files written by newer versions. The outdated replicas can continue their current work until they are replaced.
Cloudbees CI-specific features
Several Cloudbees CI-specific features depend on the connection between operations center and a controller. In an HA controller, only one replica holds this connection at a time, so these features use mechanisms such as making HTTP calls to operations center, relaying messages between replicas, and reverse proxying to the connected replica.
Remoting connection to operations center
For each controller, a single replica is connected to operations center via the Remoting protocol at a given time. When the replica holding the channel exits, another replica establishes a connection to operations center.
The Cloudbees CI notification system used for a variety of features is supported to the extent that any replica can send a message, though only the connected replica processes incoming messages. When operations center is online, messages can be sent to and from replicated controllers.
HTTP-based APIs
Features that once required a Remoting call through the channel now use HTTP calls to operations center; thus any replica can contact operations center directly.
The request and response pass arguments and return values as XStream-serialized XML.
A 200 response code is expected.
Any foreseeable error conditions are explicitly encoded in the response object.
When establishing a channel between operations center and a controller, operations center retrieves the controller’s public key.
Then a controller authenticates to operations center over HTTP using JSON Web Tokens (JWTs) signed by the controller’s private key.
The controller identifies itself using the idName field allocated by operations center when the controller item was created.
Messaging
The Cloudbees CI messaging system, related to notifications, is supported to the extent that any replica can send a message. However, only the connected replica receives inbound messages.
Additionally, the persistence layer of the messaging system uses Hazelcast instead of MapDB. This provides persistence of the messaging inbox and outbox as long as at least one replica is running.
Publish/trigger on event
This feature relies on the Cloudbees CI notification system as well as the messaging system to operate. Replicas not directly connected to operations center via Remoting can use the notification system as usual, and their events are forwarded via the connected replica. The connected replica processes inbound events, and builds triggered using this method can be load balanced.
Trigger remote job
The triggerRemoteJob step relies on various subsystems provided by operations center:
-
Remote directory listing: This system is used for various purposes, such as the Pipeline syntax snippet generator handling the
triggerRemoteJobstep, or target selection for Move/Copy/Promote. This uses HTTP transport, making it usable from an HA controller. It is also used at the beginning of the remote trigger step to validate that the remote job exists. -
Messaging: Triggering a remote job consists of sending a message to the controller hosting the downstream job with a list of future IDs to use when calling back at various stages of triggering (scheduled/started/completed). When these events occur, other messages are sent back from the controller hosting the downstream job to the controller hosting the upstream job. Since these messages are received on the connected replica, a relay mechanism broadcasts these messages to other replicas as needed.
Move/Copy/Promote
Move/Copy/Promote relies heavily on having a Remoting channel. Therefore, in an HA controller, it uses reverse proxying to ensure that the connected replica is the one handling the request.
Single sign-on
An implementation of single sign-on (SSO) between operations center and controllers based on OpenID Connect (OIDC) works without relying on a Remoting channel.
Hibernation
HA managed controllers may be hibernated when HA and/or horizontal scaling are important at certain times, yet the managed controller is also often idle. The replicas jointly decide when the controller should be considered idle and may be hibernated.