Reputation: 21
I have built two microservices and both has read & write access to a shared database. One service creates/updates user details. The other service reads the user data directly from DB and produce reports. Now the question is, if the second microservice has to update some user data for a reason should I use first microservice to update the user data or directly update the user data in the DB from second microservice as it already has write access to the shared database. Is there a bestpractice for this kind of usecase ?
Upvotes: 1
Views: 4714
Reputation: 2847
If you have two microservices that need to read and write the same data to perform their goal, the problem is not what technique or technology you use to do that (shared database connection or exposing a REST api), but why this happens in the first place.
Consider the following two options before sharing data:
Why are two separate microservices in the first place? If they read and write the same data, then they might be fulfilling the same responsibility and they should be a single microservice, not two.
Is the data serving a single responsibility or more? If you model your data/database so that it fulfills two responsibilities, then you not only need two microservices, you also need two databases. I don't know your use case, so it's hard to tell, but for example, if you store the product price and the product description in the same table, both pricing and catalog microservices will share the database, when in practice, they only need to share the ProductId.
Another possibility is that you need to separate your write model from your read model. In this case, you could have one microservice controlling the business logic that causes the model to evolve (writes) and another microservice would store a "copy" of the model optimized for reading. This pattern (CQRS) has several advantages:
You can optimize and scale the read pipeline in a different way than the write pipeline.
The read model can be fed with data from multiple write models if necessary (imagine searching and sorting products by name, category, price, rating, etc).
Upvotes: 3
Reputation: 17648
The shared database pattern is considered to be an anti pattern, since your microservices get intertangled and both will depend on your single database.
By putting an api on top of the service that controls the process, you can let the other service gather information through its endpoints. This wil give you better isolation.
Basically this will dissolve your question.
Upvotes: 0