Search code examples
microservices

How to avoid synchronous and use asynchronous effectively?


Intro

Hey, my question is kind of hard to explain so I apologize in advance.

Question

I'm trying to implement microservices for our ecommerce and I'm having issues on how to respond to a request when the actual logic and data needs to be determined by other ( 2-3 ) services.

In order to make it easier to understand, I'll give an example.

Lets say User A is trying to buy a product. after clicking on "check out" button these steps should happen.

Flow

Request comes in:

  • Ecommerce service:
    1. Check if product has enough quantity in inventory.
    2. Publish an event indicating a new order has been created. order:created
  • Anti Fraud service:
    1. Receives order:created and checks whether the user is a fraud or not
    2. Publishes an event indicating the check was successful. check:succeed
  • Payment Service:
    1. Receives check:succeed and creates a url to the gateway.
    2. Sends the gateway url to the user. (( this is where the question arises ))

Since all of these steps are asynchronous, how do I respond to the request?

Possible Solution

After the user has requested to checkout, the ecommerce service creates an order and responds immediately with the orderId of newly created order, on client-side the user has to request periodically and check whether the status of order is PENDING PAYMENT, in order to achieve this, the payment service needs to publish payment:created after the order has been approved by the system and then ecommerce service can update the order.

My solution works, but I'm really new to microservices and I want to ask from experts like you on how to implement this in a better way.

I really appreciate if you read this far, Thank you for your time.


Solution

  • your flow is a synchronous process. you need a result from previous step so it has to go step by step.

    point of system view:

    what matters here is: "how to handle steps?". which reminds me SAGA design pattern (specially when you need a rollback handling) but in general there are two types (choreography and orchestration). The choreography describes the interactions between multiple services, where as orchestration represents control from one party's perspective.

    for simplicity you can implement the command pattern or use EAI(Enterprise Application Integration) tools like Apache camel to handle message between endpoints according to the flow.

    if you have a lots of visitors it's also better to use a queue between endpoints whether with an orchestrator or without.

    point of user view:

    when a user click to checkout their cart. they don't expect many of steps or to do more than just wait. as keeping the connection open for response is not a good idea maybe a loader and a periodically ajax call behind it is quite enough while there are other solutions like push notification (then you can consider on fire and forget mechanism).