The question here is should we always reuse the common code across microservices and avoid duplication as we do in the OO development (DRY)?
We often group common functionalities in a library so they can be reused by different applications without duplicating the code. We might be tempted to do the same in microservice architecture and use shared libraries. This approach may look like a good way to reduce code duplication in the services. But this can be problematic because the shared libraries create coupling between microservices. Indeed, changes and fixes that we do in the shared library can result in a cascade of upgrades (and redeployment) of all the microservices using this library.
A solution would be to keep the shared library small and contain only the code that is considered stable and unlikely to change.
The other option to consider is to extract out the shared code that’s likely to change in a new service.
This can be particularly interesting if this new service represents a domain such as billing that will be called by the other services that need this common feature.
But duplicating the code across the different microservices can be the best option if the shared libraries are changing frequently and risk creating tight coupling between microservices.
To summarize, consider the following criteria to help you decide which approach to prefer:
– If the common code you want to reuse is stable, a shared library can be the right option.
– If the number of the microservices using the common code is large and the shared code changes frequently avoid the temptation of using a shared library.
– Where the common can represent a domain feature, creating a new service can be a better alternative.
– In the other cases, consider duplicating the code across the microservices.