Microservices: how to handle foreign key relationships

Viewed 49622

Microservices architecture suggest that each service should handle it's own data. Hence any service (Service A) dependent on data owned by other service (service B) should access such data not by making direct DB calls but through the api provided by the second service (service B).

So what does microservices best practices suggest on checking foreign key constrains.

Example: I am developing a delivery feature (microservice 1) for products and certain products are deliverable to only certain locations as mentioned in the products table accessible to only products micro service (mircoservice 2).

How do I make sure that microservice 1 (i.e delivery feature) does not take an order to a unserviced location. I have this question because delivery feature can not directly access products database, so there is no constraints applicable at DB level when a delivery order is place in to delivery data base (no check is possible to see if a foreign key match exists in products database or table).

5 Answers

first solution: API Composition

 Implement a query by defining an API Composer, which invoking the
 services that own the data and performs an in-memory join of the
 results

enter image description here

second solution: CQRS

Define a view database, which is a read-only replica that is designed to support that 
query. The application keeps the replica up to data by subscribing to Domain events 
published by the service that own the data.

enter image description here

A 2020 update to this answer is to use a Change Data Capture tool like Debezium. Debezium will monitor your database tables for changes and stream them to Kafka/Pulsar (other pipes) and your subscribers can then capture the changes and synchronize them.

...How do I make sure that microservice 1 (i.e delivery feature) does not take an order to a unserviced location...

You don't do it online, but in a deferred way.

Your service #1 receives the order, perform all validations it can do by itself, and saves it. A deferred service, processes the order and validates the other aspects of it later on. It may come back as rejected, once the location is found to be non-serviceable. Your service will need to gracefully inform that to the user, and maybe even cancel the order.

Related