mongodbtransactionsmicroservicesreplicationeventual-consistency

Should i use transactions to update child table, if any field changes in Parent table?


product:
    name
    description
    category

productVariants:
    productId
    productName
    sku
    price

What method should I use to reflect changes in the productVariants table, if product name changes in the product table?

Should I use an atomic transaction? Or should I push event in msg queue, and then set listener on productVariants, to reflect the changes?


Solution

  • First of all, you should not denormalize your data, so you should not have productName in the productVariants table.

    For display, I suggest you query the product variants, display them as soon as you get the response, then for each variant, you asynchronously query and display the product by its id. Ideally, set up some cache to avoid querying the same product again and again. If you want to simplify your frontend code, then add a GraphQL layer between your microservices and your frontend, and use GraphQL to aggregate the product variants and the products (GraphQL will do the requests and the caching for you).

    Now if you want to make a cross-query, for example if you want to find product variants by their price and by the category of the product they are related to, then you have to setup a materialized view. Like you suggested, your products and productVariants microservices emit messages at each modification. The materialized view consumes the messages to keep itself up-to-date. It might look complicated to setup a materialized view, but it keeps things under control : you modify normalized data into the two microservices, and the view is read-only. You can have as complex views as you want, it still won't be a mess.