Distributed CI Using Azure Pipelines
Nx is a set of smart and extensible build framework, and it works really well with monorepos. Monorepos provide a lot of advantages:
- Everything at that current commit works together. Changes can be verified across all affected parts of the organization.
- Easy to split code into composable modules
- Easier dependency management
- One toolchain setup
- Code editors and IDEs are "workspace" aware
- Consistent developer experience
- ...
But they come with their own technical challenges. The more code you add into your repository, the slower the CI gets.
Example Workspace
This repo is an example Nx Workspace. It has two applications. Each app has 15 libraries, each of which consists of 30 components. The two applications also share code.
If you run nx dep-graph
, you will see something like this:
CI Provider
This example will use Azure Pipelines, but a very similar setup will work with CircleCI, Jenkins, GitLab, etc..
To see CI runs click here.
Baseline
Most projects that don't use Nx end up building, testing, and linting every single library and application in the repository. The easiest way to implement it with Nx is to do something like this:
1jobs:
2 - job: ci
3 timeoutInMinutes: 120
4 pool:
5 vmImage: 'ubuntu-latest'
6 steps:
7 - template: .azure-pipelines/steps/install-node-modules.yml
8 - script: yarn nx run-many --target=test --all
9 - script: yarn nx run-many --target=lint --all
10 - script: yarn nx run-many --target=build --all --prod
This will retest, relint, rebuild every project. Doing this for this repository takes about 45 minutes (note that most enterprise monorepos are significantly larger, so in those cases we are talking about many hours.)
The easiest way to make your CI faster is to do less work, and Nx is great at that.
Building Only What is Affected
Nx knows what is affected by your PR, so it doesn't have to test/build/lint everything. Say the PR only touches ng-lib9
. If you run nx affected:dep-graph
, you will see something like this:
If you update azure-pipelines.yml
to use nx affected
instead of nx run-many
:
1jobs:
2 - job: ci
3 timeoutInMinutes: 120
4 pool:
5 vmImage: 'ubuntu-latest'
6 steps:
7 - template: .azure-pipelines/steps/install-node-modules.yml
8 - script: yarn nx affected --target=test --base=origin/master
9 - script: yarn nx affected --target=lint --base=origin/master
10 - script: yarn nx affected --target=build --base=origin/master --prod
the CI time will go down from 45 minutes to 8 minutes.
This is a good result. It helps to lower the average CI time, but doesn't help with the worst case scenario. Some PR are going to affect a large portion of the repo.
You could make it faster by running the commands in parallel:
1jobs:
2 - job: ci
3 timeoutInMinutes: 120
4 pool:
5 vmImage: 'ubuntu-latest'
6 variables:
7 IS_PR: $[ eq(variables['Build.Reason'], 'PullRequest') ]
8 steps:
9 - template: .azure-pipelines/steps/install-node-modules.yml
10 - script: yarn nx affected --target=test --base=origin/master --parallel
11 - script: yarn nx affected --target=lint --base=origin/master --parallel
12 - script: yarn nx affected --target=build --base=origin/master --prod --parallel
This helps but it still has a ceiling. At some point, this won't be enough. A single agent is simply insufficient. You need to distribute CI across a grid of machines.
Distributed CI
To distribute you need to split your job into multiple jobs.
/ lint1
Prepare Distributed Tasks - lint2
- lint3
- test1
....
\ build3
Distributed Setup
The distributed_tasks
job figures out what is affected and what needs to run on what agent.
1jobs:
2 - job: distributed_tasks
3 pool:
4 vmImage: 'ubuntu-latest'
5 variables:
6 IS_PR: $[ eq(variables['Build.Reason'], 'PullRequest') ]
7 steps:
8 - template: .azure-pipelines/steps/install-node-modules.yml
9 - powershell: echo "##vso[task.setvariable variable=COMMANDS;isOutput=true]$(node ./tools/scripts/calculate-commands.js $(IS_PR))"
10 name: setCommands
11 - script: echo $(setCommands.COMMANDS)
12 name: echoCommands
Where calculate-commands.js
looks like this:
1const execSync = require('child_process').execSync;
2const isMaster = process.argv[2] === 'False';
3const baseSha = isMaster ? 'origin/master~1' : 'origin/master';
4
5// prints an object with keys {lint1: [...], lint2: [...], lint3: [...], test1: [...], .... build3: [...]}
6console.log(
7 JSON.stringify({
8 ...commands('lint'),
9 ...commands('test'),
10 ...commands('build'),
11 })
12);
13
14function commands(target) {
15 const array = JSON.parse(
16 execSync(`npx nx print-affected --base=${baseSha} --target=${target}`)
17 .toString()
18 .trim()
19 ).tasks.map((t) => t.target.project);
20
21 array.sort(() => 0.5 - Math.random());
22 const third = Math.floor(array.length / 3);
23 const a1 = array.slice(0, third);
24 const a2 = array.slice(third, third * 2);
25 const a3 = array.slice(third * 2);
26 return {
27 [target + '1']: a1,
28 [target + '2']: a2,
29 [target + '3']: a3,
30 };
31}
Let's step through it:
The following defines the base sha Nx uses to execute affected commands.
1const isMaster = process.argv[2] === 'False';
2const baseSha = isMaster ? 'origin/master~1' : 'origin/master';
If it is a PR, Nx sees what has changed compared to origin/master
. If it's master, Nx sees what has changed compared to the previous commit (this can be made more robust by remembering the last successful master run, which can be done by labeling the commit).
The following prints information about affected project that have the needed target. print-affected
doesn't run any targets, just prints information about them.
1execSync(`npx nx print-affected --base=${baseSha} --target=${target}`)
2 .toString()
3 .trim();
The rest of the commands
splits the list of projects into three groups or bins.
Other Jobs
Other jobs use the information created by distributed_tasks
to execute the needed tasks.
1- job: lint1
2 dependsOn: distributed_tasks # this tells lin1 to wait for distributed_tasks to complete
3 condition: |
4 and(
5 succeeded(),
6 not(contains(
7 dependencies.distributed_tasks.outputs['setCommands.COMMANDS'],
8 '"lint1":[]'
9 ))
10 )
11 pool:
12 vmImage: 'ubuntu-latest'
13 variables:
14 COMMANDS: $[ dependencies.distributed_tasks.outputs['setCommands.COMMANDS'] ]
15 steps:
16 - template: .azure-pipelines/steps/install-node-modules.yml
17 - script: node ./tools/scripts/run-many.js '$(COMMANDS)' lint1 lint
where run-many.js
:
1const execSync = require('child_process').execSync;
2
3const commands = JSON.parse(process.argv[2]);
4const projects = commands[process.argv[3]];
5const target = process.argv[4];
6execSync(
7 `npx nx run-many --target=${target} --projects=${projects.join(
8 ','
9 )} --parallel`,
10 {
11 stdio: [0, 1, 2],
12 }
13);
Artifacts
This example doesn't do anything with the artifacts created by the build, but often you will need to upload/deploy them. There are several ways to handle it.
- You can create a job per application and then copy the output to the staging area, and then once tests complete unstage the files in a separate job and then deploy them.
- You can use the outputs property from running
npx nx print-affected --target=build
to stash and unstash files without having a job per app.
1{
2 "tasks": [
3 {
4 "id": "react-app:build",
5 "overrides": {},
6 "target": {
7 "project": "react-app",
8 "target": "build"
9 },
10 "command": "npx nx -- build react-app",
11 "outputs": [
12 "dist/apps/react-app"
13 ]
14 },
15 {
16 "id": "ng-app:build",
17 "overrides": {},
18 "target": {
19 "project": "ng-app",
20 "target": "build"
21 },
22 "command": "npx nx -- build ng-app",
23 "outputs": [
24 "dist/apps/ng-app"
25 ]
26 }
27 ],
28 "dependencyGraph": {
29 ...
30 }
31}
Improvements
With these changes, rebuild/retesting/relinting everything takes only 7 minutes. The average CI time is even faster. The best part of this is that you can add more agents to your pool when needed, so the worst-case scenario CI time will always be under 15 minutes regardless of how big the repo is.
Can We Do Better?
This example uses a fixed agent graph. This setup works without any problems for all CI providers. It also scales well for repo of almost any size. So before doing anything more sophisticated, I'd try this approach. Some CI providers (e.g., Jenkins) allow scaling the number of agents dynamically. The print-affected
and run-many
commands can be used to implement those setups as well.
Summary
- Rebuilding/retesting/relinting everything on every code change doesn't scale. In this example it takes 45 minutes.
- Nx lets you rebuild only what is affected, which drastically improves the average CI time, but it doesn't address the worst-case scenario.
- Nx helps you run multiple targets in parallel on the same machine.
- Nx provides
print-affected
andrun-many
which make implemented distributed CI simple. In this example the time went down from 45 minutes to only 7