Life of Apps

Compensation Logic using RabbitMQ

After listening to Caitie McCaffrey on the Saga pattern, I added basic compensation logic to the rudimentary order management flow described in this post.

  • To recap, the flow starts with an order being placed through a POST request
  • Then each microservice posts a message on a RabbitMQ Exchange (type: direct) with the completion status as the routing key 
  • The microservice that has to be executed next listens on the "topic" with the binding key for triggering it and starts executing on receipt of a matching message
  • On error, the microservice posts a message with the error text as the routing key e.g. "Order Processing Error". The message payload could contain further details about the error
  • Each microservice also listens on a "topic" with a binding key containing an error and on receipt of a message, it executes the compensation logic 

The complete flow with transaction is as follows:

1. Order Creation
- trigger: POST request
- success: order placed, check inventory
- failure: no order placed, inform and stop execution
- compensation: order cancel, inform and stop execution

2. Inventory Check
- trigger: check inventory message
- success: inventory available, notify shipment (or) inventory unavailable, notify stock replenishment
- failure: inventory unavailable and cannot be replenished notify order creation
- compensation: reset inventory, notify order creation

3. Stock Replenishment
- trigger: stock replenish message
- success: stock replenished, notify shipment
- failure: stock not replenished, notify inventory check
- compensation: none

4. Order Shipment
- trigger: ship order message
- success: order shipped, inform and stop execution
- failure: order not shipped, notify inventory check (for inventory reset)
- compensation: none

Full code is available here.

Danesh

Visit Pleb.in for apps developed by Danesh

No comments :

Post a Comment

Leave a Comment...