Search code examples
microservices

Design of Microservices that do not share a database


My requirement is below:

We have 2 microservices.

Product Microservice:

Product Class contains :
productid
productdescription
List

Order Microservice contains:

Order Class:
orderId
orderType
List

Now Product and Order Service reside in different databases.

So when I try to retrieve the order details for order id xxx, I also need the list of products . How to achieve this as we cant have the join here . Also what should be the ideal table structure in this case.

Shall I store the products as list of product_id's inside the Order model ? like List productids; In that case what shall be the table structure(DDL) of Order table.

I understand here we cant have normalization and create a join table as the 2 microservices share different databases.

Also what what is most common approach :

  1. Microservices with shared databases.
  2. Microservices with different databases.

Thanks


Solution

  • First of all, if you are implementing a micro-service architecture your services should not be sharing databases, so far so good.

    Another thing to realize is you can replicate data if you have a reason. In this case I would say you do.

    An order is not a complete order without its order lines, or products. It can be that a product in the Product database gets updated (for example, the same SKU but the color changed from blue to red). That same product ordered last year in blue, is now only available in red. That doesn't change the orders were for red ones last year.

    So think about a "Unit of Consistency" (you can google that). An order is not consistent without its products, its delivery address, invoice address, etc. You should look to store all of those with the order and have the order service responsible for all updates to orders. This is the idea of a "Bounded Context" in DDD.

    If you have a requirement for some order product attributes to be updated when the products in the product service update then the product service should send a message to the order service that contains the changes. Then the order service updates its products as it needs to (or not).

    Forget about a single copy of your data in a microservice architecture. Expect to have multiple copies in different forms that suit each service best. The idea is to make each of the service data stores eventually consistent.

    Read up on Domain Driven Design, especially Bounded Contexts, if you want to seriously think about a microservice architecture. It may well be that Order and Product are not what your bounded contexts should be in your domain, there might be better ways to express your system than the traditional entity based data.