Why shared libraries between microservices are bad?

后端 未结 3 1045
无人共我
无人共我 2020-11-30 10:03

Sam Newman states in his book Building Microservices

The evils of too much coupling between services are far worse than the problems caused b

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-30 10:24

    Good example of tight coupling where duplication would be acceptable can be shared library defining interface/DTOs between services. In particular using the same classes/structs to serialize/deserialize data.

    Let's say you have two services - A and B - they both may accept slightly different but overall almost same looking JSON input.

    It would be tempting to make one DTO describing common keys, also including the very few ones used by service A and service B as a shared library.

    For some time system works fine. Both services add shared library as dependency, build and run properly.

    With time, though, service A requires some additional data that would change the structure of JSON where is was the same before. As a result you can't use the same classes/structs to deserialize the JSON for both services at the same time - the change is needed for service A, but then service B won't be able to deserialize the data.

    You must change shared library, add new feature to service A and rebuild it, then rebuild service B to adjust it to new version of shared library even though no logic has been changed there.

    Now, would you have the DTOs defined separately, internally, for both services from the very beginning, later on, their contracts could evolve separately and safely in any direction you could imagine. Sure, at first it might have looked smelly to keep almost the same DTOs in both services but on the long run it gives you a freedom of change.

    At the end of the day, (micro)services don't differ that much from monolith. Separation of concerns and isolation are critical. Some dependencies can't be avoided (language, framework, etc.) but before you introduce any additional dependency by yourself think twice about future implications.

    I'd rather follow given advice - duplicate DTOs and avoid shared code unless you can't avoid it. It has bitten me in the past. Above scenario is trivial one, but it may be much more nuanced and affect much more services. Unfortunately it hits you only after some time, so the impact may be big.

提交回复
热议问题