Video in progress
Several services need to share code (proto files or configuration, for example). How do you choose between a Git submodule and a subtree?
A submodule is a reference to an exact commit of another repository: the code stays separate and the version is precise, but it needs extra steps in clone, update and CI. A subtree copies the other repository's contents into your own history: using it is simple, but sending changes back is awkward.
📖 Answer
Submodule:
git submodule add git@github.com:company/api-contracts.git contracts
git commit -m "api-contracts submodule qo'shildi"
# for others:
git clone --recurse-submodules git@github.com:company/order-service.git
git submodule update --init --recursive
Which commit of the external repository is in use is recorded in the parent repository. Updating is a deliberate step: git pull inside the submodule, then a commit in the parent. Typical problems: someone forgets --recurse-submodules and gets an empty folder; changes made in a detached HEAD get lost; CI needs an extra SSH key.
Subtree:
git subtree add --prefix=contracts git@github.com:company/api-contracts.git main --squash
git subtree pull --prefix=contracts git@github.com:company/api-contracts.git main --squash
The code sits there as ordinary files, and whoever clones does not need to know anything. But sending changes back (subtree push) is complicated, and the two histories get mixed.
In the Java world I often recommend a third way: publish the shared code as a separate artifact (api-contracts-1.7.0.jar) to a Maven repository and tie it in by version. A dependency at the build level instead of at the Git level is much easier to manage. If the services are very tightly coupled, consider a monorepo.
Sign up to mark studied questions and save your progress.