0
votes

I just want to implement microservices in my e-commerce projects. If I have 2 microservices that is the products microservice & transactions microservice in separate project & db & server. and the db design is like this:

products table:
id
name
code
price
...

transactions table:
id
product_id
qty
price
...

The question is: how can I make a Get All transactions API with relation to products? since product in another project & db? should I fetch all transaction, looping over and call get Product detail and then set the product key to the product object one by one? or is there any best workaround for this? Thanks.

I want to return something like this since I want this API returning product relation to show product in the transaction list frontend.

{
  "transactions": [
    {
      "id": 1,
      "product": {
        "id": 1,
        "name": "Bottle",
        "code": "B1",
        "price": 50000
      },
      "qty": 1,
      "price": 50000
    }, {
      "id": 2,
      "product": {
        "id": 2,
        "name": "Cable",
        "code": "C1",
        "price": 20000
      },
      "qty": 1,
      "price": 20000
    } 
  ]
}
1

1 Answers

1
votes

One of the most difficult things to understand when doing service orientation is that the benefits of isolation and autonomy come at a cost. That cost is data duplication. It is extremely difficult to avoid the duplication of data in a microservices architecture.

However, data duplication is not always bad. In fact, you could argue that data duplication is an important enabler. Seeing data duplication as good rather than bad goes against common sense and traditional software training, however you will need to become comfortable with this mindset to succeed with microservices.

In your model above, if you want to display your transactions with some product data alongside, then you are going to need to store that product data in the same database as your transactions, i.e. the transactions service database.

To answer the inevitable question "how does the product data get there?" - it is necessary to add the product data at some previous time, ideally when the product is first created.

If I want to update the product should I change it on the transaction service also?

Yes that is correct, although only if you care about the change (from a transactions perspective). If something on the product changes that you don't care about in transactions then don't update.

how we know which part is needed to be has duplicate data / not?

That is based on your requirements for viewing transactions. The point is this: once you have duplicated your product, it is effectively a different entity to the one in the products service, though it will share an identifier. So you can evolve the product model in your transactions service without worrying about the product model in your products service.