Fanout Async Messaging Design In Microservices Using RabbitMQ

Introduction

 
Asynchronous messaging pattern is an indispensable design choice when it comes to microservice communications. In this design pattern, one microservice can publish a message and doesn't need to wait for completion of processing  by the consumer to proceed with its work.
 
There are various techniques that could be implemented to achieve asynchronous interactions among microservices. In this article, I shall talk about a use case where we would be using a message broker – RabbitMQ – and “Fanout” technique to implement the asynchronous messaging pattern in action.
 

What is the “Fanout” Messaging Pattern?

 
Fanout is a messaging design where the published message from a particular publisher is consumed by multiple different subscribers independently and simultaneously. The intention is that the same published message will be consumed by different consumers and be processed in different ways.
 
In a message broker like RabbitMQ, the publisher publishes a message which is put into different queues through a special type of exchange called “Fanout Exchange”.
 
Consumers listening to these queues get the same message to be consumed.
 
The below diagram shows a diagrammatic representation of “Fanout” messaging pattern.
 
Fanout Async Messaging Design In Microservices Using RabbitMQ
 

When to Use Fanout Pattern?

 
The use case of fanout pattern is applicable in places where a publisher needs to asynchronously communicate to multiple consumers on a single workload.
An example could be: Let’s say in an online library system, a microservice is responsible for placing the borrowing request for a book – Book Rent service. Here, once a book is successfully rented out to a customer, this service can act as a publisher and produce a message for other services that are responsible for (i) Removing this from the customer’s ‘Wishlist’, (ii) Reducing the availability count for this book in the online library shelf, (iii) Updating the “Currently Reading Shelf” of the customer. These consumer services would listen for the same message in different queues and can work on this notification independently without making the renting process to wait. Here the publisher, “fans out” the message in different queues where interested consumers are hooked into it for consuming the message. The publisher here, the Book Rent service, doesn't need to wait until other services are finished acting on the message and can seamlessly and independently issue the book to the customer and carry out more renting requests making it available for the users.
 

Refresher on “Exchanges”, “Bindings”, “Routing Keys” on RabbitMQ

 
As a refresher or quick reckoner, I am delineating the different key aspects of the RabbitMQ message broker that we would be using in the prototype. However, I encourage you to go for further readings to have in-depth understanding on these topics.
 

Exchanges

 
Exchange is the place where all the published messages first land from publishers and then get routed to different queues. This could be compared to a mailbox or a hub where all the messages arrive and then based on the routing key, header attribute and binding are forwarded to respective queues.
 
Following are the types of exchanges supported in RabbitMQ,
  • Direct
  • Fanout
  • Topic
  • Headers
Bindings
 
Binding links a queue to an exchange.
 
Routing Keys
 
Routing Key is one of the attributes that the exchanges look for while deciding which queue the message will be routed to. However, in the case of a “Fanout” type of exchange this key doesn’t have any significance and remains ignored.
 
Prototype
 
In my earlier article I had demonstrated how to spin-up and communicate to a RabbitMQ container. This demo would be based on the same infrastructure.
 
To begin, (A) I would create an exchange of type “Fanout” in my running RabbitMQ instance. After that (B) I would declare three different queues to be bound to this exchange. Once this is ready, (C) I shall publish a message to the exchange through the rent-out service.
 
Below code snippets shows these steps, 
  1. private const string FANOUT_EXCHANGE = "fanout.exchange";
  2. private const string WISHLIST_QUEUE = "wishListQueue";  
  3. private const string LIBRARY_SHELF_QUEUE = "libraryShelfQueue";  
  4. private const string READING_SHELF = "readingShelfQueue";
  1. var factory = new ConnectionFactory()  
  2.             {  
  3.                 Uri = new Uri("amqp://guest:guest@localhost:5672")  
  4.             };  
  5.   
  6.             using (var connection = factory.CreateConnection())  
  7.             using (var channel = connection.CreateModel())  
  8.             {  
  9.                 // declare exchange of type "Fanout"  
  10.                 channel.ExchangeDeclare(exchange:FANOUT_EXCHANGE, type: ExchangeType.Fanout);  
  11.   
  12.                 // declare queue : Wishlist Queue  
  13.                 channel.QueueDeclare(queue: WISHLIST_QUEUE,  
  14.                                      durable: false,  
  15.                                      exclusive: false,  
  16.                                      autoDelete: false,  
  17.                                      arguments: null);  
  18.                 // bindind the wishlist queue to the "Fanout" exchange  
  19.                 channel.QueueBind(queue: WISHLIST_QUEUE, exchange: FANOUT_EXCHANGE, routingKey:"");  
  20.   
  21.                 // declare queue : Library Shelf Queue  
  22.                 channel.QueueDeclare(queue: LIBRARY_SHELF_QUEUE,  
  23.                                      durable: false,  
  24.                                      exclusive: false,  
  25.                                      autoDelete: false,  
  26.                                      arguments: null);  
  27.                 // bindind the Library Shelf Queue to the "Fanout" exchange  
  28.                 channel.QueueBind(queue: LIBRARY_SHELF_QUEUE, exchange: FANOUT_EXCHANGE, routingKey: "");  
  29.   
  30.                 // declare queue : Reading Shelf Queue  
  31.                 channel.QueueDeclare(queue: READING_SHELF,  
  32.                                      durable: false,  
  33.                                      exclusive: false,  
  34.                                      autoDelete: false,  
  35.                                      arguments: null);  
  36.                 // bindind the Reading Shelf to the "Fanout" exchange  
  37.                 channel.QueueBind(queue: READING_SHELF, exchange: FANOUT_EXCHANGE, routingKey: "");  
  38.   
  39.   
  40.   
  41.   
  42.                 // publish message  
  43.                 string message = "ID of the Book which is Rented out: " + id;  
  44.                 var body = Encoding.UTF8.GetBytes(message);  
  45.   
  46.                 channel.BasicPublish(exchange: FANOUT_EXCHANGE,  
  47.                                     routingKey: "",  
  48.                                     basicProperties: null,  
  49.                                     body: body);  
  50.   
  51.             }  
With this code executed, when I check in the RabbitMQ management console, I should see the following:
A new exchange with the given name is created and being listed,

Fanout Async Messaging Design In Microservices Using RabbitMQ
 
Three new queues are created which are now bound to that new Fanout exchange,
 
Fanout Async Messaging Design In Microservices Using RabbitMQ
 
The single new message has been queued in three different queues as per the “Fanout” pattern,
 
Fanout Async Messaging Design In Microservices Using RabbitMQ

Now let us spin up our consumers who are configured to listen to these three different queues. A sample code from one of the consumers – WishListService – where it consumes the messages from the respective queue: wishListQueue
  1. //establish connection  
  2.             var factory = new ConnectionFactory()  
  3.             {  
  4.                 Uri = new Uri("amqp://guest:guest@localhost:5672")  
  5.             };  
  6.             var rabbitMqConnection = factory.CreateConnection();  
  7.             var rabbitMqChannel = rabbitMqConnection.CreateModel();  
  8.   
  9.             rabbitMqChannel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false);  
  10.   
  11.             //consume the message received  
  12.             var consumer = new EventingBasicConsumer(rabbitMqChannel);  
  13.             consumer.Received += (model, args) =>  
  14.             {  
  15.                 var body = args.Body;  
  16.                 var message = Encoding.UTF8.GetString(body.ToArray());  
  17.                 Console.WriteLine("Book ID To be removed from Wishlist: " + message);  
  18.                 rabbitMqChannel.BasicAck(deliveryTag: args.DeliveryTag, multiple: true);  
  19.                 Thread.Sleep(1000);  
  20.             };  
  21.             rabbitMqChannel.BasicConsume(queue: WISHLIST_QUEUE,  
  22.                                          autoAck: false,  
  23.                                          consumer: consumer);  
  24.             Console.ReadLine();  
Once we run these consumers, the output looks like this,
 
Fanout Async Messaging Design In Microservices Using RabbitMQ
 
In this prototype, I am sending a Book ID to the publisher service through a Web API call which publishes a message with the book ID in the message broker fanout exchange and then the following consumer services are consuming the message to process the workload independently,
  1. WishListService
  2. LibraryShelfService
  3. CurrentReadingShelfService
Here is the complete snapshot that shows all these working in a single image,
 
Fanout Async Messaging Design In Microservices Using RabbitMQ
 

Summary

 
In this article, we first understood the Fanout async messaging pattern which could be used in Microservice communications. We then started exploring how this could be achieved through a message broker such as RabbitMQ. For that we created a prototype based on our hypothetical online digital library system where the renting service publishes a single message upon successfully renting out a book. This message is published through a Fanout exchange in RabbitMQ which places it in different bound queues. Consumer services listening to the respective queue pick up this message and process them independently. This way we ensure our Renting service is not blocked for any independent work to be completed and free for picking up the next request for renting out while other services perform their work independently on each rent request.