lunes, 2 de octubre de 2023

Sharing data between microservices

 

Since I started working with microservices, I learned a lot of basic rules like:

 

  •        The microservices must be isolated.
  •        The microservices must be small and they must have only one responsibility into business.
  •        The microservices must be developed by isolated and multidisciplinary teams.
  •        The only way to access to microservice business is using the API.
  •        One database can´t be shared by two microservices.

 

And about this last rule I want to discuss because, in my opinion, there are a lot of points of view we have to keep in main to reach the best approach that fits to our company. Everybody agrees that only one microservice can modify the data in one data base but … Who bad would it be if each microservice will be able to read all databases that the microservice need?

 

One rule said that API is the only one microservice contract but if the development team are using the same technology to implement the microservices then microservices develop teams can sign other contracts like libraries that other  microservices develop teams can use it for accessing the data directly without access to the API.

 

Keep in mind, nowadays, the databases technology has a high performance and the databases are implemented with a great users connection capacity. If we only have a one application (the microservice) using the database then we are losing the database performance. In addition, the connection that should be used by other microservices are read only connections. It means that other improvement more because the connection will be read only.

 

Then, may be, the two contracts case would be able to much bad idea.

 

I am going to describe the “two contracs case” by JAVA implementation library. A common communication between microservices would be:

 

 




 

If microservice client “data layer - read” is treated like an API then no development teams lose their independency only sing a other contract. “two contracts case” would be:

 


 


How you can see in the pictures, the sales microservice saves the book microservice call and use the same library to get the books data (the microservice books development team is free to make any change). This solution allows to keep the low couple and avoid inconsistency data (only the owner can write data into database).

 

In conclusion, I know  “two contracts case” is anti-pattern microservice but it would be able to fit to your environment and solve the performance issues. If the  “two contracts case” doesn’t fit your environment at least I recommend you using CQRS but you should not create a view or using other data base. Use the same database for both microservices where one microservice can read/modify data and the other microservice is a query microservices.

 

No hay comentarios: