I am using relational databases for my microservices. I have CustomersMService
which has its own database with table Customer
, then I have OrdersMService
which also has its own database but with table Order
, and that table has column CustomerId
. How can I ensure data integrity between databases, so Orders
won't point to non-existent Customers
?
-
1Possible duplicate of [Data Consistency Across Microservices](http://stackoverflow.com/questions/43950808/data-consistency-across-microservices) – Oswin Noetzelmann May 19 '17 at 18:44
-
The answer depends on what DBMS (or systems that are supplying DBMS-like functionality) you are using. Please add appropriate tag(s). The topic is distributed datbases. – philipxy May 19 '17 at 19:40
1 Answers
How can I ensure data integrity between databases, so
Orders
won't point to non-existentCustomers
?
There is an important dimension missing, which is that of the span of time over which you wish to establish the referential integrity.
If you ask, "How can I ensure that all my data is 100% consistent at all times?" - you can't. If you want that you will need to enforce it, either via foreign key constraints (which are unavailable across databases), or by never writing to more than one database outside of a distributed transaction (which would defeat the purpose of using service orientation).
If you ask, "How can I ensure that all my data is 100% consistent after a reasonable span of time?", then there are things you can do. A common approach is to implement durable, asynchronous eventing between your services. This ensures that changes can be written locally and then dispatched remotely in a reliable, but offline, manner. A further approach is a caretaker process which periodically remediates inconsistencies in your data.
However, outside of a transaction, even over a reasonable span of time, consistency is impossible to guarantee. If absolute consistency is a requirement for your application then microservices may not be the right approach.

- 30,562
- 14
- 91
- 126