microservicesdistributed

Microservice distributed database relationship issues


I faced some confusion when I adopted the Microservice architecture. When I start to design a database, I have no idea how to start.

The question is each service has its database. For example, there are three services now which are "Customer, Product, and Company". Some tables under Customer and Product Services have a relationship.

Therefore should I add these tables to each other?


Solution

  • The simple answer is yes. If there are relationships in between those models and those are needed in the other services, then the correct solution in a microservice architecture is to replicate the data to the other services and have the data stored there as well. You usually do not need to replicate the whole data but only parts (sometimes just holding ids could be enough). If you always need the complete data, than you might want to overthink the split of your microservices as it seems that the coupling is very high.

    The more convoluted answer is that you should be very careful where you set the boundaries of your services. When the coupling in between your models is too high, than it could happen that you end up with sth. called a distributed monolith, what basically means that with almost any change of one service, you have to change the other services as well due to the high coupling. That is sth. you generally want to avoid. Do not fall into the trap of thinking "the more the better". This is a very common anti-pattern applied by people starting with microservices (for more details on the downside of the approach read https://microservices.io/post/antipatterns/2019/05/21/antipattern-more-the-merrier.html). When the coupling is high, than keep the stuff together. In general you should not split up microservices by data model (what your approach looks like), but by functionality as that is where the coupling usually lies.

    One general advise from my side is that often it is better to start with fewer services and split them up as they grow in size. One big issue with designing your services from the start is that you learn a lot about your domain over time and bringing services together when you realize that the coupling is high is very hard.