Life of Apps

Understanding MicroServices Choreography using RabbitMQ & Node.js

A colleague and I had discussed on choreography of microservices a while ago and the topic came up for discussion again recently. In order to ensure that I understood the nuances correctly, I decided to write some code to implement the approach. Here are the tools/technologies that I chose:

  • Node.js for building the microservices 
  • Restify for exposing Restful APIs
  • CloudAMQP - a RabbitMQ as a service offering as the integration bus
  • amqp.node - a Node.js client library for RabbitMQ.  

CloudAMQP offers a free tier good enough for learning and trying things out. It also comes with an easy to use management console that gives good statistics. The tutorials and articles are useful too.

There is a host of options for the Node.js RabbitMQ client libraries. I tried a few and then settled with amqp.node as the RabbitMQ site had their tutorials on it. The library comes in two flavours, one with callbacks and the other with promises. Being comfortable with callbacks, I opted for it.

The approach that I followed was to mimic a part of the order management process where a POST method triggers the order creation service. The service processes the order, creates an entry in the order management database and sends a message to a RabbitMQ topic. Following is the code snippet.

Another service listens to the topic for a specific key that denotes that the order creation is complete and gets triggered when a message with that key is published. This service checks for inventory and either calls a service to replenish stock if it is low or calls an order shipment service if the stock is available. It too publishes a message on the topic with the respective keys to trigger the following services.  Following is the code snippet.

The code below publishes and consumes from a RabbitMQ topic. Apache Kafka can be used as an alternative to RabbitMQ as an event bus.

This approach will work while creating new microservices as they can be made to start on the basis of an event.

As can be seen from the code, it is heavily work in progress. I am hoping to do the following tasks:

  • Figuring out a good way of closing RabbitMQ connections Done:Updated the code to use npm module death to run a function on process kill to close RabbitMQ connections
  • Making modules out of some common code functions Done: moved the helper functions for HTTP methods and RabbitMQ to a module. 
  • Add compensation logic Done: this post explains the compensation logic 
  • Add an OpenAPI (Swagger) spec Done: added a spec for Order Creation here
  • Create Docker containers 
Full code is available here.


Visit for apps developed by Danesh

No comments :

Post a Comment

Leave a Comment...