Video in progress

Strong Middle 🌿 Git

A monorepo has 40 services, and every PR builds the whole project, so CI takes 50 minutes. How do you speed it up at the Git and CI level?

The main idea is to build and test only what changed: find the affected modules with git diff and run them together with their dependents. On top of that: shallow/partial clone, sparse-checkout and a build cache.

📖 Answer

The first step is to find which modules changed:

git fetch --no-tags --depth=50 origin main
BASE=$(git merge-base origin/main HEAD)
git diff --name-only "$BASE"...HEAD | cut -d/ -f1-2 | sort -u

Then in Maven, only those modules and the ones that depend on them:

./mvnw -B -pl services/billing,libs/money -amd verify

-amd (also-make-dependents) matters: if libs/money changes, the services that use it are checked too. In Gradle, the build cache and configuration cache do a similar job more efficiently. In big monorepos, tools like Bazel or Nx compute the dependency graph themselves.

On the Git side:

  • git clone --filter=blob:none (partial clone): the history comes, but old file contents are downloaded only when needed;
  • a shallow clone with --depth in CI, but leave enough depth for the merge-base to be found, otherwise the diff shows the whole repository as "changed";
  • git sparse-checkout set services/billing libs: a developer keeps only their own part on disk.

Traps: if shared files in the root (pom.xml, .github/, the BOM) change, you need a full build, so add that rule to the script. And run a full build once a night anyway: a bug in the "affected" logic can let hidden breakages slip through.