Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sync data between databases (each database for each instance of a service) in Microservices?

If each instance of service has a separate database in Microservices architecture, how can we keep the data synced? For instance, if instace#1 serves a request and stores data in its database db#1 and another request on instannce#2 wants the data that was inserted to db#1 through instance#1, how can the database db#2 of instance#2 get the data from the database db#1 of instance#2? I think z-scaling is the solution here!

like image 650
JavaYouth Avatar asked Oct 27 '25 05:10

JavaYouth


1 Answers

The microservice architecture uses a pattern called 'Eventual consistency'. Like you described, newly inserted data won't be directly available in all databases. You can read more about it here

That being said, the CQRS pattern is a populair way to solve the data distrubution / eventual consistency problem. enter image description here

By using a messagebroker / bus, you can publish so called 'events' on a queue. Microservices interested in changes / certain entities, can subscribe to those entities and save them in their own database. This enables loosely coupled microservices, and the data necessary for certain entities is stored in the same database. Data duplication is ok, since we use eventual cosistency to make sure (eventually) everything is in sync over all microservices.

More information about the CQRS pattern using microservices can be found here

Here's a more practical example of something i'm working on right now. The language is in Dutch, but the flow should be self explanatory: enter image description here

Hope this helps! I suggest reading up on the following topics: CQRS, microservices, eventual consistency and messagebrokers (rabbitmq, kafka, etc)

like image 148
J-me Avatar answered Oct 28 '25 20:10

J-me



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!