Volume 3 Exercises: The BackendPractice for Volume 3
0 / 0

Workbench / Volume 3 Exercises: The Backend

V3·43

Build Systems

Exercises for Volume 3, chapter 43: the jobs of a build tool and its models; Maven's POM, lifecycle, phases, goals and plugins, scopes, dependencyManagement and BOMs, repositories and multi-module builds; Gradle's model, configurations, version catalogs, resolution controls, locking and reproducibility; incremental builds and the build cache; build tools in other ecosystems; and CI builds. 9 theory questions, 9 programming exercises, 3 cumulative projects, the concepts the chapter leaves out, and 5 senior-level exercises.

32 exercises · ~15 min to read
Updated Suggest a correction

Start here: how this chapter's exercises work

The four sets and the locking work as before. The builds use Gradle 8.14 with JDK 21, offline, because Maven Central was blocked by this environment's network policy. The Maven exercises therefore show the POM and the expected outputs, and the Gradle ones are real.

Four of the measured outputs catch experienced developers:

  • P1. pricing declared money as an implementation dependency, and the app, which used Money directly, failed to compile with package tb.money does not exist. Changing it to api made the build succeed and print Money[paise=10000].
  • P3. A cacheable task read System.getenv("GST") without declaring it as an input. With GST=18, Gradle restored the old output FROM-CACHE: the file said gst=5. The version that declared the variable as an @Input re-ran and wrote gst=18.
  • P7. pip install requests==2.31.0 "urllib3<1.21" stopped with ResolutionImpossible. Python's resolver refuses an unsatisfiable set; Maven would silently pick a version instead.
  • P4. The configuration cache was reused, yet a tiny 3-project build took the same time with and without it (about 850–1,000 ms). Its value shows on large builds.

The chapter's lab measured incremental compilation (5,598 ms clean against 1,139 ms up to date), constant inlining across files, FROM-CACHE after clean (3,447 ms against 1,337 ms), reproducible JARs with --date, and Go's build cache (7,823 ms cold against 61 ms). The exercises build on those results and don't repeat them.

Coverage map.

Chapter component Exercises
jobs and models of build tools T1
Maven POM, lifecycle, phases, goals, plugins T2, P6
Maven scopes; Gradle configurations T3, P1
dependencyManagement, BOMs, version catalogs T4, P5
repositories; mirrors; credentials T4, P6
multi-module builds T5, P1
resolution controls; locking; reproducibility T6, P5, P8
build caching; incremental builds; hermeticity T7, P2, P3, P4
other ecosystems' build tools T8, P7
CI builds T9, P9

Theory

T1. What a build system does

  1. List the jobs a build does: - resolving dependencies; - generating code (annotation processors, OpenAPI, protobuf); - compiling; - processing resources; - testing; - packaging; - checks (lint, coverage, static analysis); - publishing; - building images.

Which of these does mvn verify or gradle build do by default, and which need plugins? 2. Compare the models: - Maven's declarative, convention-over-configuration lifecycle; - Gradle's task graph with a Groovy or Kotlin DSL; - Bazel and Buck's hermetic, content-addressed actions; - Make's file timestamps; - npm scripts (Volume 2).

What does each optimise for, and when is each a poor fit? 3. Why shouldn't you compile by hand, even for a "small" service? Consider the lab's constant-inlining trap, reproducibility, dependency versions and the CI parity of "works locally".

T2. Maven: POM, lifecycle, phases, goals and plugins

  1. Explain the POM: - coordinates (groupId:artifactId:version); - packaging; - parent POMs and inheritance; - properties; - dependencies; - build plugins with executions; - profiles; - the effective POM (mvn help:effective-pom).

What does Spring Boot's parent POM give you? 2. Explain the three lifecycles (clean, default, site), how phases run in order (mvn package runs compile, test and so on), how goals bind to phases (maven-surefire-plugin:test bound to test), plugin executions with <phase> and <goals>, and running a goal directly (mvn dependency:tree). Why does mvn install in a multi-module project matter less than people think? 3. Name the common Maven pitfalls: - unpinned plugin versions (a different build on another machine); - profiles activated by environment, making builds differ; - -DskipTests habits; - SNAPSHOT dependencies in releases; - local repository pollution; - long mvn clean install cycles.

Give the fix for each.

T3. Scopes and configurations

  1. Explain the Maven scopes and their class paths: - compile (compile, test and runtime; transitive); - provided (compile and test, not packaged); - runtime (test and runtime, not compile: JDBC drivers); - test; - system (avoid); - import (BOMs only).

Why was the PostgreSQL driver as provided a bug in ch42's S2? 2. Explain Gradle's configurations: - implementation (on your compile and runtime class path, not leaked to consumers' compile class path); - api (leaked, from java-library); - compileOnly; - runtimeOnly; - testImplementation; - annotationProcessor.

P1: pricing used implementation project(':money'), and the app, which referenced Money itself, failed with package tb.money does not exist. With api it worked. When is the error actually the right outcome? 3. The api against implementation choice matters for compile avoidance (consumers recompile less) and for accidental coupling. What's the rule ("api only for types in your public signatures"), and how does it map to Maven, which has no such distinction (every compile dependency is transitive)?

T4. dependencyManagement, BOMs, version catalogs and repositories

  1. Explain Maven's dependencyManagement (it sets versions and scopes without adding dependencies) and BOM import, and Gradle's platforms (implementation platform('…bom'), enforcedPlatform). Why is a BOM better than a property per version?
  2. Gradle version catalogs (gradle/libs.versions.toml) have [versions], [libraries], [bundles] and [plugins], plus type-safe accessors (libs.jackson.databind). How do catalogs differ from platforms? Catalogs say what to declare; platforms constrain resolution. When do you use both?
  3. Repositories: - Maven Central; - company repository managers (Nexus, Artifactory) as mirrors and proxies; - settings.xml mirrors and credentials; - Gradle dependencyResolutionManagement with repositoriesMode FAIL_ON_PROJECT_REPOS; - repository content filtering, to stop dependency confusion.

This environment blocked Maven Central with an HTTP 403 from its proxy. What does a team do about offline or restricted builds?

T5. Multi-module builds

  1. Why split a service into modules (domain, application, adapters-web, adapters-db, app)? Consider enforced dependency direction, compile avoidance, parallel builds and test isolation. Then compare multi-module against multi-repository against a monorepo with many services.
  2. P1's three-module build: money (a library), pricing (which depends on money) and app. Write the Maven equivalent (an aggregator POM with <modules>, a parent with dependencyManagement, module POMs with sibling dependencies). Explain reactor ordering, -pl -am, and -T parallelism.
  3. Gradle convention plugins (in buildSrc or an included build-logic build) replace copy-pasted configuration across modules: Java version, Error Prone, test settings, publishing. Why are they better than allprojects {} and subprojects {} blocks?

T6. Resolution controls, locking and reproducible builds

  1. Gradle resolution controls: - rich versions (strictly, require, prefer, reject); - dependency constraints; - resolutionStrategy (failOnVersionConflict, force); - capabilities (declaring that javax and jakarta annotation JARs conflict); - component metadata rules.

Map each to a TiffinBox problem from ch42. 2. Dependency locking. Gradle's --write-locks and gradle.lockfile; Maven has no built-in lock (use pinned versions, or the maven-lockfile plugin). How do locks differ from version catalogs and BOMs? When do dynamic versions (2.+, [2.0,3.0)) appear, and why should builds lock them? 3. Reproducible builds. The lab showed jar cf producing different hashes, and jar --date producing identical ones. List everything that must be fixed for a reproducible Java build: - timestamps; - file ordering; - the JDK version; - locale and time zone; - absolute paths in outputs; - generated code with dates; - dependency versions; - plugin versions.

Name the tools that verify it (Reproducible Central, mvn artifact:compare).

T7. Incremental builds, the build cache and hermeticity

  1. Explain up-to-date checking (task inputs and outputs fingerprinted; the lab's UP-TO-DATE and 400 touched files with no edits), incremental Java compilation (the lab: 3 or 4 classes recompiled in about 0.1 s), and compile avoidance through ABI changes (a method-body change doesn't recompile consumers in other modules). What makes a change "ABI-affecting"?
  2. The build cache (local and remote). P3: a cacheable task that read GST from the environment without declaring it came back FROM-CACHE with the stale value 5 when GST=18. The fixed task, declaring @Input gst, re-ran and wrote 18. Explain why undeclared inputs corrupt caches, and list the usual hidden inputs: - environment variables; - system properties; - the current time; - files read by path; - the network; - tool versions; - absolute paths.
  3. The configuration cache. It caches the result of the configuration phase, so later builds skip evaluating build scripts. P4: a tiny 3-project build took about 850–1,000 ms either way. Why does it matter for builds with hundreds of projects, and what does it forbid (accessing project at execution time, undeclared environment reads)?

T8. Build tools in other ecosystems

  1. Compare build and dependency tools: - Go: the go command with a module cache and build cache (the lab: 7,823 ms cold, 61 ms warm); minimal version selection. - Rust: Cargo, with Cargo.lock, workspaces and features. - Python: pip/uv/Poetry, pyproject.toml, lock files, wheels. P7's resolver gave ResolutionImpossible. - JavaScript: npm, pnpm, Turborepo and Nx (Volume 2). - .NET: MSBuild/NuGet. - Polyglot: Bazel, Pants and Buck2.

Which have built-in lock files and built-in caching? 2. P7: pip refused an impossible combination with ResolutionImpossible, while Maven's nearest-wins would silently pick a version (ch42's T5). Is refusing better? Consider correctness against convenience, and how backtracking resolvers (pip, uv, Poetry, Cargo) differ from Maven's. 3. A TiffinBox polyglot repository holds Java services, a Go worker, a Python ML job and a TypeScript frontend. Design the build orchestration: native tools per language with a thin task runner (Make, Just or Task), or Bazel or Pants for everything. What decides it?

T9. CI builds

  1. Design a CI pipeline for a Java service: - a pinned build image; - Gradle or Maven caching (dependencies by lock-file hash; the build cache, remote and read-only on PRs); - parallel jobs (unit tests, integration tests with Testcontainers, static analysis); - test reports and flaky-test handling; - artifact and image build; - SBOM and signing (ch42); - deploy stages.

What makes CI builds slow, and how do you measure it? 2. Why should PR builds read from a remote cache but not write to it, while main-branch builds write? Cover cache poisoning and trust. And why must CI use the same build entry point as developers (./gradlew build), with wrappers pinning the tool version? 3. Build observability: Gradle build scans (Develocity), the Maven build-cache extension, timings per task, the test duration distribution, cache hit rates. Write the dashboard you'd want for a 50-module build.

Programming exercises

P1. Configurations and a multi-module build

Create money, pricing and app modules in Gradle. Make pricing depend on money with implementation, let app use Money directly, and capture the compile error. Fix it the right way: api if Money is in pricing's public signatures, or a direct dependency in app otherwise. Then: - add compileOnly Lombok-style and runtimeOnly driver-style dependencies, and inspect the class paths with gradle :app:dependencies --configuration runtimeClasspath; - write the equivalent Maven multi-module POMs.

P2. Incremental builds in practice

In a Gradle project with 100 generated classes, measure: - a clean build; - no change; - touching files without editing; - editing a method body in a leaf class; - editing a public constant used by others; - editing a public method signature in a module used by two others.

Read --info for "Incremental compilation of N classes". Then compare with Maven (expected times).

P3. Hermetic tasks and the build cache

Write a cacheable Gradle task that reads an environment variable without declaring it. Run it with GST=5, clean, then run it with GST=18, and observe FROM-CACHE with the stale output. Fix it with @Input bound through providers.environmentVariable. Then find and fix two more hidden inputs: - a task embedding the build time; - a task reading a file by absolute path.

P4. Configuration cache and build performance

Enable the configuration cache on a multi-project build, run it three times, and confirm "Configuration cache entry reused". Compare the timings with and without it. Then break it deliberately (read System.getenv at configuration time, or access project in a task action), read the problem report, and fix it. Finally, run --profile or --scan and identify the slowest task.

P5. BOMs, platforms, catalogs and locking

In Gradle, create: - a version catalog with Jackson and JUnit entries; - a platform project (java-platform) that imports a BOM-like set of constraints; - dependency locking (dependencyLocking { lockAllConfigurations() }, plus --write-locks).

Show that changing a catalog version without updating the lock fails the build until locks are rewritten. Write the Maven equivalent with dependencyManagement and an imported BOM.

P6. A Maven lifecycle and plugin configuration

Write a Maven POM for the order service that: - pins all plugin versions; - sets maven.compiler.release to 21 and -parameters; - binds Error Prone to compilation; - runs unit tests with Surefire and integration tests (*IT) with Failsafe in verify; - adds JaCoCo coverage with a threshold; - adds the Enforcer rules from ch42; - sets project.build.outputTimestamp.

Explain what mvn verify runs, in order. Run it if you have Maven Central access; otherwise give the expected phase log.

P7. Dependency resolution in other ecosystems

Show: - pip refusing an impossible set (requests==2.31.0 with urllib3<1.21); - Go's minimal version selection, with go mod graph and go list -m all on a small module that requires two versions of a dependency through different paths; - npm installing nested duplicate versions (npm ls, Volume 2); - Maven's nearest-wins downgrade (ch42's P7).

Write one paragraph per ecosystem on what the resolver promises.

P8. Reproducible artifacts

Build the same JAR twice: - with jar cf (different hashes, as in the lab); - with jar --date (identical); - with Gradle with and without isPreserveFileTimestamps = false and isReproducibleFileOrder = true.

Then build in two different directories and compare the hashes, and list any differences (for example, absolute paths in generated sources).

P9. A CI pipeline definition

Write a GitHub Actions (or GitLab CI) workflow for the order service with: - the Gradle wrapper; - setup-java with a toolchain; - a dependency cache keyed on the lock files; - a remote build cache (read-only on PRs); - parallel jobs (test, integration, static analysis); - test report upload; - the image build and SBOM on main.

Add a job that fails if the build isn't reproducible (P8). Estimate the PR feedback time before and after caching.

Cumulative projects (chapters so far: Volume 1, Volume 2, and Volume 3's 33–43)

C1. Restructure the order service as a modular build

Split the order service into Gradle modules: - domain (pure: ch37's functional core); - application (use cases); - adapters-web; - adapters-db; - adapters-messaging; - app (Spring Boot wiring).

Add convention plugins, a version catalog plus a platform (the Spring Boot BOM and TiffinBox's platform BOM), dependency locking, and reproducible archives. Use implementation/api correctly. Show that domain can't import Spring or JPA, and measure incremental build times for a domain change against an adapter change.

Combines: Volume 1's modular design, ch34's architecture (aggregates), ch37's functional core and imperative shell, ch42's packaging, and this chapter.

C2. Polyglot build orchestration

Create a TiffinBox repository with: - the Java order service (Gradle); - the Go notifier; - the Python scoring job (uv); - the TypeScript dashboard (pnpm and Turborepo, Volume 2); - a shared OpenAPI spec.

Add a Justfile with build, test, gen and ci targets. Generate the Java server stubs and TypeScript client from the spec with pinned generator versions. Add CI path filters so only the affected projects build, and lock files everywhere. Measure CI time for a TypeScript-only change against a spec change.

Combines: Volume 2's monorepo tooling (ch30), ch33's language comparison, ch42's packaging per language, and this chapter.

C3. Migrate a Maven build to Gradle, or argue against it

The legacy admin application (ch42's C3) builds with a 1,200-line Maven POM: - profiles per environment; - antrun scripts; - unpinned plugins; - -DskipTests in CI.

Either migrate it to Gradle with conventions, a catalog, caching and locking, or clean up Maven properly (pinned plugins, Enforcer, explicit profiles, mvnd, the build-cache extension). Decide which, do it, and report the build times and maintenance effort before and after.

Combines: ch39's upgrade discipline, ch42's packaging and conflicts, and this chapter.

What the chapter leaves out

Annotation processing and code generation in builds

Annotation processors (MapStruct, Lombok, Dagger, Micronaut and Spring AOT) and source generators (OpenAPI, protobuf, jOOQ) are build steps with their own inputs. Misconfigured, they break incremental compilation (Gradle needs to know whether processors are incremental: "isolating" or "aggregating"), produce non-reproducible output, and slow builds. Declare generator inputs, pin generator versions, and decide whether generated code is committed or produced at build time.

Testing configuration in builds

Builds decide which tests run (unit against integration source sets, JUnit tags), with what parallelism (maxParallelForks, JUnit's parallel execution), and with what JVM settings. Test caching (Gradle skips tests whose inputs are unchanged) is powerful, but it relies on hermetic tests: tests that read clocks, networks or random data without seeding are, like P3's task, non-hermetic. Chapter 54 covers it.

Gradle Kotlin DSL against Groovy DSL

The Kotlin DSL (build.gradle.kts) gives type safety and IDE completion, and it's now Gradle's default for new builds. The Groovy DSL (used in P1–P4 for brevity) is more dynamic and has older documentation. Prefer Kotlin DSL for new builds and convention plugins. The concepts are identical.

Build tool security

Build scripts run arbitrary code: Gradle plugins, Maven plugins and npm postinstall scripts. Supply-chain attacks target builds (compromised plugins, malicious dependencies running at build time). The defences: - Gradle dependency verification (verification-metadata.xml with checksums and signatures); - wrapper checksum validation (distributionSha256Sum); - pinned plugin versions; - repository allowlists (T4); - running builds in isolated, ephemeral CI runners without production credentials.

Large-scale build infrastructure

Remote execution (Bazel's RBE, Gradle Enterprise test distribution), distributed caching, and predictive test selection (running the tests likely affected by a change) are what keep builds in companies with thousands of engineers within minutes. They require investment in build engineering, hermetic builds and metrics. Know they exist before you outgrow your current setup.

Senior exercises

S1. The build standard for TiffinBox

Write the build standard: - the tool choice (Gradle with Kotlin DSL for new services; Maven tolerated for legacy); - the wrapper; - toolchains; - convention plugins; - catalog plus platform; - locking; - api/implementation rules; - reproducible archives; - hermetic custom tasks; - the remote cache policy; - CI entry points; - required checks (Error Prone, Enforcer-equivalent rules, coverage threshold, licence report, SBOM).

Tie each to an output from this chapter.

S2. Review a build script

A PR's build.gradle: - adds repositories { mavenCentral(); maven { url 'https://repo.example-oss.org' } } in a module; - uses implementation 'com.fasterxml.jackson.core:jackson-databind:2.+'; - has a task that runs curl to download a rates file during processResources; - uses allprojects { apply plugin: 'java' } in the root; - sets test { enabled = System.getenv('CI') == null }.

Write the review.

S3. Decide whether to adopt Bazel

TiffinBox now has 40 services in a monorepo (Java, Go, Python, TypeScript), CI takes 35 minutes per PR despite Gradle and Turbo caches, and cross-language code generation (protobuf) is fragile. A staff engineer proposes migrating to Bazel. Decide, with costs, benefits, a migration plan, and the success metrics.

S4. Teach "the build is code" with four outputs

Prepare a 15-minute session using: - P1's implementation compile error; - P3's stale FROM-CACHE output; - the lab's constant-inlining trap when compiling by hand; - P7's pip ResolutionImpossible against Maven's silent choice.

End with three rules.

S5. Plan build reliability and speed as a platform service

As the platform lead, plan a 6-month programme to make builds fast and trustworthy across 14 services: - standard conventions (S1); - remote cache infrastructure and policy; - build observability (T9's dashboard); - dependency hygiene (locks, Renovate, BOMs); - reproducibility verification; - security (verification metadata, wrapper checksums, repository policy); - the developer experience (local build times, IDE sync).

Give the milestones and the metrics.