Composite vs. Multi-Project Build With Multiple Services (Docker Images)

Hi,

I am (also) trying to understand the difference between Composite Builds and Multi-Projects Build. I am particularly interested in maintaining a mono-repo, which produces multiple services, i.e., docker images. Moreover, I would like to understand, how do best versioning of the generated services, i.e., docker images, i.e., git tag of the repository vs. versions of images (probably not the context of gradle?).

Basically, my monorepo looks like

monorepo
|-- lib/
|-- proto/
|-- service/
    |-- foo/ // depends on proto/
    |-- bar/ // depends on proto/ and lib/

The lib/ contains the domain-logic and proto/ the gRPC API, i.e., auto-generated java classes from proto files, we already discussed this here and there. :heart_suit:

As can be seen in the layout, I have two services (might become more), which depend on lib/ (domain-logic) or both lib/ and proto/ (gRPC API).

Consequently, I need the files (output?) of those other directories for compilation and finally, want to build Docker images. We are using Bitbucket pipelines, i.e., I don’t know where to draw the line between gradle and Bitbucket. But I assume, each service-folder needs its own Dockerfile?

And finally, what is the best practice to do versioning for the produces artefacts (Docker images)? Shall each artefact simply has the git tag of the whole monorepo, even if a service might not be affected?

Yes, it is much. I just would like to know how to sort things out and where to look for my issues. :slight_smile:

Thanks in advance and best, patient-coder.

EDIT
Okay, seems to me I require autonomous builds for the services, i.e., composite build is my choice then?

I am (also) trying to understand the difference between Composite Builds and Multi-Projects Build.

One of the main differences is, that you can open a build that is included into another build in your IDE independently and also build it completely independently, while with a multi-project build you always have all projects in the build. But even there you can just build one project and with configuration cache also the configuration time is not that relevant anymore, …

Keep in mind the original use-case for composite builds.
You have your project A and use a library B by depending on it from some repository.
Now you want to play with the very latest code of B in A, or want to implement a feature in B that is used in A.
One way (the legacy Maven way) is to code in B then manually publish to a local Maven repository, then go to A and code there, then go back to B, do some changes publish again, work on A again.
The better way (if the Gradle versions are compatible, optimally identical) is, to include the build of B into the build of A, then you get both projects in your IDE automatically, and whenever you build A, B is built automatically if necessary and so on.

Nowadays you can also use composite builds in one repository as a measure of organizing the build, like having one build for lib, one build for foo and one build for bar where the latter two include the build for lib.

What you must not do, is to have one build for foo and one build for bar and just add the lib directory in both builds as project using include, because one project should always only be part of exactly one build or you get into serious trouble.

So the multi-project build variant would be that foo, bar, and lib are all in one build.

We are using Bitbucket pipelines, i.e., I don’t know where to draw the line between gradle and Bitbucket.

Pretty much up to you where you draw the line.
I usually try to be as independent from any CI system as possible by having all build logic in Gradle and the CI system merely is a scheduler for when to trigger which Gradle tasks.
So I would probably use some Gradle plugin like the bmuschko docker plugin to build the docker images by invoking Gradle tasks.

But I assume, each service-folder needs its own Dockerfile?

That has nothing to do with Gradle, but yes, probably.

And finally, what is the best practice to do versioning for the produces artefacts (Docker images)? Shall each artefact simply has the git tag of the whole monorepo, even if a service might not be affected?

Pretty much holy war here too.

My personal take is, if something is in the same VCS repo, it should have the same version, so that tags, branches, etc. are valid for all the things in the repo.
Also the other way around, if things are version / branched / released / … together, they should reside in the same VCS repo.

Okay, seems to me I require autonomous builds for the services, i.e., composite build is my choice then?

If you need really autonomous builds, probably.
But even with a big multi-project build you could say “build me just project X and its dependencies”.
:man_shrugging:

Thanks.

So, right into the details: Since we have discussed thoroughly the details about generating code from proto files in Best Practice To Enable Incremental Build, I am trying to make this generated code in proto/, i.e., more precisely proto/build/generated/sources/proto/, accessible in other sub-projcets, e.g., in service/foo/.
From my understanding so far, I add to build.gradle.kts from service/proto/ simply

dependencies {
    implementation(project(":proto"))
}

According to AI, this should suffice

  • Adds proto/'s compiled classes and exported (api) dependencies to :service:foo’s compile and runtime classpaths.
  • Automatically handles task dependencies and incremental builds without needing raw file paths.

But this leads to a compiler error that the package is unknown.

I also added to build.gradle.kts

sourceSets.main {
    java {
        srcDir(project(":proto").layout.buildDirectory.dir("generated/sources/proto/main"))
    }
}

Because I thought, maybe I need to tell the compiler to make the code available. At least, when IDE suggests to make the folder available, it marks those as sources-root, i.e., what I usually achieve via gradle by marking something in the sourceSets.

But this doesn’t work either.

Summarized, I am struggeling a bit to understand the role of build- and settings-files.
First of all, why do I need a “root” settings file, which contains include("proto", "service:foo")? Does the multi-project need to know which sub-projects are part of the repository?
And if the multi-project “knows”, there are proto and service:foo sub-projects, why do I need to write dependencies { implementation(project(":proto")) } in the build.gradle.kts file … and not the settings file? Okay, this dependency seems to trigger somehow caching. When re-building service:foo, the proto sub-project is not re-built.
But then, again, when I tell via build.gradle.kts, that there is another sub-project … why do I need to tell the monorepo in the “root” settings.gradle.kts file, that there are multiple sub-projects?

I don’t know if those questions make sense, but as I have written, I struggle to understand what goes where and then how to tell gradle to apply this from over there …

From my understanding so far, I add to build.gradle.kts from service/proto/ simply

You probably meant service/foo I guess.

implementation(project(":proto"))

Yes, if those files are part of the main source set of proto, so for example if the task generating the source files from the proto files is registered as srcDir for the main source set. Don’t remember by now how the exact setup was in your case, an MCVE might help.

But this leads to a compiler error that the package is unknown.

Most probably proto is not configured correctly then, but again, hard to guess from just a partly description and no MCVE.

I also added to build.gradle.kts

Go and delete that now!!!
That is horribly wrong on multiple axes.
For example, you reach into the other projects mutable state, which is bad.
And you add the files from there to your own source set instead of depending on that other project’s artifact.
And also you do not have any dependency on the task producing those files then, so you either work with stale files, or with no files, depending on whether a former build has run that task already.
And you can also never use configuration cache or isolated projects, which on the long run will be the only mode available.

Because I thought, maybe I need to tell the compiler to make the code available.

You did with implementation(project(":proto")) if proto is configured correctly.

But this doesn’t work either.

Thank god.

First of all, why do I need a “root” settings file

Every build needs a settings script.
The settings script defines the shape of the build, that is for example which projects are part of the build, where are the directories of those projects, how are their build scripts named, which other builds to include to form a composite build, some whole build settings like plugin repositories, uniform dependency repositories for the whole build, …

include(“proto”, “service:foo”)

That you have those two projects in addition to your root project, otherwise you only have the root project.

Does the multi-project need to know which sub-projects are part of the repository?

“part of the repository”?
Usually, all projects of a build are part of the same repository.
Often even mutliple builds are part of the same repository.
If you have things split into multiple repositories, they should usually not be combined as projects in one build, but more likely one (or multiple) builds per repository and when wanting to combine them, then using composite build.

Especially, if they are in multiple repositories to reuse one project in multiple builds. Never ever ever ever ever ever ever even think about doing such a thing. One project should never ever ever be part of more than one build, but only of exactly one build. And if another build needs the project, then form a composite build.

So, kind of no, Gradle does not care whether a project is in the same repository or another or in any at all, Gradle does not know anything about repositories and doesn’t care.You could have each single file of a build in a different repository and combine that into one build, it just does not really make much sense.

And if the multi-project “knows”, there are proto and service:foo sub-projects, why do I need to write dependencies { implementation(project(":proto")) } in the build.gradle.kts file …

Why should you not?
Just that both projects are part of the same build does not say anything about their dependency to each other.

Just because you have jam, ham, and bread in your fridge does not magically make your bread know that you want to spread jam on it and then lay ham on-top.
Or maybe you also want some cheese.

and not the settings file?

Because the settings script defines the layout of the build and some build-wide settings.
The project build script defines how that project is built and what dependencies it has.

Actually, you can indeed delete all build scripts and configure the complete build in the settings script, using project configuration hooks in the settings script.
It is just absolutely non-idiomatic, ugly as hell especially if you got some more projects, and totally unmaintainable and non-understandable.

Okay, this dependency seems to trigger somehow caching.

Whatever you mean … no. Or you chose extremely awkward words if you meant something correct that I cannot recognize due to not being a native speaker.

When re-building service:foo, the proto sub-project is not re-built.

Of course not, why should it, if you did not change anything in it?
One of the biggest strengths of Gradle is to avoid unnecessary work.

But then, again, when I tell via build.gradle.kts, that there is another sub-project …

You don’t.
You tell it that one project depends on another project.
That does not define that project.
Just because you want to lie cheese onto your bread too does not magically make cheese pop up in your fridge if you did not put some inside.

why do I need to tell the monorepo in the “root” settings.gradle.kts file, that there are multiple sub-projects?

Because that is one of the main responsibilities of the settings script, to define the shape of the build’s project tree.

I don’t know if those questions make sense, but as I have written, I struggle to understand what goes where and then how to tell gradle to apply this from over there …

Maybe you should spend some time with the usermanual and the example projects. :wink:

Good morning, thanks for the thorough explanation.

I also added to build.gradle.kts

Go and delete that now!!!
That is horribly wrong on multiple axes.
For example, you reach into the other projects mutable state, which is bad.

Maybe I found the issue. In the previous proto-discussion I used plugin { java } and implementation and probably this automatically marks the folders, where the generated code lies, as source sets.
But here, AI told me to use plugin { ´java-library´ } and dependencies { api(libs.protobuf.java) }. So, this makes the code consumable by other projects, but probably doesn’t mark the generate code as source set automatically?
However, in the proto sub-project, I added

sourceSets.main {
    java {
        srcDir(layout.buildDirectory.dir("generated/sources/proto/main/grpc"))
        srcDir(layout.buildDirectory.dir("generated/sources/proto/main/java"))
    }
}

and now, yes! I can use the generated files in the other sub-project, maybe simply due to dependencies { implementation(project(":proto")) }. That way, I don’t care about the layout of the proto project.

Furthermore, I’d like to consolidate versions among the sub-projects. Google told me, that I can add

dependencyResolutionManagement {
    versionCatalogs {
        create("libs") {
            from(files("../gradle/libs.versions.toml"))
        }
    }
}

to any settings.gradle.kts and thus can use in the build.gradle.kts files the notation dependencies { api(libs.protobuf.java) } . Would you agree?

Moreover, isn’t it possible to centralize these lines

java {
    toolchain {
        languageVersion = JavaLanguageVersion.of(25)
    }
}

repositories {
    mavenCentral()
}

also, such that each sub-project is consolidated?

Whatever you mean … no. Or you chose extremely awkward words if you meant something correct that I cannot recognize due to not being a native speaker.

Yes, I assume that I don’t find the appropriate words in the gradle context, but maybe this is on me. According to Core Concepts there exists the Build, which produces output.
So yes, the proto sub-project generates output which I consider to be the generated java files based on the proto files.
Next, does the lib produce outputs? I don’t know, this sub-project simply has some files containing formulas and numerical concepts.
Then, we have the sub-projects under service, which produce builds such as jar-files, which I will then continue to dockerize.
But what would you call the overall monorepo-folder? A Project? It is not a “A piece of software that can be build, [..]”, since I build distinct docker images from the sub-projects.
EDIT But yes, maybe this is also a Build, the outputs are then the results of the individual builds of the sub-projects?

Thus, this multi-project approach is for me more a question of organizing and keeping related source code together.

Probably for that reason, I cannot fully grasp “Composite Build”. From my understanding, I could create jar-files from both proto and lib sub-project java-files. And jar-file is my artifact, my build, which I include into the other sub-projects, right? Then I would literally “composite” builds … thinking in terms of jar-files as outputs.
But since they are organized in a common repository, I only need the plain java-files, why should I access them via an imported / included jar-file, when I can use them “directly”?

Maybe this helps a bit to understand my understanding / confusion.

I used plugin { java } and implementation and probably this automatically marks the folders, where the generated code lies, as source sets.

No, afair the Proto plugin you use correctly marks the generated sources as sources of the main source set.

But here, AI told me to use plugin { ´java-library´ } and dependencies { api(libs.protobuf.java) }

If it is to be consumed by other projects, java-library is more appropriate than java, yes.
java is more for “end projects”, java-library is for libraries which also means projects consumed only by other projects in the same build, not necessarily that it gets published separately somewhere.

api vs. implementation is about how the dependencies are used.

You did not say what classes were not found.
It sounded like your generated sources were not found, but if that helped, then most probably the proto classes were not found. If you would have mentioned that or had shown an MCVE, the problem would have been obvious to me. :wink:

If you use a dependency only in non-public API or only in method bodies, then the dependency is an implementation dependency, because you only need it for your implementation in that project but it is not part of the public API.

If you use a dependency in your public API, like in public or protected method signatures as return type or parameter type, or as super-type of public classes and so on, then it is an api dependency which means that downstream projects depending on it also get those dependencies in their compile classpath automatically which they don’t with implementation dependencies to not pollute the downstream compile classpath, which makes compilation faster, more reliable, and also increases the probability of up-to-dateness or cacheability, …

If you use a dependency only at compile-time, like for using annotation classes to annotate things, then it for example is a compileOnly dependency, as downstream projects should neither get this dependency at compile-time, nor at runtime, because a consumer of annotations has to make sure the annotation classes are present and otherwise the annotations are treated like they would not be present. even with runtime retention.

There is also this great plugin, which helps ensuring that you put dependencies to the proper configurations: GitHub - autonomousapps/dependency-analysis-gradle-plugin: Gradle plugin for JVM projects written in Java, Kotlin, Groovy, or Scala; and Android projects written in Java or Kotlin. Provides advice for managing dependencies and other applied plugins · GitHub

However, in the proto sub-project, I added

No, don’t do that.
Do not configure paths, but wire task outputs to task inputs.
The Proto plugin already does that correctly for you, so you do not need to configure this explicitly in any way.

If it still does not work, again, please provide an MCVE.

Would you agree?

If you only have one build with several projects, you don’t need to configure the version catalog.
This snippet you only need if you build a composite build of multiple builds that typically reside in the same repository to use the same version catalog across all those builds in the composite build.

With one build you only need that snippet if you put the version catalog to a non-standard place, name it in a non-standard way, or want to have multiple version catalogs for different use-cases like build-dependencies and production-dependencies or similar.

Moreover, isn’t it possible to centralize these lines

As mentioned earlier, yes, the repository can for example be centralized in the settings script in the dependencyResolutionManagement { ... } block.

To centralize other settings that are project-specific like the toolchain version, the idiomatic best-practice is to have a convention plugin, for example in buildSrc or better in an included build like build-logic, for example implemented as precompiled Kotlin DSL script plugins. Those have almost the same syntax as regular build scripts, and you then group releated settings in those plugin(s) and then just apply that plugin to your individual projects to apply the whole settings at once where you want those conventions to be effective.

also, such that each sub-project is consolidated?

No idea what you mean here.

According to Core Concepts there exists the Build, which produces output.

Of course a build produces outputs, or you would not have a build. :smiley:.
But not everything that produces outputs is called a build.
The build is the whole thing that is defined in your settings script and your project build scripts where the settings script configures the build as a whole and the project build scripts configure each individual project in the build.

Thus, this multi-project approach is for me more a question of organizing and keeping related source code together.

Yes, multi-project builds, as well as composite builds, are ways to organize your sources in logical ways and to also have some kind of architecture boundaries.
You could theoretically also have all in one big single-project build with different source sets and whatnot, but that is usually not a good or idiomatic approach.

From my understanding, I could create jar-files from both proto and lib sub-project java-files.

Not “you could”, “you do”.

And jar-file is my artifact

Yes

my build

No

which I include into the other sub-projects, right?

Kind of, yes.

Then I would literally “composite” builds

No, a build is something defined by a settings script.
And if a settings script includes other builds using includeBuild, then you form a composite build consisting of those two (or more) builds.

But since they are organized in a common repository, I only need the plain java-files, why should I access them via an imported / included jar-file, when I can use them “directly”?

Because that’s the way you do it.
If you organize your sources into multiple projects, then each project produces a jar and at runtime you use all those jars together as individual jars on the classpath or module path.

You could build fat / uber / whatever you call it jar, containing all the class files and even your dependencies’ classes, but this is horribly bad practice that also only works in narrow use-cases and you should imho never try to do that but just do it properly.

When compiling lib that depends on proto, you for example actually do not build the jar and compile against the jar, but you indeed compile against the plain class files on disk, at least if you properly used the java-library plugin and not the java plugin, because - as I said - one of the biggest strenghts of Gradle is to avoid unnecessary work and building the proto jar just to compile lib would be unnecessary. When packaging lib for runtime and getting its dependencies to pack them along, that is when the proto jar is then built, because then you actually need it.

Okay, I got it working. :slight_smile:

Don’t know the exact reason, but I cleaned up the folders - there have been some Spring dependenices in the proto sub-project, which I purged and only go with ´java-library´ and plain proto dependenies and plugins (protoc, protobuf, etc.).

While my statement holds true, that I only need the auto-generated java code from the proto-files I guess I have to honor the workflow though.
So yes, the monorepo is a project and when invoking ./gradlew build this propagets “down” to the sub-projects, for example I see in the terminal :proto:build , etc.
Thus, the projects “builds” by “building” its sub-projects (that’s the reason why I have to put them in the top settings.gradlefile), and then wires them together - everything works out fine, no reason to cut corners.

@Vampire Thanks for staying with me. :heart:

Okay, then for this topic, there is one question left: What can I configure on top-level of the project and not in each sub-project (again) ?

For example, is it possible to put the information about java version and repositories on top level?

java {
    toolchain {
        languageVersion = JavaLanguageVersion.of(26)
    }
}

repositories {
    mavenCentral()
}

For settings.gradle.kts, there is this toolchainManagement closure, but I don’t know how to specifiy the java version, if this is intendend for that?

And according to centralizing repositories, the following code can be put into settings.gradle.kts

dependencyResolutionManagement {
    repositories {
        mavenCentral()
    }
}

But in my IDE, repositories is highlighted with the remark: ‘repositories(org.gradle.api.Action<? super org.gradle.api.artifacts.dsl.RepositoryHandler>)’ is marked unstable with @Incubating

What can I configure on top-level of the project and not in each sub-project (again) ?

Nothing, the “top-level” project is just a project like any other, that happens to be in the tree hierarchy at the top.

Well, you can use bad-practices to do, but that is discouraged, will make problems with configuration cache and latest will make problems with isolated projects.

For example, is it possible to put the information about java version and repositories on top level?

No (short of the bad practices), I already told you where to put those.

For settings.gradle.kts, there is this toolchainManagement closure, but I don’t know how to specifiy the java version, if this is intendend for that?

Do you ever look at the extensive documentation, or just looking at what the IDE suggests and then ask here? :slight_smile: (Toolchains for JVM projects)

That block is to configure where Toolchains you configured to use are provisioned from if you don’t use a plugin that does it for you like the foojay convention plugin. It is not to configure any toolchain itself.

And according to centralizing repositories, the following code can be put into settings.gradle.kts

Yes, that’s also what I said above. :slight_smile:

But in my IDE, repositories is highlighted with the remark: ‘repositories(org.gradle.api.Action<? super org.gradle.api.artifacts.dsl.RepositoryHandler>)’ is marked unstable with @Incubating

Yes, but it is very unlikely it will significantly change.
If you don’t want to use it because of official incubating status, then also here the solution is the same like for the toolchain.
Add it to a convention plugin that you apply to those projects where that convention should be effective.

Yes,
I did read it, but quickly ran into the issue that version catalogue and buildSrc / convention plugin does not work out of the box, see this discussion with some github discussion / suggestion.