<?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 Si Thu Kyaw on Medium]]></title>
        <description><![CDATA[Stories by Si Thu Kyaw on Medium]]></description>
        <link>https://medium.com/@sithukyaw_31735?source=rss-e4c337b03b52------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Xn3bsWtoE-7dncnhbtWnjw.jpeg</url>
            <title>Stories by Si Thu Kyaw on Medium</title>
            <link>https://medium.com/@sithukyaw_31735?source=rss-e4c337b03b52------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 14:31:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sithukyaw_31735/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[Kafka as a message broker between microservices (Part 1)]]></title>
            <link>https://medium.com/@sithukyaw_31735/kafka-as-a-message-broker-between-microservices-part-1-991ec75f1550?source=rss-e4c337b03b52------2</link>
            <guid isPermaLink="false">https://medium.com/p/991ec75f1550</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[event-driven-design]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Si Thu Kyaw]]></dc:creator>
            <pubDate>Sat, 28 Sep 2024 04:12:11 GMT</pubDate>
            <atom:updated>2024-09-28T07:03:43.587Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Oyu9964pHE4nYI45B7J9MA.jpeg" /></figure><p>In a microservices architecture, <strong>Kafka</strong> can be used as a message broker to enable communication between independent services. Instead of relying on direct API calls, Kafka allows services to exchange data asynchronously in an event-driven manner. This design promotes loose coupling and improves the scalability of the system.</p><h3>Key benefits of this design pattern include:</h3><ul><li><strong>Asynchronous Communication</strong></li><li><strong>Event-Driven Architecture</strong></li><li><strong>Resilience and Fault Tolerance</strong></li><li><strong>Scalability</strong></li></ul><p>In this article, I’ll demonstrate how to use Kafka as a message broker between microservices. To simplify the example, I’ll use two basic Node.js/Express microservices in TypeScript: order-service and inventory-service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*L9SUiZCBDBwZZyqtyYpk2A.png" /></figure><h3>1. Environment Setup</h3><h4>Install Docker</h4><p>Visit the official Docker website to download and install Docker for your operating system from <a href="https://docs.docker.com/desktop/install/windows-install/">here</a>.</p><h4>Install Node.js</h4><p>Download and install Node.js from the official website <a href="https://nodejs.org/en">here</a>. To verify the installation, run the command:</p><pre>node  -v</pre><h4>Install Docker Desktop</h4><p>Download and install docker desktop from <a href="https://www.docker.com/products/docker-desktop/">here</a>.</p><h3>2. Creating Project Structure</h3><p>Let’s create the Node.js services.</p><p>Open your terminal and create a folder called kafka-microservices-demo</p><pre>mkdir kafka-microservices-demo</pre><p>Inside this folder, create two additional folders, order-service and inventory-service</p><pre>cd kafka-microservices-demo<br>mkdir order-service<br>mkdir inventory-service</pre><h3>3. Setting up order-service and inventory-service</h3><p>Navigate into the order-service folder and install the necessary dependencies.</p><pre>cd order-service<br>npm init -y<br>npm install typescript --save-dev<br>npx tsc --init<br>npm install express body-parser kafka-node<br>npm install @types/express @types/body-parser</pre><p>3.1 Create a src folder and a server.ts file inside src. The folder structure should look like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/0*5sH72Yeb8gixeaot" /></figure><p>3.2 We need to modify thepackage.json and tsconfig.json.Add start and build scripts to package.json so that you can run the app with npm start command.</p><pre>{<br>  &quot;name&quot;: &quot;order-service&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;start&quot;: &quot;tsc &amp;&amp; node dist/server.js&quot;<br>  },<br>  &quot;dependencies&quot;: {<br>    &quot;express&quot;: &quot;^4.21.0&quot;,<br>    &quot;body-parser&quot;: &quot;^1.20.3&quot;,<br>    &quot;kafka-node&quot;: &quot;^5.0.0&quot;<br>  },<br>  &quot;devDependencies&quot;: {<br>    &quot;typescript&quot;: &quot;^5.6.2&quot;,<br>    &quot;@types/express&quot;: &quot;^5.0.0&quot;,<br>    &quot;@types/body-parser&quot;: &quot;^1.19.5&quot;<br>  }<br>}</pre><p>3.3 In the tsconfig.json file, add outDir to specify where the compiled JavaScript files should be placed.</p><pre>{<br>  &quot;compilerOptions&quot;: {<br>    &quot;target&quot;: &quot;es2016&quot;,<br>    &quot;module&quot;: &quot;commonjs&quot;,<br>    &quot;outDir&quot;: &quot;./dist&quot;,<br>    &quot;strict&quot;: true<br>  }<br>}</pre><p>3.4 Navigate to the inventory-service folder and install the required dependencies.</p><pre>cd inventory-service<br>npm init -y<br>npm install typescript --save-dev<br>npx tsc --init<br>npm install kafka-node<br>npm install @types/node --save-dev</pre><p>3.5 Update the package.json and tsconfig.json files the same way we did for the order-service.</p><h3>4. Implementing order-service</h3><p>Now, we’ll add logic to order-service.</p><p>The goal is simple: when a user places an order via the order endpoint, order-service will notify inventory-service by sending a message to Kafka.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*XVWnQSMx8H_pAunIBKWSeA.png" /><figcaption>(Figure 2)</figcaption></figure><p>Open server.ts in the order-service/src folder and add the following code to create an Express application.</p><pre>import express, { Request, Response } from &#39;express&#39;;<br>import bodyParser from &#39;body-parser&#39;;<br>import { KafkaClient, Producer } from &#39;kafka-node&#39;;<br><br>const app = express();<br>const port = process.env.PORT || 6500;<br><br>app.use(bodyParser.json());<br><br>const kafkaHost = process.env.KAFKA_BROKER || &#39;localhost:9092&#39;;<br>const client = new KafkaClient({ kafkaHost });<br>const producer = new Producer(client);<br><br>producer.on(&#39;ready&#39;, () =&gt; {<br>    console.log(&#39;Kafka Producer is connected and ready&#39;);<br>});<br><br>producer.on(&#39;error&#39;, (err) =&gt; {<br>    console.log(&#39;Error in Kafka Producer:&#39;, err);<br>});<br><br>app.post(&quot;/order&quot;, (req: Request, res: Response) =&gt; {<br>    const order = req.body;<br>    const payload = [{<br>        topic: &quot;order-topic&quot;,<br>        messages: JSON.stringify(order)<br>    }];<br><br>    producer.send(payload, (err, data) =&gt; {<br>        if (err) {<br>            console.error(&quot;Failed to send order&quot;, err);<br>            return res.status(500).send(&quot;Error processing order&quot;);<br>        }<br>        res.send(&#39;Order received and sent to Kafka&#39;);<br>    });<br>});<br><br>app.listen(port, () =&gt; {<br>    console.log(`Order service running on port ${port}`);<br>});</pre><p>This code sets up an Express server that listens for incoming orders and sends them to a Kafka topic.</p><h3>5. Implementing inventory-service</h3><p>Open server.ts in the inventory-service/src folder and add the following code to create a Kafka consumer:</p><pre>import { Consumer, KafkaClient } from &#39;kafka-node&#39;;<br><br>const kafkaHost = process.env.KAFKA_BROKER || &#39;localhost:9092&#39;;<br>const client = new KafkaClient({ kafkaHost });<br>const consumer = new Consumer(<br>    client,<br>    [{ topic: &quot;order-topic&quot;, partition: 0 }],<br>    { autoCommit: true }<br>);<br><br>consumer.on(&quot;message&quot;, (message) =&gt; {<br>    const order = JSON.parse(message.value as string);<br>    console.log(&quot;Order received:&quot;, order);<br><br>    // Process order, e.g., update inventory<br>    console.log(`Processing inventory for Order ID ${order.id}`);<br>});<br><br>consumer.on(&quot;error&quot;, (error) =&gt; {<br>    console.error(&quot;Error in Kafka consumer:&quot;, error);<br>});</pre><p>The consumer listens for messages on the order-topic and processes the orders received.</p><h3>6. Deployment and Running</h3><p>let’s setup Dockerfiles and docker-compose.yaml file for the deployment.</p><p>6.1 Create a Dockerfile under the order-service folder and put following code to it.</p><pre>FROM node:18-alpine<br><br>WORKDIR /usr/src/app<br><br>COPY package*.json ./<br><br>RUN npm install<br><br>COPY . .<br><br>EXPOSE 6500<br><br>CMD [&quot;npm&quot;, &quot;run&quot;, &quot;start&quot;]</pre><p>Also, create a Dockerfile under the inventory-service folder with the following code.</p><pre>FROM node:18-alpine<br><br>WORKDIR /usr/src/app<br><br>COPY package*.json ./<br><br>RUN npm install<br><br>COPY . .<br><br>EXPOSE 3001<br><br>CMD [&quot;npm&quot;, &quot;run&quot;, &quot;start&quot;]</pre><p>6.2 Go to the project root folder which is “kafka-microservices-demo”. Then create a docker-compose.yml file.</p><pre>version: &#39;2&#39;<br>services:<br>  zookeeper:<br>    image: wurstmeister/zookeeper<br>    ports:<br>      - &quot;2181:2181&quot;<br><br>  kafka:<br>    image: wurstmeister/kafka<br>    ports:<br>      - &quot;9092:9092&quot;<br>    environment:<br>      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092<br>      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181<br>      KAFKA_LISTENERS: PLAINTEXT://0.0.0.0:9092<br>    depends_on:<br>      - zookeeper<br><br>  order-service:<br>    build:<br>      context: ./order-service<br>    environment:<br>      KAFKA_BROKER: kafka:9092<br>    ports:<br>      - &quot;6500:6500&quot;<br>    depends_on:<br>      - kafka<br><br>  inventory-service:<br>    build:<br>      context: ./inventory-service<br>    environment:<br>      KAFKA_BROKER: kafka:9092<br>    depends_on:<br>      - kafka<br><br>  redpanda-console:<br>    image: redpandadata/console:v2.7.2<br>    ports:<br>      - &quot;8080:8080&quot;<br>    environment:<br>      KAFKA_BROKERS: kafka:9092<br>    depends_on:<br>      - kafka</pre><blockquote>In the docker-compose.yaml file, I’ve included two important components: <strong>Zookeeper</strong> and <strong>Redpanda Console</strong>. Here&#39;s why:</blockquote><blockquote><strong>Zookeeper</strong>: Kafka relies on Zookeeper to manage its distributed cluster. Zookeeper helps coordinate various Kafka brokers, handling tasks like leader election, configuration management, and metadata storage. Without Zookeeper, Kafka wouldn’t be able to manage brokers or ensure high availability.</blockquote><blockquote><strong>Redpanda Console</strong>: Monitoring and managing Kafka clusters can be complex, especially in real-world applications. That’s where Redpanda Console comes in. It provides a user-friendly web interface for visualizing Kafka topics, consumer groups, and broker status. This helps with real-time monitoring and troubleshooting, making it easier to see what’s happening in the Kafka ecosystem.</blockquote><blockquote>By integrating these components, we ensure that Kafka is properly managed and monitored in a scalable and production-ready way.</blockquote><p>6.3 Run the following command to deploy all services:</p><pre>docker-compose up --build -d<br></pre><p>You should see something similar to this in the terminal after running the above command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*axAF91wQ11qGuAu2" /><figcaption>(Figure 3)</figcaption></figure><p>In the Container tab of Docker Desktop, you should see the services running.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3e5ZKKG-kky77X-F" /><figcaption>(Figure 4)</figcaption></figure><p>When you look at the logs of the order-service, you will see something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Z-GaH1BN_snGOu5W" /><figcaption>(Figure 5)</figcaption></figure><h3>7. Testing the Services</h3><p>Now, we can test our services using tools like Postman, JMeter, or curl to send a request to the order-service. For simplicity, I will use curl for this demonstration.</p><p>7.1 In the terminal, run this curl command.</p><pre>curl -X POST \<br>  http://localhost:6500/order \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{<br>    &quot;id&quot;: 1,<br>    &quot;item&quot;: &quot;Laptop&quot;,<br>    &quot;quantity&quot;: 2,<br>    &quot;price&quot;: 1500<br>  }&#39;</pre><p>You will see that the order-service has received the request and sent it to Kafka.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JHgdcduR_gbmaJz9" /><figcaption>(Figure 6)</figcaption></figure><p>When you open the logs of inventory-service, you will see it has consumed the message from the kafka.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qlKEk_lSM0_vxtYH" /><figcaption>(Figure 7)</figcaption></figure><p>Open the Redpanda console by navigating to http://localhost:8080 in your web browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hjr1yKKEmeeEQRhQ" /><figcaption>(Figure 8)</figcaption></figure><h3>8. Summary</h3><p>In this article, we explored how to use Kafka as a message broker to enable asynchronous communication between microservices in an event-driven architecture. We set up two services “order-service” and “inventory-service” that communicate through Kafka, demonstrating how to deploy and test them using Docker.</p><p>Stay tuned for part 2, where I will demonstrate how to scale these microservices horizontally by leveraging Kafka’s partitioning and replication features, ensuring resilience and efficient load distribution in our event-driven system.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=991ec75f1550" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>