Aren Hovsepyan
Aren Hovsepyan

Reputation: 2047

Sharing custom code between two NodeJS microservices

I am creating web app and micorservice for that app, and both need to have same DB model created with Sequelize. What is approach for handling this task with NodeJS?

I am thinking about creating separate module of my DB models and save it in private git and add this private git to my web app and microservice as npm dependency.

But I am wondering is it right approach or what is right way to separate shared private module between few microservices, in my case it is DB models? Should I go with DRY or not?

Thanks in advance!

Upvotes: 3

Views: 1120

Answers (2)

Oswin Noetzelmann
Oswin Noetzelmann

Reputation: 9555

There is no rule about Microservices that code should not reused. In fact stating that DRY is wrong in general with Microservices is dangerous. Rather you should ask the following questions: Will the shared code be a separate module with a dedicated purpose that rectifies a separately managed lifecycle and releases? If yes you should definitely go for reusing it as a separately released module - Similar to how you would reuse any third party library. This ensures that you do not have strong coupling between the shared code and your Microservices, because each Microservice team can decide for themselves if they want to stay with a specific release version of the module or upgrade to a newer version. What you want to avoid is a dependency that forces you to change your microservices when the reused library changes (avoid the ripple effect).

One more thing - Because you are mentioning it being DB related schemas you have to ask another question: Will the schemas being reused in separate DBs or will they refer to the same physical DB in the end?. If they will end up using a shared DB you are effectively tightly coupling the two Microservices and thus they should probably be considered to be part of the same service rather than separate.

I feel this is as much as I can say without knowing more about your services and goals.

Upvotes: 2

Constantin Galbenu
Constantin Galbenu

Reputation: 17683

You should not go with DRY in microservices. Think about one of the advantages of using them: you can replace one microservice with other stack at any time (PHP + Apache) and the system would not care, as long as it respects the contract.

You can read more here, page 59, DRY and the Perils of Code Reuse in Microservices World.

Upvotes: 1

Related Questions