Sharing code between Micro-services - is it justified in this situation?

Viewed 4326

There are so many answers and blog posts saying "never share code between microservices" and I wonder right now how I am supposed to follow that advice. I've got the following microservices and each of them is communicating via RabbitMQ:

enter image description here

The express server and the two different background services have completely different code, while the request workers are just multiple instances. Each request worker is supposed to process a request and return a direct reply to it once it is done with it (RPC).

My question:

I have written a class (RequestScheduler) which offers methods to schedule a request (e. g. getProfile: Promise<IProfile>). Since I am apparently not allowed to share code between microservices what about the code for the communication between the microservices?

I don't see a way how I could avoid sharing that code along with my microservices on the left side.

3 Answers

Cross-cutting concerns are often not as well documented in discussions I've seen about Microservices architecture - probably because on first blush they seem contrary to the concept (though they are not). While developing our applications (first time using Microservices) we struggled with similar questions to what you are asking. After speaking with some folks who have much more experience in it than we did at the time, we came to realize that the concept of Microservices is much more about Domain encapsulation so hard rules around size, library sharing, etc. are all secondary to the idea of a Microservice having a single responsibility (SRP) and owning a single, well-defined domain (DDD).

We have libraries (which we manage as NuGet packages) for wiring up new services to the event bus(es), managing Authorization, cross-service event logging, and even a standard Middleware for error handling - we share these across nearly all our services.

Though we haven't defined a hard rule on it, I would say we approach code reuse as "If all Microservices in our ecosystem require it, it must be available as a shared library. If most of them could use it, it should be available as a shared library. Each Microservice has the option as to whether or not it implements the shared libraries or rolls its own solutions."

So long as your shared code is distributed in such a way to allow each Microservice to independently manage its own upgrade and your shared code is free from any domain-specific language or concerns, by all means share away!

code for the communication between the microservices looks like kind of a library or a package for me, that would not be changed so often. Why not to use it as a package?

A good options is to make a package in private npm registry. Then you would be able to have different version of that package. So you will be on safe ground using semantic versioning.

Related