Sharing DTOs between microservices

Viewed 1016

we have about 15 microservices, which are communicating to each other and exchanging DTOs between each other. In our project it is very common, that one DTO is used in several microservices. So we ask ourselves how to define the DTOs. The very first approach would be of course to define the DTOs in each microservice independently from each other. This approach is very simple, but has several disatvantages. Each time we would like to change a DTO in one service, we would have to change it in the other as well.

Our second approach was following: We created several maven projects. This maven projects contain just the DTOs, which are shared between services. So lets assume we have services 1, 2, 3, 4, 5 and DTOs A, B & C. Lets assume DTO A is shared between services 1 & 2. DTOs B & C are shared between services 3, 4 & 5. In this case we would create two maven dependecies, the first one with DTO A, which would be included in the services 1 & 2. The second dependecy would contain the DTOs B & C and would be included in the services 3, 4, 5.

This approach reduces code duplication, because if we update a DTO, we just have to update the version number of the corresponding maven dependency. On the other hand, we still have to touch every service to update the dependeny.

The other disadvantage can be following. First we thought, that service 1 & service 2 would just use the DTO A. After some time new requirements were added and now DTO A should depend on DTO B. So lets imagine DTO A is Vehicle with fields (brand, constructionYear) and DTO B is Motor with field (power). So lets assume the motor DTO is exchanged between the services 2 & 3. The vehicle DTO is exchanged between the services 1 & 2. After some time we receive a requirement, that the vehicle DTO should get a new field motor. So now we have two options:

Option 1: We let the vehicle DTO depend on the motor DTO. Option 2: We create another motor DTO (Motor2), which is included in the vehicle DTO, so we have two motor DTOs and the vehicle does not depend on the initial motor DTO.

The advantage of option 1 is, that we do not have any code duplication. The disadvantage is, that both dtos are in separate maven projects and its quite difficult to mantain them. Because if we change one dto, we have to update the version of the dependency.

The advantage of option 2 is, that the dtos are independent of each other. But if there is a change, we have to touch several places. Of course it is easy to change one DTO in two services. But if the change affects a handful of DTOs, which are exchanged between four or five services, it can be very annoying. Especially it is very common, that during the begin of the project, the requirements change very quickly.

So what is your expirience with exchanging DTOs between microservices/systems. Which approach are you following and what are the advantages or disadvantages of your approach?

0 Answers
Related