BE·43
Build Systems
Maven and Gradle from first principles: the build as a graph of tasks, dependency resolution, scopes and configurations, plugins, repositories, BOMs and platforms, version catalogs, dependency locking, reproducible builds, build caching, multi-module projects and CI builds. Compared with Cargo, the Go toolchain, CMake and Conan, Bazel, zig build, MSBuild/NuGet and Python's uv.
Start here: what a build tool does for you
The jobs
Chapter 42 built and ran an app with javac, jar and a hand-typed classpath. A real project repeats those steps hundreds of times a day, on every developer's machine and in CI, with hundreds of dependencies. A build tool automates five jobs:
- Fetch dependencies: download the libraries you declare (and their dependencies) from a repository like Maven Central, and pick one version of each.
- Compile your code against them, with the right Java release.
- Test: compile and run the tests, failing the build if any fail.
- Package: produce the JAR, container image or other artifact.
- Do as little as possible: skip steps whose inputs haven't changed, so a one-line change rebuilds in a second, not a minute.
Java's two mainstream tools are Maven (declarative XML, a fixed life cycle, since 2004) and Gradle (a build script in Kotlin or Groovy, a graph of tasks with fine-grained caching, since 2012). Other ecosystems have their own: go build, Cargo, npm with Vite, Python's uv, and Bazel for very large multi-language repositories.
The same project, both ways
<!-- pom.xml (Maven) -->
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>com.cafe</groupId><artifactId>cafe</artifactId><version>1.0.0</version>
<properties><maven.compiler.release>21</maven.compiler.release></properties>
<dependencies>
<dependency><groupId>org.junit.jupiter</groupId><artifactId>junit-jupiter</artifactId><version>6.0.0</version><scope>test</scope></dependency>
</dependencies>
</project>
// build.gradle.kts (Gradle)
plugins { application }
application { mainClass = "com.cafe.Main" }
tasks.withType<JavaCompile> { options.release = 21 }
dependencies { testImplementation("org.junit.jupiter:junit-jupiter:6.0.0") }
Both rely on the same convention: sources in src/main/java, tests in src/test/java, resources in src/main/resources, output in target/ (Maven) or build/ (Gradle). Follow the convention and the build file stays tiny. Dependencies are named by coordinates, group:artifact:version, and a scope or configuration says where they're needed: test dependencies never reach the production JAR, and implementation dependencies don't leak to projects that depend on yours.
The everyday commands: mvn verify or gradle build (compile, test, package), mvn dependency:tree or gradle dependencies (see what was resolved and why), mvn clean/gradle clean (start over). Use the wrapper checked into the project (./mvnw, ./gradlew) so everyone and CI run the same tool version.
Doing less: incremental builds
A project with 400 classes, built with Gradle:
clean build: > Task :compileJava [5598 ms]
run again, nothing changed: > Task :compileJava UP-TO-DATE [1139 ms]
edit one method body: > Task :compileJava Incremental compilation of 3 classes
touch every source file without editing: > Task :compileJava UP-TO-DATE
Gradle fingerprints each task's inputs (source contents, classpath, compiler settings) and outputs. If nothing changed, the task is skipped; if a little changed, its incremental Java compiler works out which classes are affected and recompiles only those. Because it compares contents, touching files without changing them does nothing. Classic make compares timestamps, so it rebuilt everything after the same touch:
$ make → javac -d out com/cafe/*.java
$ make → make: 'out/com/cafe/Main.class' is up to date.
$ touch com/cafe/Prices.java && make → javac -d out com/cafe/*.java
Why you shouldn't compile by hand
Here's a bug a build tool prevents. Main prints a constant from Prices. Change the constant, recompile only Prices.java, and run:
GST 5%, service charge 10% ← before
GST 5%, service charge 12% ← after changing both to 18% and 12% and recompiling Prices only
The method call picked up the new value; the constant didn't, because javac copies static final primitive and string constants into every class that uses them. Main.class still contains the text GST 5%. Gradle's incremental compiler knows this and recompiled Main too when the same change was made in the Gradle project (lab experiment 2). Hand-run partial compiles, IDE quirks and stale build directories produce exactly this kind of "impossible" bug; a clean build in CI is the arbiter.
How deep to go in build systems
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.
| Level | What you can do |
|---|---|
| L1 | Run builds and tests with the wrapper; add a dependency |
| L2 | Structure multi-module builds; use scopes/configurations, BOMs and plugins |
| L3 | Explain Maven's life cycle and resolution, Gradle's task graph, incremental compilation, build and configuration caches, and other ecosystems' tools |
| L4 | Diagnose slow, flaky or non-reproducible builds and stale outputs from build scans and logs |
| L5 | Design build conventions (convention plugins, version catalogs, caching, CI integration) for many projects |
| L6 | Choose and migrate build systems for an organisation (Maven, Gradle, Bazel) |
What a build system does
Jobs and models
Every build system answers the same questions:
- What are the inputs? Source files, resources, dependencies (with versions), tool versions, configuration.
- What are the steps? Compile, process resources, generate code, test, package, publish.
- In what order? Steps form a directed acyclic graph (DAG): packaging needs compiled classes, which need generated sources.
- What can be skipped? If a step's inputs haven't changed, reuse its outputs (incremental builds, caching).
- Is the result reproducible? The same inputs should give the same outputs on any machine.
Two philosophies:
- Convention-based lifecycle (Maven): a fixed sequence of phases; plugins attach goals to phases; configuration is declarative XML. Every Maven project looks the same, which makes it predictable but rigid.
- Programmable task graph (Gradle, Bazel, zig build, Cargo build scripts): you (or plugins) define tasks with declared inputs and outputs; the tool computes the graph and runs only what's needed. Flexible, with the risk of each build becoming a bespoke program.
| Ecosystem | Build tool | Manifest | Lock file | Registry |
|---|---|---|---|---|
| Java/Kotlin | Maven, Gradle (also Bazel, sbt for Scala, Mill) | pom.xml, build.gradle.kts |
Gradle gradle.lockfile; Maven has none natively (pin via dependencyManagement) |
Maven Central, private repos (Nexus, Artifactory, GitHub Packages) |
| Go | go command (built in) |
go.mod |
go.sum (checksums, not a solver lock: MVS is deterministic) |
Module proxy (proxy.golang.org) + checksum DB (sum.golang.org) |
| Rust | Cargo (built in) | Cargo.toml |
Cargo.lock |
crates.io |
| C/C++ | CMake (meta-build generating Ninja/Make/MSBuild), Meson, Bazel, Make; packages via Conan, vcpkg | CMakeLists.txt, conanfile.py |
Conan lockfiles, vcpkg baselines | ConanCenter, vcpkg registry |
| Zig | zig build (build script in Zig) |
build.zig, build.zig.zon |
Hashes in build.zig.zon |
URLs (Git, tarballs) |
| C#/.NET | MSBuild via dotnet CLI |
.csproj, Directory.Packages.props |
packages.lock.json (opt-in) |
NuGet |
| Python | pip, uv, Poetry, Hatch; PEP 517 build backends | pyproject.toml |
uv.lock, poetry.lock |
PyPI |
| JS/TS | npm, pnpm, Yarn + bundlers (Vol. 2 ch. 30) | package.json |
package-lock.json, pnpm-lock.yaml |
npm registry |
The newer languages (Go, Rust, Zig) ship their build tool and package manager with the compiler, with one blessed project layout. That removes a whole category of decisions that Java (Maven or Gradle?) and C++ (CMake? Bazel? Conan or vcpkg?) still impose.
Maven
The project object model
A Maven project is described by its POM (pom.xml). Everything not stated is inherited from the super POM and parent POMs: conventions like src/main/java, src/test/java, target/.
<project xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<parent> <!-- inherit plugin config + dependency versions -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>4.0.1</version>
<relativePath/>
</parent>
<groupId>com.shop</groupId> <!-- coordinates: groupId:artifactId:version (GAV) -->
<artifactId>orders-service</artifactId>
<version>1.5.0-SNAPSHOT</version> <!-- SNAPSHOT = mutable, in-development version -->
<packaging>jar</packaging>
<properties>
<java.version>25</java.version>
<testcontainers.version>1.21.3</testcontainers.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId> <!-- no version: managed by the parent's BOM -->
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId> <!-- repackages into an executable JAR -->
</plugin>
</plugins>
</build>
</project>
Lifecycle, phases, goals and plugins
Maven's default lifecycle is an ordered list of phases. Running a phase runs every phase before it:
validate → initialize → generate-sources → process-sources → generate-resources → process-resources
→ compile → process-classes → generate-test-sources → … → test-compile → test → prepare-package
→ package → pre-integration-test → integration-test → post-integration-test → verify → install → deploy
mvn package: compile, run unit tests, build the JAR.mvn verify: also run integration tests (Failsafe) and quality checks. This is usually the right CI command.mvn install: copy the artifact into the local repository (~/.m2/repository) so other local builds can use it. It's often unnecessary in CI and can cause stale-artifact confusion locally.mvn deploy: publish to a remote repository.- Separate lifecycles:
clean(mvn clean) andsite.
Plugins do all the actual work. Each plugin provides goals (compiler:compile, surefire:test), and packaging types bind default goals to phases (for jar: resources:resources → process-resources, compiler:compile → compile, surefire:test → test, jar:jar → package). You add executions to bind more goals:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId> <!-- integration tests: *IT.java -->
<executions>
<execution>
<goals><goal>integration-test</goal><goal>verify</goal></goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId>
<executions><execution><id>enforce</id><goals><goal>enforce</goal></goals>
<configuration><rules>
<requireMavenVersion><version>[3.9,)</version></requireMavenVersion>
<requireJavaVersion><version>[25,)</version></requireJavaVersion>
<dependencyConvergence/> <!-- fail on version conflicts (chapter 42) -->
<banDuplicatePomDependencyVersions/>
</rules></configuration>
</execution></executions>
</plugin>
Commonly used plugins: maven-compiler-plugin (<release>25</release>), Surefire (unit tests) and Failsafe (integration tests), JaCoCo (coverage), Spotless or Checkstyle (formatting), SpotBugs/Error Prone (static analysis), versions-maven-plugin (versions:display-dependency-updates), Enforcer, exec, build-helper, flatten (CI-friendly versions), CycloneDX (SBOM), Jib, Spring Boot's plugin.
Maven Wrapper (mvnw, .mvn/wrapper/maven-wrapper.properties) pins the Maven version per project, so every developer and CI agent uses the same one. Maven 4 has been in release-candidate stage (rc-4 and later). It brings a separate consumer POM (the published POM no longer carries build-only details), better reactor handling, and stricter validation. Check its status before adopting it.
Dependency scopes
| Scope | Compile class path | Test class path | Runtime class path | Transitive? | Example |
|---|---|---|---|---|---|
compile (default) |
✓ | ✓ | ✓ | Yes | Spring, Jackson |
provided |
✓ | ✓ | ✗ (the container provides it) | No | Servlet API in a WAR, Lombok |
runtime |
✗ | ✓ | ✓ | Yes | JDBC drivers, logging back-ends |
test |
✗ | ✓ | ✗ | No | JUnit, Mockito, Testcontainers |
system |
Like provided, from a local path |
Avoid it | |||
import (in dependencyManagement only) |
Imports a BOM's managed versions | spring-boot-dependencies, jackson-bom |
<optional>true</optional> marks a dependency your library can use but doesn't force on consumers (for example, an optional Micrometer integration).
dependencyManagement and BOMs
<dependencyManagement> declares versions (and scopes and exclusions) without adding dependencies. When any module, or any transitive dependency, uses that artifact, the managed version applies. A BOM (Bill of Materials) is a POM whose only job is a dependencyManagement section listing compatible versions of a family of artifacts:
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers-bom</artifactId>
<version>${testcontainers.version}</version>
<type>pom</type>
<scope>import</scope> <!-- import all managed versions from this BOM -->
</dependency>
<dependency> <!-- pin a transitive dependency for a security fix -->
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.19.2</version>
</dependency>
</dependencies>
</dependencyManagement>
Spring Boot's dependency management (via the parent POM or by importing spring-boot-dependencies) curates several hundred libraries at mutually tested versions. That's one of Boot's most valuable features (chapter 47). Override a single managed version with its property (<jackson-bom.version>2.19.2</jackson-bom.version>) rather than fighting the BOM.
Repositories
Maven resolves artifacts from repositories: the local cache ~/.m2/repository, then remotes. Maven Central is the default. Organisations run a repository manager (Sonatype Nexus, JFrog Artifactory, or cloud equivalents such as AWS CodeArtifact, Azure Artifacts, Google Artifact Registry) as a proxy and cache of Central plus a host for internal artifacts. Configure it as a mirror in ~/.m2/settings.xml, which also holds credentials, never the POM:
<settings>
<mirrors>
<mirror><id>corp</id><mirrorOf>*</mirrorOf><url>https://nexus.corp/repository/maven-public/</url></mirror>
</mirrors>
<servers>
<server><id>corp</id><username>${env.NEXUS_USER}</username><password>${env.NEXUS_TOKEN}</password></server>
</servers>
</settings>
Supply-chain concerns (Part X):
- Dependency confusion: an attacker publishes a public artifact with your internal name and a higher version. Route all resolution through the mirror, and reserve your group IDs.
- Typosquatting and compromised maintainers.
- Checksum and signature verification: Maven Central requires PGP signatures. Gradle has dependency verification metadata (
verification-metadata.xml). - SBOMs (CycloneDX or SPDX) document exactly what shipped.
- Vulnerability scanning: OWASP Dependency-Check, Snyk, GitHub Dependabot, Renovate for automated update PRs.
Multi-module Maven builds
shop/
├── pom.xml ← parent/aggregator: <packaging>pom</packaging>, <modules>…</modules>
├── shop-domain/pom.xml ← pure domain model, no framework
├── shop-persistence/pom.xml ← depends on shop-domain
├── shop-api/pom.xml ← REST layer, depends on domain + persistence
└── shop-app/pom.xml ← Spring Boot application, assembles everything
- The parent's
<dependencyManagement>and<pluginManagement>centralise versions and plugin configuration. - The reactor sorts modules topologically and builds them in order.
-pl shop-api -ambuilds that module plus everything it depends on ("also make");-amdbuilds dependents.-T 1Cbuilds in parallel (one thread per core) where the graph allows. - Keep one version for all modules (bump together), unless modules are released independently.
- Use modules to enforce architectural boundaries:
shop-domainsimply can't import Spring if Spring isn't on its class path. ArchUnit tests (chapter 54) add finer rules.
Gradle
The model
Gradle builds are programs written in a Kotlin (the default for new builds) or Groovy DSL. A build goes through three phases:
- Initialisation: find
settings.gradle.ktsand determine the projects (modules). - Configuration: run every build script to create and configure tasks, and wire their dependencies into a DAG.
- Execution: run the requested tasks and their dependencies, skipping up-to-date tasks whose declared inputs and outputs haven't changed.
// build.gradle.kts
plugins {
java
id("org.springframework.boot") version "4.0.1"
id("io.spring.dependency-management") version "1.1.7" // or use the platform(...) approach below
}
group = "com.shop"
version = "1.5.0-SNAPSHOT"
java {
toolchain { languageVersion = JavaLanguageVersion.of(25) } // Gradle provisions/selects the JDK
}
repositories { mavenCentral() }
dependencies {
implementation("org.springframework.boot:spring-boot-starter-web")
implementation(platform("org.testcontainers:testcontainers-bom:1.21.3")) // BOM as a platform
runtimeOnly("org.postgresql:postgresql")
compileOnly("org.projectlombok:lombok")
annotationProcessor("org.projectlombok:lombok")
testImplementation("org.springframework.boot:spring-boot-starter-test")
testImplementation("org.testcontainers:postgresql")
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}
tasks.test { useJUnitPlatform() }
$ ./gradlew build # assemble + check (tests, lint)
$ ./gradlew :shop-api:test --tests '*OrderControllerTest'
$ ./gradlew tasks --all
$ ./gradlew build --scan # Build Scan: timeline, cache hits, dependency resolution (Develocity)
$ ./gradlew build --dry-run # show the task graph without executing
The Gradle Wrapper (gradlew, gradle/wrapper/gradle-wrapper.properties) pins the Gradle version. Commit it, and verify its checksum (distributionSha256Sum).
Configurations: Gradle's scopes
Gradle uses configurations instead of scopes, and they distinguish API from implementation, which Maven can't:
| Configuration | On consumers' compile class path? | On runtime class path? | Use for |
|---|---|---|---|
api (needs the java-library plugin) |
Yes (leaks to consumers) | Yes | Types that appear in your module's public signatures |
implementation |
No | Yes | Internal dependencies (most of them) |
compileOnly |
No | No | Annotations, provided APIs |
runtimeOnly |
No | Yes | JDBC drivers, logging implementations |
testImplementation / testRuntimeOnly |
— | Tests only | Test libraries |
annotationProcessor |
— | — | MapStruct, Lombok, Dagger |
implementation over api keeps compile class paths smaller, so changing an internal dependency of module A doesn't force recompiling A's consumers (better incremental builds), and consumers can't accidentally depend on A's internals.
Version catalogs
A version catalog (gradle/libs.versions.toml) centralises dependency coordinates and versions for all modules, with type-safe accessors:
[versions]
jackson = "2.19.2"
testcontainers = "1.21.3"
[libraries]
jackson-databind = { module = "com.fasterxml.jackson.core:jackson-databind", version.ref = "jackson" }
testcontainers-bom = { module = "org.testcontainers:testcontainers-bom", version.ref = "testcontainers" }
testcontainers-postgres = { module = "org.testcontainers:postgresql" }
[bundles]
testing = ["testcontainers-postgres"]
[plugins]
spring-boot = { id = "org.springframework.boot", version = "4.0.1" }
plugins { alias(libs.plugins.spring.boot) }
dependencies {
implementation(libs.jackson.databind)
testImplementation(platform(libs.testcontainers.bom))
testImplementation(libs.bundles.testing)
}
Catalogs declare coordinates. Platforms (platform(...), enforcedPlatform(...), or a java-platform project) declare constraints, like Maven's dependencyManagement. Renovate and Dependabot understand both formats.
Dependency resolution controls
dependencies {
constraints {
implementation("com.fasterxml.jackson.core:jackson-databind") {
version { require("2.19.2") } // minimum, upgrades allowed
because("CVE fix")
}
}
implementation("org.apache.commons:commons-text") {
version { strictly("[1.12, 2.0)") } // strict range: nothing outside
}
}
configurations.all {
exclude(group = "commons-logging", module = "commons-logging")
resolutionStrategy {
failOnVersionConflict() // make conflicts explicit
// force("…") exists but constraints/platforms are preferred
}
}
Dependency locking and reproducibility
Version ranges and dynamic versions (1.+, latest.release), plus SNAPSHOTs, make builds non-reproducible: the same commit resolves differently tomorrow. Lock files record exact resolved versions:
dependencyLocking { lockAllConfigurations() }
// $ ./gradlew dependencies --write-locks → gradle.lockfile per project, committed to git
// Builds then fail if resolution would differ from the lock.
Maven has no native lock file. Pin everything through dependencyManagement/BOMs, avoid ranges and SNAPSHOTs in releases, and use the Enforcer (requireReleaseDeps). Cargo (Cargo.lock), npm, uv and Poetry lock by default. Go's go.sum stores checksums, while MVS makes resolution deterministic without a solver lock.
Reproducible builds
A reproducible build yields bit-for-bit identical artifacts from the same source, whoever builds it. This lets third parties verify that a binary matches its source, an important supply-chain defence (the Reproducible Builds project, SLSA). Sources of non-determinism in JARs:
- Timestamps in ZIP entries and manifests → set
project.build.outputTimestamp(Maven 3.9 plugins honour it) or Gradle'sisPreserveFileTimestamps = falseandisReproducibleFileOrder = trueon archive tasks. - File ordering in archives (file system order differs between machines).
- Build environment: JDK vendor and version (pin with toolchains), locale, time zone, user name or path embedded in outputs.
- Dependencies changing (locking, as above).
<properties><project.build.outputTimestamp>2026-10-01T00:00:00Z</project.build.outputTimestamp></properties>
tasks.withType<AbstractArchiveTask>().configureEach {
isPreserveFileTimestamps = false
isReproducibleFileOrder = true
}
Go builds are reproducible by default (-trimpath removes local paths). Rust is close, with --remap-path-prefix. Bazel and Nix are designed around hermeticity.
Build caching and incremental builds
Gradle's performance features:
- Up-to-date checks: a task is skipped if its inputs and outputs are unchanged since its last run in this workspace.
- Build cache (local and remote): task outputs are stored keyed by a hash of all inputs (source files, class path ABI, tool versions, relevant properties). Any machine with the same inputs reuses the output. CI populates the remote cache, and developers and other CI jobs pull from it. Tasks must declare inputs and outputs correctly (
@InputFiles,@OutputDirectory,@PathSensitive), or caching is wrong. Most core and popular plugins are cacheable. - Configuration cache: caches the result of the configuration phase (the task graph), skipping build-script evaluation on later runs. Gradle 9 made it the preferred mode. It requires plugins that don't touch the
Projectmodel at execution time. - Compile avoidance: Java compile tasks depend on the ABI of upstream modules (public signatures), so changing a private method body in module A doesn't recompile A's consumers. That's another reason to prefer
implementationoverapi. - Incremental Java compilation: recompiles only affected classes.
- Parallel execution (
org.gradle.parallel=true) across modules. - Gradle daemon: a long-lived JVM that keeps the build model and JIT-warmed code between builds.
Maven's equivalents are weaker but improving: incremental compilation in the compiler plugin, parallel reactor builds (-T), and build-cache extensions (the Apache Maven Build Cache Extension, Develocity for Maven).
Bazel (Google) takes caching and hermeticity furthest: every action declares exact inputs, runs sandboxed, and is cached locally or remotely with remote execution across a build farm. It handles huge polyglot monorepos (Java, Go, C++, Python, TypeScript in one graph). The cost is a steep learning curve and BUILD files for everything. Pants and Buck2 are similar.
Other ecosystems
Other languages' build tools in practice
# Rust: Cargo.toml: build tool, package manager, test runner, doc generator, benchmark runner in one
[package]
name = "orders-service"
version = "1.5.0"
edition = "2024"
rust-version = "1.85" # minimum supported Rust version
[dependencies]
axum = "0.8" # "0.8" means ^0.8: semver-compatible updates
tokio = { version = "1", features = ["full"] } # features: compile-time optional functionality
serde = { version = "1", features = ["derive"] }
sqlx = { version = "0.8", default-features = false, features = ["postgres", "runtime-tokio", "macros"] }
[dev-dependencies] # tests/benchmarks only (like Maven's test scope)
testcontainers = "0.25"
[profile.release]
lto = "thin"
codegen-units = 1
debug = "line-tables-only" # keep symbols for profiling
# Workspaces (multi-module): [workspace] members = ["crates/*"] with a single shared Cargo.lock
# $ cargo build --release | cargo test | cargo clippy | cargo fmt | cargo tree | cargo audit
// Go: go.mod: the toolchain is the build system; no build scripts at all
module github.com/shop/orders
go 1.25 // language version (also gates semantics like loop vars)
toolchain go1.25.3 // optional: auto-download this toolchain
require (
github.com/jackc/pgx/v5 v5.7.5
golang.org/x/sync v0.16.0
)
// $ go build ./... compile everything (cached in GOCACHE; content-addressed, always on)
// $ go test ./... -race test with the race detector
// $ go vet ./... static checks
// $ go mod tidy add missing / remove unused requirements
// $ go generate ./... run //go:generate directives (code generation is explicit, not part of build)
// Build tags (//go:build linux) and GOOS/GOARCH select files; no plugins, no lifecycle.
# C++: CMake describes targets; a generator (Ninja) does the building; Conan/vcpkg supply packages
cmake_minimum_required(VERSION 3.28)
project(orders LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 23)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
find_package(fmt CONFIG REQUIRED) # provided by vcpkg/Conan/system
find_package(Boost REQUIRED COMPONENTS json)
add_library(orders_core src/order.cpp src/pricing.cpp)
target_include_directories(orders_core PUBLIC include) # PUBLIC/PRIVATE/INTERFACE ≈ Gradle api/implementation
target_link_libraries(orders_core PUBLIC fmt::fmt PRIVATE Boost::json)
add_executable(orders_server src/main.cpp)
target_link_libraries(orders_server PRIVATE orders_core)
enable_testing()
add_subdirectory(tests)
# $ cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release --preset vcpkg && cmake --build build && ctest --test-dir build
// Zig: build.zig is ordinary Zig code that constructs a build graph
const std = @import("std");
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{}); // -Dtarget=aarch64-linux-musl: cross-compile anything
const optimize = b.standardOptimizeOption(.{}); // Debug, ReleaseSafe, ReleaseFast, ReleaseSmall
const httpz = b.dependency("httpz", .{ .target = target, .optimize = optimize }); // from build.zig.zon
const exe = b.addExecutable(.{
.name = "orders",
.root_module = b.createModule(.{
.root_source_file = b.path("src/main.zig"),
.target = target,
.optimize = optimize,
}),
});
exe.root_module.addImport("httpz", httpz.module("httpz"));
b.installArtifact(exe);
const tests = b.addTest(.{ .root_module = exe.root_module });
b.step("test", "Run unit tests").dependOn(&b.addRunArtifact(tests).step);
}
// build.zig.zon: .dependencies = .{ .httpz = .{ .url = "…tar.gz", .hash = "…" } } (content-addressed)
<!-- .NET: SDK-style project; MSBuild under the dotnet CLI -->
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<RestorePackagesWithLockFile>true</RestorePackagesWithLockFile>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" /> <!-- version in Directory.Packages.props -->
<ProjectReference Include="..\Orders.Domain\Orders.Domain.csproj" />
</ItemGroup>
</Project>
<!-- $ dotnet build | dotnet test | dotnet publish -c Release -r linux-x64 -p:PublishAot=true -->
# Python: pyproject.toml + uv (fast resolver/installer, lock file, Python version management)
[project]
name = "orders-service"
version = "1.5.0"
requires-python = ">=3.13"
dependencies = ["fastapi>=0.115", "sqlalchemy>=2.0", "psycopg[binary]>=3.2"]
[dependency-groups]
dev = ["pytest>=8", "testcontainers[postgres]>=4", "ruff>=0.12", "mypy>=1.16"]
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
# $ uv sync (creates .venv from uv.lock) | uv run pytest | uv lock --upgrade-package fastapi | uv build
CI builds
Principles that apply to every build tool (Part VIII covers pipelines in depth):
- Use the wrapper or pinned toolchain (
./mvnw,./gradlew, Go'stoolchainline,rust-toolchain.toml,global.json,.python-version), so CI matches local builds exactly. - Cache dependencies:
~/.m2/repository,~/.gradle/caches(or the Gradle remote build cache),~/.cargo/registry+target/,GOMODCACHE+GOCACHE,~/.nuget/packages, uv's cache. Key caches on lock-file hashes. - One command that does everything a merge requires:
./mvnw -B verify(batch mode, no interactive output),./gradlew build,cargo test --locked,go test ./... -race,dotnet test,uv run pytest. Developers run the same command locally. - Fail on drift:
--locked/--frozenflags,go mod tidy && git diff --exit-code, Gradle'sfailOnVersionConflict, the Enforcer. - Build once, deploy many: produce the artifact (JAR or image) once, tag it with the commit SHA, scan it, sign it, and promote the same artifact through environments.
- Speed: parallelism, remote build caches, running only affected modules (Gradle's configuration on demand, Nx and Bazel affected targets,
mvn -pl … -amdfrom a changed-file list), test sharding. - Security: no secrets in build files; repository credentials from the CI secret store; SBOM generation; dependency scanning; artifact signing (Sigstore/cosign, Maven GPG); SLSA provenance.
# GitHub Actions: a Maven example (Gradle: gradle/actions/setup-gradle handles caching)
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-java@v4
with: { distribution: temurin, java-version: '25', cache: maven }
- run: ./mvnw -B -ntp verify # -ntp: no transfer progress logs
- run: ./mvnw -B -ntp org.cyclonedx:cyclonedx-maven-plugin:makeAggregateBom
Lab: what makes builds fast, correct and reproducible
Gradle 8.14 on JDK 21, with a generated project of 400 classes (each with a record, a stream pipeline and a switch, and chains of classes calling each other); javac, jar and make by hand for comparison; Go 1.24 for a cross-ecosystem check. Times include Gradle's client talking to an already running daemon.
Experiment 1: up-to-date checks and incremental compilation
clean build > Task :compileJava 5598 ms
nothing changed > Task :compileJava UP-TO-DATE 1139 ms
edit a method body in C399 Incremental compilation of 3 classes completed in 0.106 secs 1214 ms
edit a method body in C381 (called by others) Incremental compilation of 4 classes completed in 0.093 secs 1306 ms
touch all 400 files, no edits > Task :compileJava UP-TO-DATE
The remaining second per build is Gradle's own overhead (configuring the project and checking fingerprints), so the compile step itself went from about 4.5 s to 0.1 s. Two details are worth noticing. Editing a method body didn't force recompiling the classes that call it: callers depend only on the method's signature, its ABI, which didn't change. Gradle tracks that distinction, and so do Maven's newer incremental compiler options and Bazel (via "header" or ABI JARs); a change to a public signature would recompile dependents. And content hashing means switching git branches back and forth, or a tool that touches files, doesn't trigger rebuilds.
Experiment 2: the inlined constant
By hand:
public class Prices { public static final int GST_PERCENT = 5; public static int serviceCharge() { return 10; } }
// change to 18 and 12, then: javac -cp out -d out com/cafe/Prices.java (Main not recompiled)
GST 5%, service charge 12%
$ javap -v -cp out com.cafe.Main | grep GST
#38 = String #39 // GST 5%, service charge \u0001%
The compiler folded the constant into Main's string concatenation recipe; the method call was resolved at run time and picked up the change. The same edit in the Gradle project:
change a constant used by Main Incremental compilation of 2 classes completed in 0.062 secs
GST is 18% | zero!
Gradle recompiled Prices and Main, because its analysis records which classes use which constants (and falls back to a full recompile if it can't tell). The same trap exists across JARs: a library that changes a public constant doesn't change applications compiled against the old version until they're rebuilt. Expose values that may change through methods, not public static final fields.
Experiment 3: the build cache
clean, build with --build-cache (cache empty) Full recompilation is required … clean builds 3447 ms
clean again, build with --build-cache > Task :compileJava FROM-CACHE 1337 ms
Up-to-date checks only help when the outputs are still in build/. The build cache stores task outputs keyed by a hash of all their inputs, so a clean build, a fresh CI agent or a colleague's machine can reuse outputs produced anywhere with identical inputs. A shared remote cache (Gradle's, or Bazel's remote execution) is what makes CI builds of large repositories take minutes instead of hours. It only works if tasks are hermetic: an input the tool doesn't know about (an environment variable, the current time, a file read by a custom script) produces wrong cache hits. Turborepo's cache in Volume 2 is the same idea for JavaScript.
Experiment 4: reproducible artifacts
The same class files packed twice, two seconds apart, after touching the class files:
jar cf a.jar … ; jar cf b.jar … sha256: 17c9061f27817550 vs 2e46e68aa58f155d
jar --create --date=2026-01-01T00:00:02Z … (twice) sha256: 934ab77a42c1ffa1 vs 934ab77a42c1ffa1
A JAR is a zip, and zip entries record modification times, so identical code produced different files. With a fixed --date (JDK 17+), the output is byte-for-byte identical. Maven (project.build.outputTimestamp) and Gradle (isPreserveFileTimestamps = false, isReproducibleFileOrder = true) have settings for this. Reproducible builds let anyone verify that a published binary came from the claimed source, which is a supply-chain security control (Volume 10), and they make caching and deduplication work.
Experiment 5: the same ideas in Go
go build, cold cache: 7823 ms
go build, nothing changed: 61 ms
go build, file touched: 57 ms
go build, a comment added: 182 ms
Go's build cache is content-addressed and on by default, without any build-tool configuration: the toolchain is the build system. Rust's Cargo does incremental compilation per crate; Bazel and Buck2 apply content-hashed, sandboxed, remotely cached actions to any language. The ideas are the same everywhere: hash inputs, cache outputs, rebuild only what depends on what changed.
Try it yourself
- Change a public method signature in one generated class. How many classes does Gradle recompile now?
- Enable the configuration cache (
--configuration-cache) and measure the no-change build again. Which part of the overhead does it remove? - Make a task non-hermetic: add a Gradle task whose output includes
System.currentTimeMillis(), enable the build cache and observe the wrong cache hit. Then declare the input properly. - Build the same project with Maven (
mvn -q packagetwice) and compare its no-change build time with Gradle's.
Revision sheet: build systems
Key ideas
- Jobs: resolve dependencies, compile, test, package, publish; do the minimum work; be reproducible.
- Maven: POM, coordinates, scopes (
compile,provided,runtime,test), the default life cycle (validate…compile…test…package…verify…install…deploy) with plugins bound to phases, parent POMs, BOMs anddependencyManagement, nearest-wins resolution, reactor multi-module builds, wrapper. - Gradle: tasks in a directed acyclic graph, configurations (
implementation,api,compileOnly,runtimeOnly,testImplementation), highest-wins resolution with constraints and platforms, version catalogs, convention plugins, incremental compilation with ABI tracking, build cache, configuration cache, daemon, build scans, toolchains. - Correctness: hermetic tasks, declared inputs and outputs, constant inlining, clean CI builds, dependency locking and verification (checksums, signatures).
- Reproducibility: fixed timestamps and file order, pinned tools and dependencies.
- Other ecosystems:
go build(content-addressed cache), Cargo (crates, features, workspaces, lock file), npm/pnpm and Vite, Pythonuv/Poetry, .NETdotnet build/MSBuild, CMake/Ninja, Bazel/Buck2/Pants for monorepos.
Numbers to remember
- Lab: 400-class clean compile 5.6 s; no-change 1.1 s (UP-TO-DATE); one-method edit recompiled 3 classes in 0.1 s; build cache turned a clean build into FROM-CACHE; Go no-change build 61 ms.
Pitfalls
- Building outside the wrapper; unpinned plugin and dependency versions.
- Undeclared task inputs (environment, time, files read by scripts) breaking caching.
apiinstead ofimplementationeverywhere (leaking dependencies, recompiling everything).- Public constants changed in libraries without rebuilding dependents.
- Treating a green incremental local build as proof; not running a clean CI build.
- Build logic copy-pasted across projects instead of convention plugins or parent POMs.
Glossary
- Life cycle phase: a named step in Maven's build (compile, test, package).
- Configuration (Gradle): a named set of dependencies for a purpose.
- ABI: the public signatures other code compiles against.
- Hermetic build: one whose outputs depend only on declared inputs.
- Build cache: stored task outputs keyed by input hashes.
- BOM / platform: an aligned set of versions applied to many dependencies.