<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Dhanush Kamath on Medium]]></title>
        <description><![CDATA[Stories by Dhanush Kamath on Medium]]></description>
        <link>https://medium.com/@dhanushnkamath?source=rss-81011daee0d2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*7-q7vFAvQksNKWEDGmDsYg@2x.jpeg</url>
            <title>Stories by Dhanush Kamath on Medium</title>
            <link>https://medium.com/@dhanushnkamath?source=rss-81011daee0d2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 10:46:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dhanushnkamath/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[RabbitMQ: Developing Message-Based Applications]]></title>
            <link>https://medium.com/swlh/rabbitmq-developing-message-based-applications-a56003c55649?source=rss-81011daee0d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/a56003c55649</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Dhanush Kamath]]></dc:creator>
            <pubDate>Sun, 17 Jan 2021 21:03:35 GMT</pubDate>
            <atom:updated>2021-10-13T13:52:23.824Z</atom:updated>
            <content:encoded><![CDATA[<h3>Developing Message-Based Applications with RabbitMQ</h3><h4>Build a distributed food delivery application with Node.js and RabbitMQ. Learn how message-based asynchronous communication works in a distributed system.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*e_sJkzAiTVTB3ncE" /><figcaption>Photo by <a href="https://unsplash.com/@victorbrd?utm_source=medium&amp;utm_medium=referral">Victor Larracuente</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Most modern applications follow one of two thriving architectures — Monolithic or Microservices. In a Monolithic architecture, the application is structured as a single entity making it quite easy to develop, test and deploy. This is a good choice for small applications that do not anticipate a lot of changes. However, for large applications, a Monolithic architecture has proven to be difficult to maintain. The components that constitute a Monolithic architecture are tightly coupled. A small change introduced in one can severely affect the application, if not appropriately implemented. Microservices, on the contrary, segregate the various functionalities of an application into standalone services. These services interact with each other using network calls that follow RPC, REST, Message-based or a combination of these communication styles depending on whether they require synchronous or asynchronous communication.</p><p>This article aims to explain the significance of asynchronous communication in a distributed system and how it can be facilitated with the help of RabbitMQ, a very popular open-source message queuing software. We shall build a system that requires asynchronous communication to process various tasks in the backend — more precisely, a distributed message-based food delivery application using Node.js, Express, MongoDB, RabbitMQ and Docker. We’ll also be injecting faults in the system to examine the resilience it offers.</p><h4>Request-Response Systems</h4><p>The significance of message-based systems can be comprehended by analysing some of the drawbacks of a request-response system such as REST (Representational State Transfer) or RPC (Remote Procedure Call). Request-Response systems employ synchronous communication. In such a system, one service (client) calls another service (server) directly — often through a load balancer — using a protocol such as HTTP.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*N6MnJUiJNi4vsZch.png" /><figcaption>img-1 (source: <a href="https://medium.com/better-programming/understand-the-flow-of-a-http-request-1a268ec193f0">Better Programming</a>)</figcaption></figure><p>Each service is associated with a URL or an IP address that other services use to initiate a connection. As the Microservices architecture comprise numerous independent services, the number of connections between these services become colossally large; consequently, convoluting the system. Additionally, after making the request, the client has to wait for a response from the server. In other words, the client is blocked from performing other tasks until it receives a response or times out. A client triggering an inherently time-consuming service such as one which requires significant computing resources can exacerbate this situation. This can impact the user experience if the client is a frontend application as the UI becomes unresponsive.</p><h4>Message-Based Systems</h4><p>Message-based systems work differently. In such a system, rather than allowing two applications/services to directly communicate with each other, an additional component is introduced as an intermediary. This additional component is known as the Message Broker. The Message Broker is configured to route a message from the sender to the intended receiver, as shown in <em>img-2</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/0*ZGRVn0yGjM-Vsffo.png" /><figcaption>img-2 (source: <a href="https://neiljbrown.com/2017/05/13/message-broker-or-bus-whats-the-difference/">neiljbrown.com</a>)</figcaption></figure><p>A message is just a piece of information that is sent between two applications. Introducing a Message Broker provides some key advantages. It aids in decoupling applications. Since applications interact by employing a Message Broker, they can communicate without directly connecting to each other. Each application only needs to adhere to the data format of this Message Broker and does not need to handle the nuances of interacting with different services. This simplifies incorporating heterogenous applications in the system. Additionally, it provides the functionality of queueing messages which is immensely helpful when triggering a compute intensive service with a significant request processing time. The sender no longer remains blocked from executing other tasks as it no longer waits for a response. Adding messages onto an intermediary queue ensures that a request is not lost even if the receiver is unavailable. This enhances the reliability of the system. Queueing also aids in handling load spikes, permitting the receiving services to be scaled proportionately without losing any messages. From a much broader perspective, Message Brokers increase the flexibility of the system.</p><p>However, it is crucial to not overlook the fact that the sending service does not get an appropriate response as opposed to a request-response system. The sender can remain confident that its request has been received and can continue processing other tasks without getting blocked. Consequently, the communication is asynchronous and is often compared with email since the sender does not expect an immediate response. Another point to note is that the system is now immensely dependent on the Message Broker. If the Message Broker goes down, the system is compromised. This is resolved by deploying a cluster of Message Brokers.</p><h3>RabbitMQ</h3><h4>Overview</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RCe_qUF8U8AV1dUT.png" /></figure><p>RabbitMQ is an extremely popular open-source Message Broker that is used for building message-based systems. The key elements that constitute RabbitMQ — <strong>Producers, Consumers, Exchanges, Bindings </strong>and<strong> Queues</strong> — are shown in <em>img-3</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*5vkI4Ic6v8X6y0liDKwyzg.png" /><figcaption>img-3 (source: <a href="https://www.cloudamqp.com/blog/2015-05-18-part1-rabbitmq-for-beginners-what-is-rabbitmq.html">cloudamqp.com</a>)</figcaption></figure><p>The applications that generate messages are called <strong>Producers</strong>. These messages are published to the RabbitMQ <strong>Exchange</strong>. The Exchange, depending on its configuration, forwards the messages to one or more <strong>Queues</strong> which act as buffers for storing messages. The link between the Exchange and the Queue is called <strong>Binding</strong>. The applications that consume from the Queues are called <strong>Consumers</strong>. It is important to note that once the Producer publishes a message to the Exchange, it does not wait for a response i.e, it is not blocked. This form of communication is facilitated by the <a href="https://www.amqp.org/about/what#:~:text=The%20Advanced%20Message%20Queuing%20Protocol,instructions%20that%20achieve%20their%20goals.">Advanced Message Queueing Protocol</a> or AMQP.</p><h4>Advanced Message Queueing Protocol (AMQP)</h4><p>Though RabbitMQ supports several <a href="https://www.rabbitmq.com/protocols.html">messaging protocols</a>, the most popular one is the <a href="https://www.amqp.org/about/what#:~:text=The%20Advanced%20Message%20Queuing%20Protocol,instructions%20that%20achieve%20their%20goals.">Advanced Message Queueing Protocol (AMQP)</a>. AMQP is a binary protocol. Contrary to text protocols such as HTTP, where the information exchanged between the client and the server is in human-readable text format, AMQP exchanges information (messages) in a binary format. Instead of relying on different fields, the participating entities agree upon a certain structure and find the required information at specific positions in the transmitted binary data.</p><p>The binary data is transmitted as <em>frames</em>,<em> </em>as shown in <em>img-3.</em> The first byte stores the <em>type</em> of the <em>frame</em> and can assume the value <em>HEADER</em>, <em>METHOD</em>, <em>BODY</em> or <em>HEARTBEAT</em>. The next byte stores the <em>channel </em>which identifies an independent thread of messages<em>. </em>Although the client establishes only a single TCP connection with the Message Broker, the connection is multiplexed — contrary to HTTP/1.1. This means that the client and the message-broker can utilise the same TCP connection to transmit multiple independent threads of messages. The next byte indicates the <em>size</em> of the <em>Payload</em>. The first three bytes are collectively called the <em>frame header</em>. The <em>Payload</em> holds data corresponding to the <em>type </em>of the <em>frame</em>. For example, if the <em>type </em>is<em> METHOD</em>, the <em>payload</em> will contain the name of the operation to be performed. If the <em>type </em>is <em>BODY</em>, it will contain the message data that the sender is transmitting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*owLRdPEbQSIQ3ogM.png" /><figcaption>img-4 (source: <a href="https://www.brianstorti.com/speaking-rabbit-amqps-frame-structure/#:~:text=A%20frame%20is%20AMQP%20&#39;s,your%20application%20and%20vice%2Dversa.">brianstorti.com</a>)</figcaption></figure><h4>Exchange Types</h4><p>RabbitMQ Exchanges can be configured in four different ways depending on how the messages are to be routed — <strong>Direct, Fanout, Topic </strong>and<strong> Header</strong>. As explaining the different types of Exchanges would require an article of its own, this article will cover the Fanout Exchange. In a <strong>Fanout Exchange</strong>, messages are forwarded to every queue that is bound to the exchange. This is particularly useful for consumers that need to process the same message in different ways — such as in an online ordering platform where one queue can be used for generating an invoice PDF and another one for sending the order details to the seller.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*tELJdFpoxBo7jtHDLCB33Q.png" /><figcaption>img-5 (source: rabbitmq.com)</figcaption></figure><h3>Burgernaut</h3><h4>Overview</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kEp35IrCW4dpTs-YWDwa1g.png" /></figure><p>The application that we’ll be building in this article is called <a href="https://github.com/dhanushkamath/Burgernaut">Burgernaut</a>. <a href="https://github.com/dhanushkamath/Burgernaut">Burgernaut</a> is a food delivery platform that allows customers to place food orders and track them — well, virtually. It basically mimics order processing and delivery with timeouts. The order placed by a customer is forwarded to an available restaurant and a confirmation email is sent back to the customer. The customer also receives an order ID that can be used to track the order.</p><p>The application has been developed with RabbitMQ, Node.js, Express, MongoDB and Docker. Its purpose is to demonstrate how a simple message-based system can be built. This would not resemble an actual large-scale system. In fact, this is more suitable for an application that triggers a long running task and emails the details to the client.</p><h4>System Architecture and Flow</h4><p><a href="https://github.com/dhanushkamath/Burgernaut">Burgernaut</a> consists of three integral components — order-service, restaurant-service and email-service, as shown in <em>img-6</em>. The order-service exposes REST endpoints that allow clients to fetch the food menu, place an order and track the order in real-time. Once the client places an order, the order-service persists the order details on a MongoDB server, publishes it to a RabbitMQ Exchange and returns a confirmation response which includes the order ID to track the order. The Exchange is configured with a fanout pattern which publishes the order to the two queues that are bound to it - order.process and order.confirmation. While placing it on the queue, the ‘status’ field of the order holds the value ‘pending’. A restaurant-service consumes the order from the order.process queue and an email-service consumes the order from the order.confirmation queue. Once the restaurant-service consumes the order, it modifies the ‘state’ of the order to ‘accepted’ in the database. The email-service on the other hand sends an order confirmation to the email address specified in the order. After a pre-defined time period, the restaurant-service modifies the ‘state’ to ‘delivered’ in the database indicating that the order has been delivered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tevWc8CyE9XLdNZA.png" /><figcaption>img-6</figcaption></figure><p><a href="https://github.com/dhanushkamath/Burgernaut">Burgernaut</a> uses a message-based architecture to enhance scalability, flexibility and loose coupling among the various services it comprises. RabbitMQ, by default, ensures that all the messages consumed from a queue are distributed in a round-robin fashion. Since the restaurant-service and email-service consume from queues, they can be independently scaled - though physically, scaling out the restaurant-service would mean opening new restaurants. The services are configured to process only a limited number of orders at a time to mimic actual business since restaurants have limited staff. The remaining orders wait on the queue to be consumed. The restaurant-service sends an ‘acknowledge’ to RabbitMQ once the order is fully processed - delivered, in our case - to prevent it from being added back onto the queue. If one of the restaurants stop functioning say, due to a power loss, RabbitMQ, being aware that the TCP connection between the restaurant-service and the Exchange has been closed, would automatically add any order that was being processed back onto the queue, making it ready to be consumed by another restaurant-service. This enhances the fault-tolerance of the system. The number of orders that can be handled by the restaurant-service and the amount of time it takes to process an order can be configured with their respective environment variables at the time of deployment.</p><p>As is evident, the system relies on asynchronous communication for its components. This is difficult to achieve with REST or RPC based systems. The system is also dependent on a highly-available and fault-tolerant queueing service for queueing the orders. This prevents overwhelming the downstream components during peak load intervals. RabbitMQ aids in satisfying these requirements. It also enhances the user experience. Instead of rejecting an order during peak load intervals or downtime, the order gets queued and a response is sent immediately to the client. As soon as a restaurant is available, it will consume the order. Simply put, it tells the client — “Hey, we got your order and are working on it. Here’s an order confirmation ID to track it.”</p><h4>Developing Burgernaut</h4><p>I took the liberty of adding all the three services — order-service, restaurant-service and email-service in the same repository 🤓 Go ahead and clone the application from my <a href="https://github.com/dhanushkamath/Burgernaut">GitHub repository</a>. As far as RabbitMQ is concerned, we only need to focus on the mqService.js file present in the src/services<em> </em>folder in each of the three application folders. The rest of the code involves creating an Express application, configuring routes and connecting, querying and sending data to MongoDB.</p><p>The mqService.js file present in order-service/src/services represents a Producer and consequently contains the code to connect to the exchange and publish a message as shown below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/04da60cfe35b6d5811641f94192bdfe2/href">https://medium.com/media/04da60cfe35b6d5811641f94192bdfe2/href</a></iframe><p>The application uses the <em>amqplib</em> library to communicate with RabbitMQ. The <em>amqpConnect()</em> function is used to establish a TCP connection with the exchange and create a <em>Channel</em>. As explained in the AMQP section of this article, the TCP connection is multiplexed with the help of <em>Channels. </em>The <em>publishOrderToExchange() </em>function simply invokes the <em>publish()</em> function on the <em>channel</em> object to publish a message — the JSON request payload, in our case — to the exchange. The <em>injectExchangeService() </em>is an express middleware that injects the <em>publishOrderToExchange() </em>function in the <em>request </em>object. This allows it to be easily extended in the future.</p><p>The mqService.js file present in email-service/src/services and restaurant-service/src/service represents a Consumer and consequently contains the code to connect to the exchange and consume a message. The code for restaurant-service is shown below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/192cf45c3083041aea98a36c8fb81742/href">https://medium.com/media/192cf45c3083041aea98a36c8fb81742/href</a></iframe><p>There are a few important differences here. The code binds a queue to the exchange and configures the <em>prefetch — </em>which sets the maximum number of messages that can be processed at a time. When a message arrives, <em>processOrder() </em>is invoked. This is defined in orderController.js<em> </em>present in restaurant-service/src/service/controllers.This method updates the status of the order in MongoDB to <em>‘accepted’</em>. Once the order is processed — mimicked with a <em>setTimeout() — </em>the status is updated to <em>‘delivered’ </em>and the <em>ack()</em> function on the <em>channel </em>object is invoked to tell the Exchange that the order (message) has been processed successfully. Failing to invoke <em>ack() </em>will place the message back onto the queue.</p><h4>Running Burgernaut</h4><p>Burgernaut consists of containerized services that are deployed using <a href="https://docs.docker.com/compose/">Docker Compose</a>. If you’re new to Docker, I recommend reading my article — ‘<a href="https://medium.com/swlh/containerize-your-personal-projects-with-docker-fe62ca391db8">Containerize your Personal Projects with Docker</a>’.</p><p>Docker Compose deploys each service in a Docker Network, thereby creating a virtual distributed environment. The <a href="https://github.com/dhanushkamath/Burgernaut/blob/main/docker-compose.yml">docker-compose.yml</a> file is shown below. Modify the EMAIL_ID and EMAIL_PWD environment variables in <em>email-service </em>to send email confirmations. In the <em>restaurant-service</em>, control the maximum number of orders that can be processed simultaneously using PREFETCH_COUNT and the order processing time using ORDER_DELIVERY_TIME:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64d78e72115ac7d840b4790dfe5e1886/href">https://medium.com/media/64d78e72115ac7d840b4790dfe5e1886/href</a></iframe><p>To prevent building the images at the time of deployment with <em>docker-compose up, </em>build the images first using the command:</p><pre>$ docker-compose build</pre><p>To replicate the architecture shown in <em>img-6, </em>use the command given below:</p><pre>$ docker-compose up --scale restaurant-service=2</pre><p>Observe the services (containers) being created:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*rytoRz515e3AfkvUh9sgXA.png" /><figcaption>img-7</figcaption></figure><p>Docker Compose launched one container of MongoDB, RabbitMQ, order-service, email-service and two containers of restaurant-service. Use the <a href="https://github.com/dhanushkamath/Burgernaut/tree/main/test">Postman</a> collection present in the /test folder to interact with the application.</p><h4>Placing an Order</h4><p>Placing an order with <em>place-order</em> request defined in the Postman collection will produce a response similar to the one shown below. The order ID is also highlighted. Ensure to update the email address present in the body of the request to receive order confirmations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*Qnn5MtyPL-h4rbYkIZfssA.png" /><figcaption>img-8</figcaption></figure><p>Tracking the order with this order ID using<em> </em>the<em> track-order </em>request will show the <em>status</em> as accepted if it is within the ORDER_DELIVERY_TIME defined in the docker-compose.yml file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*rfGeBLq_EgcDcmK1UecLUg.png" /><figcaption>img-9</figcaption></figure><p>Tracking the order past the ORDER_DELIVERY_TIME will show the <em>status</em> as delivered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*33f-D5Juv61NUkpFR5AwQQ.png" /><figcaption>img-10</figcaption></figure><p>Also, check your inbox for the confirmation — if you had specified your email address in the payload of <em>place-order</em> request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*z6pTIOVVeQ0FULNUyLx8cw.png" /><figcaption>img-11</figcaption></figure><h4>Understanding the Asynchronous Tasks</h4><p>Let’s examine the logs to understand the asynchronous tasks in the backend for the order — <em>6004942dedbd3a00125a9aea</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lkz4EnQoK002EDGSuAL0wA.png" /><figcaption>img-12</figcaption></figure><ol><li>The<em> order-service_1</em> container receives a POST request. It immediately responds with a status code of 201 and the payload shown in <em>img-8.</em></li><li>The Exchange ‘fans-out’ the order to both the queues.</li><li>The <em>restaurant-service_2 </em>container<em> </em>accepts the order from the order.process queue and starts processing the order.</li><li>The <em>email-service_1 </em>container<em> </em>accepts the order from order.confirmation queue and send outs an email to <em>dhanushnarayan1991@gmail.com </em>as shown in<em> img-11.</em></li><li><em>order-service_1</em> gets a request for tracking the order and responds with a status of 200 and the payload shown in img-9.</li><li><em>restaurant-service_2 </em>delivers the order when the timeout defined by ORDER_DELIVERY_TIME finishes.</li></ol><p>Placing an order again will route it to the other restaurant service - in this case, <em>restaurant-service_1</em>. This is because RabbitMQ dispatches messages from a queue in a Round-Robin fashion.</p><p>As an exercise, I encourage you to try placing more than 2*PREFETCH_COUNT orders —assuming that there are 2 <em>restaurant-service</em> containers — and observe how the orders get queued up.</p><h3>Fault Injection</h3><h4>Scenario 1</h4><p>Let’s kill <em>restaurant-service</em> while an order is being prepared (i.e, during the timeout) and observe how RabbitMQ gracefully sends the unprocessed order to another <em>restaurant-service</em>.</p><p>Place an order with the Postman request and execute the command given below in a new terminal window before the order gets ‘delivered’. Use the container id of the <em>restaurant-service</em> processing the order.</p><pre>$ docker container kill &lt;CONTAINER-ID&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MM4aXF--CaEcf6gLAjmeXQ.png" /><figcaption>img-13</figcaption></figure><p>The logs shown in <em>img-13 </em>reveal that the <em>restaurant-service_1 </em>container was killed while processing the order. The TCP connection between this container and RabbitMQ was terminated before it could process the order and send an ‘acknowledge’ — with <em>ack(). </em>Hence, RabbitMQ placed the unprocessed order back onto the queue allowing <em>restaurant-service_2</em> to consume and process it.</p><h4>Scenario 2</h4><p>To understand how orders get queued, let’s kill all the <em>restaurant-service</em> containers and place multiple orders. Kill the containers using the command shown below:</p><pre>docker-compose up --scale restaurant-service=0 -d</pre><p>Now place the orders and track them using Postman. With no <em>restaurant-service </em>to fulfil them, all the orders will be shown as ‘pending’.</p><p>Spin up two containers of <em>restaurant-service</em> and observe what happens.</p><pre>docker-compose up --scale restaurant-service=2 -d</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FP7UkBfQ0m_hYQHU3bGhWg.png" /><figcaption>img-14</figcaption></figure><p>Recall that the RabbitMQ Exchange was publishing messages to queues. As the <em>restaurant-service </em>containers were unavailable to consume from the order.process queue, the messages remained on the queue. When two <em>restaurant-service</em> containers were spun up, the orders were instantly dispatched to them. This is the beauty of a message-based architecture! The system can handle the unavailability of consumers by queueing up the messages. Had the system been implemented with a request-response architecture, all the orders placed during the downtime would’ve been lost. For an actual firm, this would unfortunately result in a loss of revenue.</p><h3>Conclusion</h3><p>Message-based communication is an integral part of distributed systems. They allow heterogeneous components to seamlessly interact over the network. We saw how developing message-based systems with RabbitMQ facilitated the integration of asynchronous tasks such as sending an email and triggering a time-consuming process. We also injected two common faults and observed how RabbitMQ handles them. In our system, the client immediately receives a response with an identifier that allows it to track the task while the task is being executed asynchronously in the backend. This is just one example of a message-based architecture. We’ve barely scratched the surface!</p><p>You can find the complete source code in my <a href="https://github.com/dhanushkamath/Burgernaut">GitHub repository</a>.</p><h3>Further Reading</h3><ol><li>RabbitMQ tutorials — <a href="https://www.rabbitmq.com/getstarted.html">https://www.rabbitmq.com/getstarted.html</a></li><li>A good explanation on the types of exchanges — <a href="https://www.cloudamqp.com/blog/2015-09-03-part4-rabbitmq-for-beginners-exchanges-routing-keys-bindings.html">https://www.cloudamqp.com/blog/2015-09-03-part4-rabbitmq-for-beginners-exchanges-routing-keys-bindings.html</a></li><li>REST, RPC and Brokered Messaging — <a href="https://medium.com/@natemurthy/rest-rpc-and-brokered-messaging-b775aeb0db3">https://medium.com/@natemurthy/rest-rpc-and-brokered-messaging-b775aeb0db3</a></li><li>Monolithic vs Microservices Architecture — <a href="https://articles.microservices.com/monolithic-vs-microservices-architecture-5c4848858f59">https://articles.microservices.com/monolithic-vs-microservices-architecture-5c4848858f59</a></li><li>Messaging in Microservices -<a href="https://microservices.io/patterns/communication-style/messaging.html">https://microservices.io/patterns/communication-style/messaging.html</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a56003c55649" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/rabbitmq-developing-message-based-applications-a56003c55649">RabbitMQ: Developing Message-Based Applications</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Containerize Your Personal Projects With Docker]]></title>
            <link>https://medium.com/swlh/containerize-your-personal-projects-with-docker-fe62ca391db8?source=rss-81011daee0d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe62ca391db8</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Dhanush Kamath]]></dc:creator>
            <pubDate>Tue, 05 Jan 2021 18:39:37 GMT</pubDate>
            <atom:updated>2021-06-15T10:58:59.417Z</atom:updated>
            <content:encoded><![CDATA[<h3>Containerize your projects with Docker</h3><h4>Containerize a RESTful Node.js application to seamlessly run, ship and deploy it anywhere.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xuDVaBmxgAeXE4-y" /><figcaption>Photo by <a href="https://unsplash.com/@alvarordesign?utm_source=medium&amp;utm_medium=referral">Alvaro Reyes</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Docker is a platform that allows you to build, ship and run your application on any computer that also has Docker installed. If you’ve collaborated on a software development project, either at your workplace or for a hackathon, you would be aware that getting your application running on another plaform may not be so straightforward. As a developer, once you’ve managed to get your application running on your computer with Docker, it is guaranteed to run on other platforms — from laptops to virtual machines in the cloud! In essence, Docker helps solve the old “<a href="https://www.reddit.com/r/ProgrammerHumor/comments/70we66/it_works_on_my_machine/">But it works on my machine!</a>” problem.</p><p>Any modern application would have several dependencies. Most development stacks have distinct ways of managing these dependencies. Node.js has the Node Package Manager (NPM), wherein all the dependencies are defined in an easy-to-read <em>package.json</em> file. If you’re a Python user, you would most likely use a <em>requirements.txt</em> file. Though this takes care of application specific dependencies, it doesn’t necessarily guarantee that the application would run the same on any computer. There can be a plethora of reasons why this may happen — a version mismatch, different operating systems and what not! Even if you manage to write up a robust installation script, there are still solid reasons why Dockerizing your application would be quite beneficial. With the growing popularity of Microservices, where large monolithic applications are broken down into smaller autonomous services, Docker helps to encapsulate these services into isolated runtime environments known as <em>containers</em>. These containers turn out to be a lot more resource efficient than deploying the application with virtual machine (VM) instances.</p><p>This article is meant to help developers employ Docker in their projects to containerize their applications. We’ll be containerizing an extremely simple RESTful application for adding and retrieving books. The source code for this application can be accessed from my <a href="https://github.com/dhanushkamath/dockerize-node">GitHub Repository</a>. The application was deliberately made simple as the focus is on Docker and not on any particular development stack.</p><h3>Containerization</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-a1h7KV6tjx-EKwv" /><figcaption>Photo by <a href="https://unsplash.com/@max_williams?utm_source=medium&amp;utm_medium=referral">Max Williams</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Containerizing your application with docker begins with the process of creating a Docker Image. A Docker Image is a read-only template that packages everything needed for your application. This includes the runtime, application source code, application specific dependencies, system libraries and commands to configure and run your application. Docker uses these images to run Docker Containers. These containers are isolated environments that run your application. Simply put, a container is an instance of a docker image running your application.</p><p>This can be comprehended quite easily with an analogy. Say someone gifted you a DIY Robotics Kit. It contains everything needed to build a robot —an instruction manual, a microcontroller, motors, sensors and other parts. After referring to the instruction manual, you manage to get the robot up and running. Anybody with the same kit can easily build an identical robot. The DIY Robotics Kit is analogous to a Docker Image — it contains everything that is required to get your application up and running. The robot is analogous to a Docker Container.</p><p>Similar to how building this robot only requires the DIY Robotics Kit and someone who can understand the instructions, running a containerized application only requires the Docker Image and a Docker host. The robotics kit can be picked up from a store while Docker Images can be <em>pulled </em>from a repository such as <a href="https://hub.docker.com/">Docker Hub</a>. Everything that is required to build and run the application is contained in the Docker Image. In fact, you don’t even need Node.js installed in your computer to run a containerized Node.js application!</p><h3>Benefits of Containerization</h3><p>Apart from helping you share a runnable copy of your application, Docker Containers have the added advantage of being more resource efficient than virtual machine (VM) instances.</p><p>Consider the scenario where you have three applications that have to be deployed on a popular cloud platform. Assume that only one running instance is required per application. You would start by creating three VM instances for each application (refer img-1), installing an operating system and the required packages, cloning the source code from a code hosting platform such as GitHub, installing the application specific dependencies and finally building/configuring the application for production. Though some fundamental steps are automated with the help of VM images (like <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html">Amazon Machine Images</a> (AMI) in AWS), you would still have to ensure that the application and its dependencies are configured correctly in your production environment. Also, since each VM instance runs its own copy of an operating system, the total CPU and RAM consumption rises significantly as you start scaling or deploying more applications.</p><p>With Docker, instead of sharing source code, developers share read-only templates known as Docker Images that contain instructions for creating Docker Containers. These Docker Containers can start much faster than virtual machines. As long as Docker is installed on the host system, running your application is as simple as executing a single command from the terminal. These Docker containers are a lot more efficient as well. While virtual machines virtualize the underlying hardware, allowing you to run multiple operating systems on the same physical host, containers allow you to run multiple applications in virtually isolated environments by sharing the same operating system. This means that you do not need three copies of the operating system to deploy three applications. Containers share the kernel of the host operating system which makes them lightweight, as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XBDzH8kPBzO5oW492NdLDg.png" /><figcaption>img-1 (source: <a href="https://www.docker.com/blog/containers-replacing-virtual-machines/">https://www.docker.com/blog/containers-replacing-virtual-machines/</a>)</figcaption></figure><h3>Docker Overview</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/0*k1QKLiBuQdiGxpaM.png" /></figure><p>With Docker, developers can easily containerize their applications and reap the benefits of containerization. At the heart of Docker, is the Docker Engine. The Docker Engine is a client-server application that comprises the docker server, a REST API and a command line interface, as shown in img-2. The Docker server (<em>dockerd</em>) is a daemon process that builds and manages docker containers. It also listens for Docker API requests. The REST API provides the interface to communicate with <em>dockerd</em> to perform operations such as starting/stopping a container and obtaining container information. In most cases, the command line interface (CLI) — which also uses the REST API — is what you would employ to interact with Docker from your terminal. If you want to interact with Docker using say Python, Docker provides an SDK. If an SDK is not available for the programming language of your choice, you can always rely on the REST API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/0*NWvXjJxE331RzqTJ.png" /><figcaption>img-2 (source: <a href="https://docs.docker.com/get-started/overview/">https://docs.docker.com/get-started/overview/</a>)</figcaption></figure><h3>Containerizing an application</h3><h4><strong>Application Overview</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/0*9qTlkAIuDpXnvJ9e.png" /></figure><p>The application that we will be containerizing is a very simple RESTful application for storing and retrieving books (<a href="https://github.com/dhanushkamath/dockerize-node">GitHub Repository</a>) developed with Node.js, Express and MongoDB. The application exposes one endpoint - ‘<em>/api/books</em>’ that supports <em>POST</em> and <em>GET</em> to store and retrieve books respectively. It also exposes an ‘<em>/api/info</em>’ endpoint that only supports <em>GET</em> and is meant to return a generic response to check if the application is deployed successfully. The API specification can be found inside <a href="https://github.com/dhanushkamath/dockerize-node/blob/develop/Readme.md#API">Readme.md</a>.</p><p>Note: If you’re keen to try running this application without Docker, you would have to follow all the steps mentioned inside <a href="https://github.com/dhanushkamath/dockerize-node/blob/develop/Readme.md#API">Readme.md</a> after cloning the repository. This means you would have to install Node.js and MongoDB - assuming you do not have them installed on your computer.</p><h4>Building the Docker Image</h4><p>Before creating a Docker Image, clone the source code from my <a href="https://github.com/dhanushkamath/dockerize-node">GitHub Repository</a>. Recall that Docker Images are read-only templates that contain everything needed to run your application. A Docker Image is built using a <em>Dockerfile. </em>The <em>Dockerfile </em>is a text-file that contains a series of instructions as shown below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9de48a678b28a91a845cb8ae71367e5f/href">https://medium.com/media/9de48a678b28a91a845cb8ae71367e5f/href</a></iframe><p>After the Dockerfile has been created, the Docker Image can be built with the <a href="https://docs.docker.com/engine/reference/commandline/build/"><em>build</em></a><em> </em>command. You can also tag your image with the <em>-t</em> flag. Tagging is recommended as it helps to build and identify different images easily. The <a href="https://docs.docker.com/engine/reference/commandline/build/"><em>build</em></a><em> </em>command is given below:</p><pre>docker build &lt;path-to-Dockerfile&gt; -t &lt;repository&gt;/&lt;image&gt;:&lt;tag&gt;</pre><p>Example:</p><pre>docker build . -t dhanushkamath/dockerize-node:1.0.0</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tdm-YGP_IJp0cTGL.png" /></figure><p>Once the image is built you can view all your local images using the <a href="https://docs.docker.com/engine/reference/commandline/image_ls/"><em>image ls </em></a>command:</p><pre>docker image ls</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9KnLIaG0e0YOILfuhu2Yag.png" /></figure><h4>Running a Docker Container</h4><p>Use the <a href="https://docs.docker.com/engine/reference/run/"><em>run</em></a><em> </em>command to create and start a container from this image. Along with the <a href="https://docs.docker.com/engine/reference/run/"><em>run</em></a><em> </em>command, it is necessary to specify the port mapping. This is done with the <em>-p</em> flag. Recall that containers are virtually isolated environments. Although our app is listening on port 3000, it is not accessible to our local machine. It can only be accessed by containers on the same <a href="https://docs.docker.com/network/">Docker Network</a>. Hence, to make the application accessible to entities outside the Docker Network, it is mandatory to map the container port to a port on the host machine. You can also name your container with the <em>name </em>option<em>.</em></p><pre>docker run -p &lt;host-port&gt;:&lt;container-port&gt; --name=&lt;container-name&gt; &lt;repository&gt;/&lt;image&gt;:&lt;tag&gt;</pre><p>Example:</p><pre>docker run -p 80:3000 --name=dockerize-node dhanushkamath/dockerize-node:1.0.0</pre><p>To view your running containers, execute the command given below. Include the <em>-a </em>flag to view stopped containers as well.</p><pre>docker container ls</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u5qjmZMa3oESnwKQBXAIAQ.png" /></figure><p>Now execute a GET request to <a href="http://localhost/api/info"><em>http://localhost/api/info</em></a><em> </em>either directly from the browser or using the ‘testService’ request defined in the Postman collection present in the <a href="https://github.com/dhanushkamath/dockerize-node/tree/develop/test">test folder</a>. Ideally, you should be seeing this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*UQNs9Ap-zBO9YJGHX1NWeg.png" /></figure><p>The application will run regardless of whether you have Node.js installed on your computer or not. This is because we have specified in our <em>Dockerfile </em>that our image is to be built from <a href="https://hub.docker.com/_/node">node:15.5.0</a>. This contains Node.js and NPM. Consequently, they are packaged along with our application. Pretty neat, right?</p><h4>Publishing a Docker Image</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/0*w7Su0tCOGP0YRION.png" /></figure><p>To share your image with the world, you first need to create a <a href="https://docs.docker.com/docker-id/">Docker ID</a>. Use the Docker ID to login to <a href="https://hub.docker.com/">Docker Hub</a> and <a href="https://docs.docker.com/docker-hub/repos/">create a repository</a>. A repository is where all your tagged images would be pushed into.</p><p>Now login through the CLI by executing:</p><pre>docker login</pre><p>Push your Docker Image to the Docker Hub repository with the following command:</p><pre>docker image push &lt;repository&gt;/&lt;image&gt;:&lt;tag&gt;</pre><p>Example:</p><pre>docker image push dhanushkamath/dockerize-node:1.0.0</pre><p>You’ve successfully published your first image to the world!</p><p>Running this container on a different computer that has Docker only requires a single command:</p><pre>docker run dhanushkamath/dockerize-node:1.0.0</pre><p>This is how powerful Docker is! Go ahead and try it on another computer. This command will pull the image from your Docker Hub repository and run the container on the new computer.</p><p>However, we are not done yet because our book application does not have a MongoDB server to connect to for storing the books. If you have MongoDB installed in your computer, feel free to start the <em>mongod </em>service and the app would work just fine. Otherwise, trying to execute a <em>GET</em> or <em>POST </em>on <em>/api/books </em>will crash our application! Though proper error handling is always recommended, it was omitted to deliberately invoke this behaviour 😉</p><p>Since this article focusses on Docker, we’ll be using a <a href="https://hub.docker.com/_/mongo">MongoDB</a> container which can be pulled directly from DockerHub. Whenever we start our application, we also need to start a MongoDB container. Hence, our application comprises two containers — a Node.js application container which exposes the API endpoints and a MongoDB container for persisting data. This makes our application a multi-container Docker application. Our application also uses an environment variable that stores the name of this MongoDB container to connect to it — explained in the upcoming sections. To recapitulate, at runtime, our application container is reliant on the MongoDB container, appropriate port mappings and environment variables. Though all of this can be specified using commands on the CLI, there exists a more convenient method to elegantly configure multi-container deployments— <a href="https://docs.docker.com/compose/">Docker Compose</a>.</p><h4>Stopping and Removing a Container</h4><p>Before proceeding further, stop the Docker Container by executing the following commands:</p><pre>docker stop dockerize-node</pre><p>Execute the <em>docker container</em> <em>ls </em>command with and without the <em>-a</em> flag and notice the difference. Observe the <em>STATUS </em>column.</p><p>Now remove the docker container by executing:</p><pre>docker rm dockerize-node</pre><p>Execute the <em>docker container</em> <em>ls -a </em>command again.</p><h4>Docker Compose</h4><p><a href="https://docs.docker.com/compose/">Docker Compose</a> allows you to specify all of the runtime information your application needs — other containers/services, port mappings, environment variables — in a yaml file. This can be a boon when you have several services (containers) that your application is reliant on. Take a look at the YAML file below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b80b85a425c0f12e9c639be1643c6e3/href">https://medium.com/media/7b80b85a425c0f12e9c639be1643c6e3/href</a></iframe><p>The environment variable <em>MONGO_CONTAINER_NAME</em> is used in <a href="https://github.com/dhanushkamath/dockerize-node/blob/develop/index.js"><em>index.js</em></a> to form the MongoDB connection string as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*uTusBnCiX91wQxjEyeBRFA.png" /></figure><p>So our database string would essentially be <em>mongodb://</em><strong><em>mongo</em></strong><em>:27017/bookDB. </em>Surprised?</p><p>Each container belongs to a <a href="https://docs.docker.com/compose/networking/">Docker Network</a> and is assigned an IP address randomly. All the services (containers) defined in the YAML file are added to the same <a href="https://docs.docker.com/compose/networking/">Docker Network</a> allowing one service to talk to another. Docker has a DNS that allows containers to look up the names of other containers and obtain their IP addresses. This is why our <em>app</em> container is able to connect to the <em>mongo</em> container by using the <em>mongo</em> hostname. Even though the <em>mongo</em> hostname can be replaced with the MongoDB container’s IP address, it is inadvisable because IP addresses are randomly assigned.</p><p>To run our application, execute the command:</p><pre>docker-compose up</pre><p>Now that our entire application is up and running, use the <a href="https://github.com/dhanushkamath/dockerize-node/tree/develop/test">Postman</a> collection to test it.</p><h4>Persisting Container Data</h4><p>In case you haven’t observed, every time we destroy our MongoDB container, the stored data also gets destroyed rendering our database absolutely pointless. This is because each container has its own isolated filesystem and all the stored data gets erased the moment the container ceases to exist. As a simple exercise to the reader, I leave it up to you to make the changes — which are absolutely minimal.</p><p><em>Hint: Use </em><a href="https://docs.docker.com/storage/volumes/"><em>Volumes</em></a><em>.</em></p><h3>Conclusion</h3><p>In this article, we have seen how Docker can be used as a powerful resource to seamlessly ship and deploy applications. We have successfully Dockerized a RESTful application developed with Node.js, Express and MongoDB to create a multi-container Docker application. Developers should now be able to containerize their applications with Docker and not worry about setting up the right environment for their applications to run.</p><p>For further reading, I would recommend <a href="https://docs.docker.com/get-started/">Docker Docs</a> which are lucid and well-maintained.</p><p>You can find the complete source code in my <a href="https://github.com/dhanushkamath/dockerize-node"><strong>GitHub Repository</strong></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe62ca391db8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/containerize-your-personal-projects-with-docker-fe62ca391db8">Containerize Your Personal Projects With Docker</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generating new faces with Variational Autoencoders]]></title>
            <link>https://medium.com/data-science/generating-new-faces-with-variational-autoencoders-d13cfcb5f0a8?source=rss-81011daee0d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/d13cfcb5f0a8</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[generative-model]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[variational-autoencoder]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Dhanush Kamath]]></dc:creator>
            <pubDate>Sun, 16 Feb 2020 09:37:54 GMT</pubDate>
            <atom:updated>2021-01-19T07:28:22.978Z</atom:updated>
            <content:encoded><![CDATA[<h4>A comprehensive tutorial on using a Variational Autoencoder to generate new faces.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nGNKVE7XIhuej_F7yS6cVA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@wish07?utm_source=medium&amp;utm_medium=referral">Vidushi Rajput</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Deep generative models are gaining tremendous popularity, both in the industry as well as academic research. The idea of a computer program generating new human faces or new animals can be quite exciting. Deep generative models take a slightly different approach compared to supervised learning which we shall discuss very soon.</p><p>This tutorial covers the basics of Generative Deep Learning with Variational Autoencoders. I am assuming that you are fairly familiar with the concepts of Convolutional Neural Networks and representation learning. If not, I would recommend watching Andrej Karpathy’s <a href="https://www.youtube.com/playlist?list=PLkt2uSq6rBVctENoVBg1TpCC7OQi31AlC">CS231n lecture videos</a> as they are, in my honest opinion, the best resource for learning CNNs on the internet. You can also find the lecture notes for the course <a href="http://cs231n.github.io/">here</a>.</p><p>This example demonstrates the process of building and training a VAE using Keras to generate new faces. We shall be using the <a href="https://www.kaggle.com/jessicali9530/celeba-dataset">CelebFaces Attributes (CelebA) Dataset</a> from Kaggle and <a href="https://colab.research.google.com/">Google Colab</a> for training the VAE model.</p><h3>Generative Models</h3><p>If you’re beginning to explore the field of Generative Deep Learning, a Variational Autoencoder (VAE) is ideal to kick off your journey. The VAE architecture is intuitive and simple to understand. Contrary to a discriminative model such as a CNN classifier, a generative model attempts to learn the underlying distribution of the data rather than classifying the data into one of many categories. A well trained CNN classifier would be highly accurate in differentiating an image of a car from that of a house. However, this does not accomplish our objective of generating images of cars and houses.</p><p>A discriminative model learns to capture useful information from the data and utilise that information to classify a new data point into one of two or more categories. From a probabilistic perspective, a discriminative model estimates the probability 𝑝(𝑦|𝑥), where 𝑦 is the category or class and 𝑥 is the data point. It estimates the probability of a datapoint 𝑥 belonging to the category 𝑦. For example, the probability of an image being that of a car or a house.</p><p>A generative model learns the underlying distribution of the data that explains how the data was generated. In essence, it mimics the underlying distribution and allows us to sample from it to generate new data. It can be defined as estimating the probability 𝑝(𝑥), where 𝑥 is the data point. It estimates the probability of observing the data point 𝑥 in the distribution.</p><h3>Simple Autoencoder</h3><p>Before delving into a Variational Autoencoder, it is crucial to analyse a simple Autoencoder.</p><p>A simple or Vanilla Autoencoder consists of two neural networks — an Encoder and a Decoder. An Encoder is responsible for converting an image into a compact lower dimensional vector (or latent vector). This latent vector is a compressed representation of the image. The Encoder, therefore maps an input from the higher dimensional input space to the lower dimensional latent space. This is similar to a CNN classifier. In a CNN classifier, this latent vector would be subsequently fed into a softmax layer to compute individual class probabilities. However, in an Autoencoder, this latent vector is fed into the Decoder. The Decoder is a different neural network that tries to reconstruct the image, thereby mapping from the lower dimensional latent space to the higher dimensional output space. The Encoder and Decoder perform mappings that are exactly opposite to each other, as shown in the image <em>img-1</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*wKE69-fX180Q_gkzYzGbwg.png" /><figcaption>img-1 (Source : en.wikipedia.org/wiki/Autoencoder)</figcaption></figure><p>Consider the following analogy to understand this better. Imagine you’re playing a game with your friend over the phone. The rules of the game are simple. You are presented with a number of different cylinders. Your task is to describe the cylinders to your friend who will then attempt to recreate them out of modelling clay. You are forbidden from sending pictures. How will you convey this information?</p><p>Since any cylinder can be constructed with two parameters — its height and diameter, the most efficient strategy would be to estimate these two measures and convey them to your friend. Your friend, upon receiving this information can then reconstruct the cylinder. In this example, it is quite evident that you are performing the function of an Encoder by condensing visual information into two quantities. Your friend, on the contrary, is performing the function of a Decoder by utilising this condensed information to recreate the cylinder.</p><h3>Housekeeping</h3><h4>Downloading the dataset</h4><p>The dataset can be downloaded directly into your Google Colab environment using the <a href="https://www.kaggle.com/docs/api">Kaggle API</a> as shown below. You can refer to this <a href="https://medium.com/@opalkabert/downloading-kaggle-datasets-into-google-colab-fb9654c94235">post</a> on Medium for more details.</p><p>Upload Kaggle.json downloaded from your registered kaggle account.</p><pre>!pip install -U -q kaggle<br>!mkdir -p ~/.kaggle</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5c1bc241d0bbbe546e3a3cb5374df41/href">https://medium.com/media/f5c1bc241d0bbbe546e3a3cb5374df41/href</a></iframe><p>Download the dataset from Kaggle.</p><pre>!cp kaggle.json ~/.kaggle/<br>!kaggle datasets download -d jessicali9530/celeba-dataset</pre><p>Defining the project structure.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/794341b947982778f1432d27aed27091/href">https://medium.com/media/794341b947982778f1432d27aed27091/href</a></iframe><p><em>CAUTION (for Colab users) : Do not attempt to explore the directory using the viewer on the left as the page becomes unresponsive owing to the large size of the dataset.</em></p><h4>Imports</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c622807aab5f2e31e43b51c5ac3e387/href">https://medium.com/media/7c622807aab5f2e31e43b51c5ac3e387/href</a></iframe><h4>Data</h4><p>Since the dataset is quite large, we shall create an <em>ImageDataGenerator</em> object and employ its member function — <em>flow_from_directory</em> to define the flow of data directly from disk rather than loading the entire dataset into memory. The ImageDataGenerator can also be used to dynamically apply various transformations for image augmentation which is particularly useful in the case of small datasets.</p><p>I highly encourage you to refer to the <a href="https://keras.io/preprocessing/image/#flow_from_directory">documentation</a> for understanding the various parameters of the dataflow function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cbb200a06437db0e3617734a2240711f/href">https://medium.com/media/cbb200a06437db0e3617734a2240711f/href</a></iframe><h3>Model Architecture</h3><h4>Building the Encoder</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e3a3557f886e96accbaa88b1fc028d6/href">https://medium.com/media/5e3a3557f886e96accbaa88b1fc028d6/href</a></iframe><p>The architecture of the Encoder, as shown below, consists of a stack of convolutional layers followed by a dense (fully connected) layer which outputs a vector of size 200.</p><p><em>NOTE : The combination of padding = ‘same’ and stride = 2 will produce an output tensor half the size of the input tensor in both height and width. The depth/channels aren’t affected as they are numerically equal to the number of filters.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q9Z1qTU873AFG71WodyyIQ.png" /></figure><h4>Building the Decoder</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/39e20db9ff5c139289b453b87ce01bb7/href">https://medium.com/media/39e20db9ff5c139289b453b87ce01bb7/href</a></iframe><p>Recall that it is the function of the Decoder to reconstruct the image from the latent vector. Therefore, it is necessary to define the decoder so as to increase the size of the activations gradually through the network. This can be achieved either through the <a href="https://keras.io/layers/convolutional/#upsampling2d">UpSampling2D</a> layer or the <a href="https://keras.io/layers/convolutional/#conv2dtranspose">Conv2DTransponse</a> layer.</p><p>Here, the Conv2DTranspose Layer is employed. This layer produces an output tensor double the size of the input tensor in both height and width.</p><p><em>NOTE : The Decoder, in this example, is defined to be a mirror image of the encoder, which is not mandatory.</em></p><h4>Attaching the Decoder to the Encoder</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/92f68ca1da6e88e7bb8603383c3a0afa/href">https://medium.com/media/92f68ca1da6e88e7bb8603383c3a0afa/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OEG-Nf5wuMpeLNE7KJAp9A.png" /></figure><h3>Compilation and Training</h3><p>The loss function used is a simple Root Mean Square Error (RMSE). The true output is the same batch of images that was fed to the model at its input layer. The Adam optimizer is optimizing the RMSE error for encoding the batch of images into their respective latent vectors and subsequently decoding them to reconstruct the images.</p><p>The ModelCheckpoint Keras callback saves the model weights for reuse. It overwrites the file with a fresh set of weights after every epoch.</p><p><em>NOTE : If you’re using Google Colab, either download the weights to disc or mount your Google Drive.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f8caba2f7fa2529194e372b9cedb095d/href">https://medium.com/media/f8caba2f7fa2529194e372b9cedb095d/href</a></iframe><p><em>TIP: Here’s a really useful tip I found on Reddit (by arvind1096) — to prevent Google Colab from disconnecting due to a timeout issue, execute the following JS function in the Google Chrome console.</em></p><pre>function ClickConnect(){console.log(“Working”);document.querySelector(“colab-toolbar-button#connect”).click()}setInterval(ClickConnect,60000)</pre><h3>Reconstruction</h3><p>The first step is to generate a new batch of images using the ImageDataGenerator defined in the ‘Data’ section at the top. The images are returned as an array and the number of images is equal to <em>BATCH_SIZE</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2389984d4fa3b3d663959de7c3b24933/href">https://medium.com/media/2389984d4fa3b3d663959de7c3b24933/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a0f-Rr4hcGKXkDmANpGfRQ.png" /></figure><p>The first row shows images directly from the dataset and the second row shows images that have been passed through the Autoencoder. Evidently, the model has learned to encode and decode (reconstruct) fairly well.</p><p><em>NOTE: A reason why the images lack sharpness is due to the RMSE loss as it averages out the differences between individual pixel values.</em></p><h3>Drawbacks</h3><h4>Adding noise vectors sampled from a standard normal distribution to the image encodings</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c953ec7172adacb04d86617e610e9a37/href">https://medium.com/media/c953ec7172adacb04d86617e610e9a37/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vCciZN_HkquxOAJHyhGFMg.png" /></figure><p>It can be observed that the images are starting to get distorted with a bit of noise added to its encodings. One possible reason could be that the model did not ensure that the space around the encoded values (latent space) was continuous.</p><h4>Attempting to generate images from latent vectors sampled from a standard normal distribution</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64d6d600ca61942f8af82f38d183faa5/href">https://medium.com/media/64d6d600ca61942f8af82f38d183faa5/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-q2CbJioo8dJBwT6pbL6pQ.png" /></figure><p>It is evident that the latent vector sampled from a standard normal distribution can not be used to generate new faces. This shows that the latent vectors generated by the model are not centred/symmetrical around the origin. This also strengthens our inference that the latent space is not continuous.</p><p>Since we do not have a definite distribution to sample latent vectors from, it is unclear as to how we can generate new faces. We observed that adding a bit of noise to the latent vector does not produce new faces. We can encode and decode images but that does not meet our objective.</p><p>Building on this thought, wouldn’t it be great if we could generate new faces from latent vectors sampled from a standard normal distribution? This is essentially what a Variational Autoencoder is capable of.</p><h3>Variational Autoencoder</h3><p>Variational Autencoders tackle most of the problems discussed above. They are trained to generate new faces from latent vectors sampled from a standard normal distribution. While a Simple Autoencoder learns to map each image to a fixed point in the latent space, the Encoder of a Variational Autoencoder (VAE) maps each image to a z-dimensional standard normal distribution.</p><h4>How can a simple Autoencoder be modified to make the encoder map to a z-dimensional standard normal distribution?</h4><p>Any z-dimensional normal distribution can be represented by a mean vector 𝜇 and a covariance matrix Σ.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*C7JhczjKFeAjwaCViDE76Q.png" /></figure><p><strong>Therefore, in the case of a VAE, the encoder should output a mean vector (</strong>𝜇<strong>) and a covariance matrix (</strong>Σ<strong>) to map to a normal distribution, right?</strong></p><p>Yes, however, there are slight modifications to be made to the covariance matrix Σ.</p><p><strong>Modification 1) </strong>It is assumed that there is no correlation between the elements of the latent vector. Hence, the non-diagonal elements, representing covariance, are all zeroes. The covariance matrix is, therefore, a diagonal matrix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*ovuSvmjKmRpNfoK5QtjRaw.png" /></figure><p>As the diagonal elements of this matrix represent variance, it is simply represented as 𝜎2, a z-dimensional variance vector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*Uf4cKk0yEKrYAWRyBfSjiA.png" /></figure><p><strong>Modification 2) </strong>Recall that the variance can only take non-negative values. To ensure that the output of the encoder is unbounded, the encoder is actually mapped to the mean vector and the <strong>logarithm</strong> of the variance vector. The logarithm ensures that the output can now take up any value in the range, (−∞,∞). This makes training easier as the outputs of the neural network are naturally unbounded.</p><p><strong>Now, how is it ensured that the Encoder maps to a standard normal distribution (i.e., with a mean of 0 and a standard deviation of 1)?</strong></p><p>Enter KL divergence.</p><p><strong>KL divergence</strong> provides a measurement of the extent to which one probability distribution differs from another. The KL divergence between a distribution with mean 𝜇 and standard deviation 𝜎, and the standard normal distribution, takes up the form:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*gFaSS_VOr-Kx9IOKDTPkpA.png" /></figure><p>By slightly modifying the loss function to include the KL divergence loss in addition to the RMSE loss, the VAE is forced to ensure that the encodings are very similar to a multivariate standard normal distribution. Since a multivariate standard normal distribution has a zero mean, it is centered around the origin. Mapping each image to a standard normal distribution as opposed to a fixed point ensures that the latent space is continuous and the latent vectors are centered around the origin.</p><p>Take a look at the image <em>img-2</em> for a better understanding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n0VZIk0_gSVJozS5PtiKaQ.jpeg" /><figcaption>img-2 (Source : blog.bayeslabs.co/2019/06/04/All-you-need-to-know-about-Vae)</figcaption></figure><h4>If the encoder maps to 𝜇 and 𝜎 instead of a z-dimensional latent vector, what is the input given to the Decoder during training?</h4><p>The input to the Decoder, as shown in <em>img-2</em>, is a vector sampled from the normal distribution represented by the output of the Encoder — 𝜇 and 𝜎. This sampling can be done as follows:</p><p>𝑍=𝜇+𝜎𝜀</p><p>where 𝜀 is sampled from a multivariate standard normal distribution.</p><h4>How do we generate new faces?</h4><p>Since the KL divergence ensures that the encoder maps as close to a standard normal distribution as possible, we can sample from a z-dimensional standard normal distribution and feed it to the decoder to generate new images.</p><h4>Does the decoder require any modification?</h4><p>No, the decoder remains the same. It is identical to that of a Simple Autoencoder.</p><h3>VAE Model Architecture</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee69f166a24fa01dcc912becc43eaffa/href">https://medium.com/media/ee69f166a24fa01dcc912becc43eaffa/href</a></iframe><p>The encoder architecture has minor changes. It now has two outputs : mu (mean) and log_var (logarithm of variance) as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V-u3N_t6kxsHz76asduyWg.png" /></figure><h4>Building the Decoder</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d3164d9552d0893a2761842be1f1ac05/href">https://medium.com/media/d3164d9552d0893a2761842be1f1ac05/href</a></iframe><p>Since the Decoder remains the same, the Decoder architecture of the Simple Autoencoder is reused.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YM5meQmzpK4SrW1F_p6-8g.png" /></figure><h4>Attaching the Decoder to the Encoder</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b9d617fbde2f8276998f033a872db63/href">https://medium.com/media/0b9d617fbde2f8276998f033a872db63/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PwRJiBJICK1NdV3RsnyePg.png" /></figure><h3>Compilation and Training</h3><p>The loss function is a sum of RMSE and KL Divergence. A weight is assigned to the RMSE loss, known as the loss factor. The loss factor is multiplied with the RMSE loss. If we use a high loss factor, the drawbacks of a Simple Autoencoder start to appear. However, if we use a loss factor too low, the quality of the reconstructed images will be poor. Hence the loss factor is a hyperparameter that needs to be tuned.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d30c5130457b20d99e55e31641d8569/href">https://medium.com/media/1d30c5130457b20d99e55e31641d8569/href</a></iframe><h3>Reconstruction</h3><p>The reconstruction process is the same as that of the Simple Autoencoder.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c66026050d50eda6b624f02a138d5baa/href">https://medium.com/media/c66026050d50eda6b624f02a138d5baa/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W5AnCJmd90kLL_PDwIOssQ.png" /></figure><p>The reconstruction results are quite similar to that of a Simple Autoencoder.</p><h4>Generating new faces from random vectors sampled from a standard normal distribution.</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d6103b79750c1c9ba8be1c4021ff9d6/href">https://medium.com/media/0d6103b79750c1c9ba8be1c4021ff9d6/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bNmzMZe2M108ypMPV-1OZw.png" /></figure><p>The VAE is evidently capable enough of producing new faces from vectors samped from a standard normal distribution. The fact that a neural network is capable of generating new faces from random noise shows how powerful it is in performing extremely complex mappings!</p><p>As it is impossible to visualize a 200 dimensional vector, some of the elements of the latent vector are individually visualized to see if they are close to a standard normal distribution.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d410d2a11eab03012fc4068e23778003/href">https://medium.com/media/d410d2a11eab03012fc4068e23778003/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z0h1gY1hpDC45-7f06aSRQ.png" /></figure><p>It is observed that the first 30 elements of the Z dimensional vector are very similar to a standard normal distribution. The addition of the KL divergence term is therefore, justified.</p><h3>Conclusion</h3><p>As we have observed, a Variational Autoencoder fulfils our objective of creating a generative model. The VAE has learnt to mimic the underlying distribution of the data and perform a very complex mapping between a multivariate standard normal distribution and the face data. In other words, we can sample a latent vector from a multivariate standard normal distribution and our VAE model converts the vector into a new face.</p><p>The notebook for this tutorial can be accessed from my<em> </em><a href="https://github.com/dhanushkamath/VariationalAutoencoder"><strong>GitHub repository</strong></a><strong>.</strong></p><p>For further reading, I would recommend Carl Doersch’s <a href="https://arxiv.org/abs/1606.05908"><strong>Tutorial on Variational Autoencoders</strong></a><em>.</em></p><p>Feel free to connect with me on <a href="https://www.linkedin.com/in/dhanushkamath/"><strong>LinkedIn</strong></a> and <a href="https://github.com/dhanushkamath"><strong>GitHub</strong></a>.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d13cfcb5f0a8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/generating-new-faces-with-variational-autoencoders-d13cfcb5f0a8">Generating new faces with Variational Autoencoders</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>