<?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 Pawara Gunawardena on Medium]]></title>
        <description><![CDATA[Stories by Pawara Gunawardena on Medium]]></description>
        <link>https://medium.com/@pawara?source=rss-ef2234f38408------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ioBLMt4pQ-bYbdYA</url>
            <title>Stories by Pawara Gunawardena on Medium</title>
            <link>https://medium.com/@pawara?source=rss-ef2234f38408------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 17:58:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pawara/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[Binary Search Tree]]></title>
            <link>https://medium.com/@pawara/binary-search-tree-847aa4d87eec?source=rss-ef2234f38408------2</link>
            <guid isPermaLink="false">https://medium.com/p/847aa4d87eec</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[binary-search-tree]]></category>
            <dc:creator><![CDATA[Pawara Gunawardena]]></dc:creator>
            <pubDate>Sun, 25 Oct 2026 18:31:25 GMT</pubDate>
            <atom:updated>2026-10-25T18:31:25.173Z</atom:updated>
            <content:encoded><![CDATA[<p>A <a href="https://en.wikipedia.org/wiki/Binary_search_tree">binary search tree</a> is a <a href="https://en.wikipedia.org/wiki/Binary_tree">binary tree</a> that satisfies the following property:</p><p><em>For each node x and any node y in the subtrees of x,</em></p><ul><li><em>If y is in the left subtree of x, then</em></li></ul><pre>y.key &lt; x.key</pre><ul><li><em>If y is in the right subtree of x, then</em></li></ul><pre>y.key &gt; x.key</pre><p>The above comparison condition excludes duplicate entries. If required, the comparison condition can be modified to allow duplicate values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*owaknFt-Q9mpGh0-4UwV0g.png" /></figure><p>The binary search tree insertion, search, and removal operations take O(log(n)) time in the average case and O(n) time in the worst case, where n is the number of elements.</p><h4>Implementation</h4><p>Consider <em>Node</em> of the Binary Search Tree.</p><pre>struct Node {<br>    int value;<br>    Node* left;<br>    Node* right;<br><br>    Node(int value, Node* left = nullptr, Node* right = nullptr):value(value), left(left), right(right) {}<br>};</pre><p>Define <em>BinarySearchTree</em> with a private Node struct, along with other member variables and member functions.</p><pre>#pragma once<br><br>class BinarySearchTree {<br>private:<br>    struct Node {<br>        int value;<br>        Node* left;<br>        Node* right;<br><br>        Node(int value, Node* left = nullptr, Node* right = nullptr):value(value), left(left), right(right) {}<br>    };<br>    Node* insert(Node* subtreeRoot, int value);<br>    bool search(Node* subtreeRoot, int value);<br>    Node* remove(Node* subtreeRoot, int value);<br>    Node *findMinNode(Node* subtreeRoot);<br>    void printInOrder(Node* subtreeRoot);<br>    void clear(Node* node);<br><br>    Node* root;<br><br>public:<br>    BinarySearchTree();<br>    ~BinarySearchTree();<br>    BinarySearchTree(const BinarySearchTree&amp; other) = delete;<br>    BinarySearchTree&amp; operator=(const BinarySearchTree&amp; other) = delete;<br>    void insert(int value);<br>    bool search(int value);<br>    void remove(int value);<br>    void printInOrder();<br>};</pre><pre>#include &lt;iostream&gt;<br>#include &quot;BinarySearchTree.h&quot;<br><br>BinarySearchTree::BinarySearchTree() : root(nullptr) {<br><br>}<br><br>BinarySearchTree::~BinarySearchTree() {<br>    clear(root);<br>}<br><br>void BinarySearchTree::insert(int value) {<br>    root = insert(root, value);<br>}<br><br>bool BinarySearchTree::search(int value) {<br>    return search(root, value);<br>}<br><br>void BinarySearchTree::remove(int value) {<br>    root = remove(root, value);<br>}<br><br>void BinarySearchTree::printInOrder() {<br>    printInOrder(root);<br>    std::cout &lt;&lt; std::endl;<br>}<br><br>BinarySearchTree::Node *BinarySearchTree::insert(Node* subtreeRoot, int value) {<br>    if(!subtreeRoot) {<br>        return new Node(value);<br>    }<br>    else if (value &lt; subtreeRoot-&gt;value) {<br>        subtreeRoot-&gt;left = insert(subtreeRoot-&gt;left, value);<br>    }<br>    else if (value &gt; subtreeRoot-&gt;value){<br>        subtreeRoot-&gt;right = insert(subtreeRoot-&gt;right, value);<br>    }<br>    return subtreeRoot;<br>}<br><br>bool BinarySearchTree::search(Node* subtreeRoot, int value) {<br>    if(!subtreeRoot) {<br>        return false;<br>    }<br>    if (value == subtreeRoot-&gt;value) {<br>        return true;<br>    }<br>    else if(value &lt; subtreeRoot-&gt;value) {<br>        return search(subtreeRoot-&gt;left, value);<br>    }<br>    else {<br>        return search(subtreeRoot-&gt;right, value);<br>    }<br>}<br><br>BinarySearchTree::Node *BinarySearchTree::findMinNode(Node* subtreeRoot) {<br>    if(!subtreeRoot || !subtreeRoot-&gt;left) {<br>        return subtreeRoot;<br>    }<br>    return findMinNode(subtreeRoot-&gt;left);<br>}<br><br>BinarySearchTree::Node *BinarySearchTree::remove(Node* subtreeRoot, int value) {<br>    if(!subtreeRoot) {<br>        return subtreeRoot;<br>    }<br>    if(value &lt; subtreeRoot-&gt;value) {<br>        subtreeRoot-&gt;left = remove(subtreeRoot-&gt;left, value);<br>    }<br>    else if(subtreeRoot-&gt;value &lt; value) {<br>        subtreeRoot-&gt;right = remove(subtreeRoot-&gt;right, value);<br>    }<br>    else {<br>        if(!subtreeRoot-&gt;left) {<br>            Node* rightTemp = subtreeRoot -&gt; right;<br>            delete subtreeRoot;<br>            return rightTemp;<br>        }<br>        else if(!subtreeRoot-&gt;right) {<br>            Node* leftTemp = subtreeRoot -&gt; left;<br>            delete subtreeRoot;<br>            return leftTemp;<br>        }<br>        Node* inOrderSuccessor = findMinNode(subtreeRoot-&gt;right);<br>        subtreeRoot -&gt; value = inOrderSuccessor -&gt; value;<br>        subtreeRoot -&gt; right = remove(subtreeRoot -&gt; right, inOrderSuccessor -&gt; value);<br>    }<br>    return subtreeRoot;<br>}<br><br>void BinarySearchTree::printInOrder(Node* subtreeRoot) {<br>    if (!subtreeRoot) {<br>        return;<br>    }<br>    printInOrder(subtreeRoot-&gt;left);<br>    std::cout &lt;&lt; subtreeRoot-&gt;value &lt;&lt; &quot; &quot;;<br>    printInOrder(subtreeRoot-&gt;right);<br>}<br><br>void BinarySearchTree::clear(BinarySearchTree::Node* subtreeRoot) {<br>    if(!subtreeRoot) {<br>        return;<br>    }<br>    clear(subtreeRoot-&gt;left);<br>    clear(subtreeRoot-&gt;right);<br>    std::cout &lt;&lt; &quot;Deleting &quot; &lt;&lt; subtreeRoot-&gt;value &lt;&lt; std::endl;<br>    delete subtreeRoot;<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=847aa4d87eec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes Persistent Volumes and Persistent Volume Claims]]></title>
            <link>https://medium.com/@pawara/kubernetes-persistent-volumes-and-persistent-volume-claims-191e451884df?source=rss-ef2234f38408------2</link>
            <guid isPermaLink="false">https://medium.com/p/191e451884df</guid>
            <category><![CDATA[persistent-volume-claim]]></category>
            <category><![CDATA[persistent-volume]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Pawara Gunawardena]]></dc:creator>
            <pubDate>Sun, 25 Oct 2026 17:01:25 GMT</pubDate>
            <atom:updated>2026-10-25T17:01:25.817Z</atom:updated>
            <content:encoded><![CDATA[<p>A <a href="https://kubernetes.io/docs/concepts/storage/persistent-volumes"><em>PersistentVolume (PV)</em></a> is a cluster storage asset and it can be provisioned by an administrator or it can be provisioned using <a href="https://kubernetes.io/docs/concepts/storage/storage-classes/">Storage Classes</a>.</p><p>A <a href="https://kubernetes.io/docs/concepts/storage/persistent-volumes/"><em>PersistentVolumeClaim (PVC)</em></a> is a storage request that consumes <a href="https://kubernetes.io/docs/concepts/storage/persistent-volumes/"><em>PersistentVolume (PV)</em></a> resources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*OhmJWuSFCZUrWpRF6XHD_Q.png" /></figure><h4>PV and PVC Manifest Files</h4><p>Kubernetes PersistentVolumes and PersistentVolumeClaims can be created using YAML configuration files.</p><ul><li><strong>Create a persistent volume manifest file</strong></li></ul><pre>apiVersion: v1<br>kind: PersistentVolume<br>metadata:<br>  name: persistent-volume-demo<br>spec:<br>  storageClassName: &quot;&quot;<br>  accessModes:<br>    - ReadWriteOnce<br>  capacity:<br>    storage: 2Gi<br>  hostPath:<br>    path: /tmp/data</pre><ul><li><strong>Create a persistent volume claim manifest file</strong></li></ul><pre>apiVersion: v1<br>kind: PersistentVolumeClaim<br>metadata:<br>  name: persistent-volume-claim-demo<br>spec:<br>  storageClassName: &quot;&quot;<br>  accessModes:<br>    - ReadWriteOnce<br>  resources:<br>    requests:<br>      storage: 800Mi</pre><ul><li><strong>Create PersistentVolume and a PersistentVolumeClaim</strong> <strong>using the manifest files</strong></li></ul><pre>kubectl create -f &lt;file-path&gt;</pre><pre>kubectl apply -f &lt;file-path&gt;</pre><h4>Pods and PersistentVolumeClaims</h4><p>Pods can use the <em>PersistentVolumeClaim</em> as a volume to access the underlying storage.</p><pre>apiVersion: v1<br>kind: Pod<br>metadata:<br>  name: pod-demo<br>spec:<br>  containers:<br>    - name: alpine<br>      image: alpine<br>      command: [&quot;/bin/sh&quot;, &quot;-c&quot;]<br>      args:<br>        - |<br>          while true; do<br>            NUM=$(shuf -i 0-1000 -n 1)<br>            if [ $((NUM % 2)) -eq 0 ]; then<br>              echo &quot;$NUM&quot; &gt;&gt; /opt/value<br>              sleep 10<br>            fi<br>          done<br>      volumeMounts:<br>        - mountPath: /opt <br>          name: persistent-volume-claim-data<br>  volumes: <br>    - name: persistent-volume-claim-data<br>      persistentVolumeClaim:<br>        claimName: persistent-volume-claim-demo</pre><p>Verify the file data and the mount path of the pod.</p><pre>kubectl exec -it pod-demo  -- ls -la /opt</pre><pre>kubectl exec -it pod-demo  -- less /opt/value</pre><p>Verify the file data and the host path of the persistent volume.</p><pre>minikube ssh</pre><pre>more /tmp/data/value</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=191e451884df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apache Kafka Producer and Acknowledgements]]></title>
            <link>https://medium.com/@pawara/apache-kafka-producer-and-acknowledgements-d6f5e51180b3?source=rss-ef2234f38408------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6f5e51180b3</guid>
            <category><![CDATA[consumer]]></category>
            <category><![CDATA[apache-kafka]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[producer]]></category>
            <dc:creator><![CDATA[Pawara Gunawardena]]></dc:creator>
            <pubDate>Wed, 30 Sep 2026 17:48:36 GMT</pubDate>
            <atom:updated>2026-09-30T17:48:36.059Z</atom:updated>
            <content:encoded><![CDATA[<p>Apache Kafka producer can be identified as a Kafka client that publishes a stream of data to the Kafka cluster.</p><h4>Kafka Topic and Partitions</h4><p>A Kafka topic represents a stream of data, and a given topic can be identified by its name. A single Kafka topic contains a set of partitions. When messages are produced to a topic, they are directed to one of the topic’s partitions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8j7_Ic8Nqh2MwmtsSlOhEg.png" /></figure><h4>Kafka Producer</h4><p>Kafka producer writes data into Kafka topics and it will write data sequentially into partitions of the particular topic.</p><p>Producer applications can utilize partitions to load balance among partitions and a single partition can receive event records from one or more producers.</p><p>Implementation of a sample Kafka Producer describes <a href="https://medium.com/@pawara/apache-kafka-producer-application-e4ed8a944d62">here</a>.</p><h4>Producer Acknowledgements</h4><p>Kafka producers can configure different numbers of acknowledgments required for a request to be considered successfully complete.</p><ul><li><strong>acks = 0</strong></li></ul><p>When acks is set to zero, the producer does not wait for any acknowledgment from the broker. As a result, message delivery is not guaranteed and there is a risk of data loss if a failure occurs before the message is written.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lCAHYVUvwexCpwin5OWGNQ.png" /></figure><ul><li><strong>acks = 1</strong></li></ul><p>When acks is set to one, the producer waits for the leader’s acknowledgment and the leader responds once its local log is updated. If the leader fails right after acknowledging but before replication happens, the record can be lost.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N0ljObTLkuu1eAjyiB1AHg.png" /></figure><ul><li><strong>acks = all</strong></li></ul><p>When acks is set to all, the producer waits for the leader’s acknowledgment, and the leader sends the acknowledgment once the in-sync replicas acknowledge the record. This provides the strongest delivery guarantee and the highest level of fault tolerance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wTXjG_27GV3jc0ffbpk6xQ.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6f5e51180b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Priority Queue Design Pattern]]></title>
            <link>https://medium.com/@pawara/priority-queue-design-pattern-c46dcea86e6d?source=rss-ef2234f38408------2</link>
            <guid isPermaLink="false">https://medium.com/p/c46dcea86e6d</guid>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Pawara Gunawardena]]></dc:creator>
            <pubDate>Wed, 30 Sep 2026 14:47:39 GMT</pubDate>
            <atom:updated>2026-09-30T14:47:39.666Z</atom:updated>
            <content:encoded><![CDATA[<p>The priority queue design pattern provides the capability to manage and process messages or related tasks based on their priority.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*O52g0W4Mht664b9Zuy2O9w.jpeg" /></figure><p>The producer application assigns a priority value when producing a message, and the consumer application receives messages based on the priority order.</p><ul><li>It handles higher-priority, urgent messages or tasks before lower-priority messages or tasks.</li><li>The message queue provides messages according to the priority, rather than in First-In, First-Out (FIFO) order.</li></ul><h4>Priority Queue Pattern</h4><p>The priority queue pattern can be implemented using different approaches.</p><ul><li><strong>Single Queue</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*a77gkcbQToeANb_zAYwQBg.jpeg" /></figure><ul><li><strong>Multiple Queues — Single Consumer Pool</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*JGP67ntjn57sPe1qP62VqA.jpeg" /></figure><ul><li><strong>Multiple Queues — Multiple Consumer Pools</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*qMgByMjN-gCwSyq6dGITiw.jpeg" /></figure><h4>Implementation</h4><p>There are different types of message queues available. Below implementation uses the RabbitMQ which is an open source message broker.</p><p>Below explains the implementation of the <em>Producer</em> application which is a C++ application, and the implementation of the <em>Consumer</em> application which is a Java application.</p><p>This previous <a href="https://medium.com/@pawara/producer-and-consumer-with-a-message-queue-e6a00b1476d2">article</a> describes implementation of a similar producer consumer application along with installation setup of dependencies.</p><p><strong>Producer Application</strong></p><p>For a RabbitMQ producer client libraries, <a href="https://www.rabbitmq.com/client-libraries/devtools">RabbitMQ documentation</a> explains multiple clients and this article uses the <a href="https://github.com/CopernicaMarketingSoftware/AMQP-CPP">AMQP-CPP</a> library.</p><p>Installation steps are explaining under the <a href="https://github.com/CopernicaMarketingSoftware/AMQP-CPP#how-to-install"><em>how to install</em></a> section of the library project.</p><p>Below implementation has verified in a Linux Ubuntu environment with C++ 17 and verified with CMake based compile steps. Since this example depends on the TCP module it need to use the respective flags of the cmake command.</p><pre>mkdir build<br>cd build</pre><pre>cmake .. -DAMQP-CPP_BUILD_SHARED=ON -DAMQP-CPP_LINUX_TCP=ON</pre><pre>cmake --build . --target install</pre><p><em>MessageQueueTcpHandler</em> implements the <em>AMQP::TcpHandler</em> pure virtual class interface.</p><pre>#pragma once<br><br>#include &lt;amqpcpp.h&gt;<br>#include &lt;amqpcpp/linux_tcp.h&gt;<br><br>class MessageQueueTcpHandler : public AMQP::TcpHandler<br>{<br>    virtual void onAttached(AMQP::TcpConnection *connection) override;<br>    virtual void onConnected(AMQP::TcpConnection *connection) override;<br>    virtual bool onSecured(AMQP::TcpConnection *connection, const SSL *ssl) override;<br>    virtual void onReady(AMQP::TcpConnection *connection) override;<br>    virtual void onError(AMQP::TcpConnection *connection, const char *message) override;<br>    virtual void onClosed(AMQP::TcpConnection *connection) override;<br>    virtual void onLost(AMQP::TcpConnection *connection) override;<br>    virtual void onDetached(AMQP::TcpConnection *connection) override;<br>    virtual void monitor(AMQP::TcpConnection *connection, int fd, int flags) override;<br>};</pre><pre>#include &quot;MessageQueueTcpHandler.h&quot;<br><br>void MessageQueueTcpHandler::onAttached(AMQP::TcpConnection *connection)<br>{<br><br>}<br><br>void MessageQueueTcpHandler::onConnected(AMQP::TcpConnection *connection)<br>{<br><br>}<br><br>bool MessageQueueTcpHandler::onSecured(AMQP::TcpConnection *connection, const SSL *ssl)<br>{<br>     return true;<br>}<br><br>void MessageQueueTcpHandler::onReady(AMQP::TcpConnection *connection)<br>{<br><br>}<br><br>void MessageQueueTcpHandler::onError(AMQP::TcpConnection *connection, const char *message)<br>{<br><br>}<br><br>void MessageQueueTcpHandler::onClosed(AMQP::TcpConnection *connection)<br>{<br><br>}<br><br>void MessageQueueTcpHandler::onLost(AMQP::TcpConnection *connection)<br>{<br><br>}<br><br>void MessageQueueTcpHandler::onDetached(AMQP::TcpConnection *connection)<br>{<br><br>}<br><br>void MessageQueueTcpHandler::monitor(AMQP::TcpConnection *connection, int fd, int flags)<br>{<br><br>}</pre><p><em>Producer</em> application publish messages to the queue named <em>demo_priority_queue. </em>For the demonstration, within the implementation it uses the default authentication literal values.</p><p><em>ProducerApplication.cpp</em> produces to the <em>demo_priority_queue</em>.</p><pre>#include &lt;iostream&gt;<br>#include &lt;thread&gt;<br>#include &lt;ctime&gt;<br>#include &lt;amqpcpp.h&gt;<br>#include &lt;boost/asio/io_service.hpp&gt;<br>#include &lt;amqpcpp/libboostasio.h&gt;<br>#include &quot;MessageQueueTcpHandler.h&quot;<br><br>const std::string QUEUE = &quot;demo_priority_queue&quot;;<br>const std::string DEFAULT_EXCHANGE = &quot;&quot;;<br>const std::string ROUTING_KEY = &quot;demo_priority_queue&quot;;<br><br>int getIdleMilliseconds()<br>{<br>    int idleMilliseconds = (10 + std::rand() % 3) * 100;<br>    return idleMilliseconds;<br>}<br><br>std::string readData(const std::string&amp; appId)<br>{<br>    time_t timestamp;<br>    time(&amp;timestamp);<br>    std::string data = &quot;[&quot;+appId+&quot;] &quot;+ctime(&amp;timestamp);<br>    return data;<br>}<br><br>void publishToDefaultExchange(AMQP::TcpChannel&amp; channel, const std::string&amp; appId)<br>{<br>    while(channel.usable()) <br>    {<br>        const std::string data = readData(appId);<br><br>        int priority = std::rand() % 11; <br><br>        AMQP::Envelope envelope(data.c_str(), data.length());<br>        envelope.setPriority(priority);<br><br>        std::cout&lt;&lt;&quot;Producer application publish priority &quot; &lt;&lt; priority &lt;&lt; &quot; - data &quot; &lt;&lt; data &lt;&lt; std::endl;<br><br>        channel.publish(DEFAULT_EXCHANGE, ROUTING_KEY, envelope);<br>        std::this_thread::sleep_for(std::chrono::milliseconds(getIdleMilliseconds()));<br>    }<br>}<br><br>int main(int argc, char *argv[])<br>{<br>    std::cout&lt;&lt; std::endl;<br>    std::srand(static_cast&lt;unsigned int&gt;(std::time(nullptr)));<br><br>    boost::asio::io_service service(4);<br>    AMQP::LibBoostAsioHandler handler(service);<br>    AMQP::TcpConnection connection(&amp;handler, AMQP::Address(&quot;amqp://&lt;username&gt;:&lt;password&gt;@localhost/&quot;));<br>    AMQP::TcpChannel channel(&amp;connection);<br><br>    AMQP::QueueCallback callback = [&amp;](const std::string &amp;name, int msgcount, int consumercount)<br>        {<br>            publishToDefaultExchange(channel, argv[1]);<br>        };<br><br>    AMQP::Table arguments;<br>    arguments[&quot;x-max-priority&quot;] = 10;<br><br>    channel.declareQueue(QUEUE, AMQP::durable, arguments).onSuccess(callback);<br>    return service.run();<br>}</pre><p>To compile the program using g++, it needs amqpcpp, pthread and dl libraries.</p><pre>g++ -g -Wall  ProducerApplication.cpp MessageQueueTcpHandler.cpp MessageQueueTcpHandler.h -o producer -lamqpcpp -lpthread -ldl</pre><p>Executing the executable file will produce messages to the queue <em>sample_priority_queue</em>.</p><pre>./producer producer_app</pre><p><strong>Consumer Application</strong></p><p>For the Consumer Application, <a href="https://www.rabbitmq.com/client-libraries/devtools">RabbitMQ documentation</a> explains multiple clients and this article uses the <a href="https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-amqp">Spring for RabbitMQ</a> and the below implementation has verified in a Linux Ubuntu environment with Java 17.</p><p>Visit <a href="https://start.spring.io/">Spring Initializr</a> and configure the project details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JBcfB6hBck_oPpVyp2tiBQ.png" /></figure><p>Dependencies:</p><ul><li>Lombok</li><li>Spring for RabbitMQ</li></ul><p>Update <em>resources/application.properties</em></p><pre>spring.application.name=consumer<br>spring.rabbitmq.host=localhost<br>spring.rabbitmq.port=5672<br>spring.rabbitmq.username=&lt;username&gt;<br>spring.rabbitmq.password=&lt;password&gt;<br><br>rabbitmq.queue.name=demo_priority_queue<br>rabbitmq.exchange.name=<br>rabbitmq.routing.key=demo_priority_queue</pre><p><em>MessageQueueConfig</em> defines the configs of the message queue.</p><pre>package com.demo.consumer.config;<br><br>import org.springframework.amqp.core.Binding;<br>import org.springframework.amqp.core.BindingBuilder;<br>import org.springframework.amqp.core.DirectExchange;<br>import org.springframework.amqp.core.Queue;<br>import org.springframework.amqp.core.QueueBuilder;<br>import org.springframework.beans.factory.annotation.Value;<br>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br><br>@Configuration<br>public class MessageQueueConfig {<br>    @Value(&quot;${rabbitmq.queue.name}&quot;)<br>    private String queue;<br><br>    @Value(&quot;${rabbitmq.exchange.name}&quot;)<br>    private String exchange;<br><br>    @Value(&quot;${rabbitmq.routing.key}&quot;)<br>    private String routingKey;<br><br>    @Bean<br>    public Queue priorityQueue() {<br>        return QueueBuilder.durable(queue)<br>                .withArgument(&quot;x-max-priority&quot;, 10)<br>                .build();<br>    }<br><br>    @Bean<br>    public DirectExchange exchange() {<br>        return new DirectExchange(exchange);<br>    }<br><br>    @Bean<br>    public Binding binding() {<br>        return BindingBuilder<br>                .bind(priorityQueue())<br>                .to(exchange())<br>                .with(routingKey);<br>    }<br>}</pre><p><em>MessageQueueConsumer</em> consumes messages from the queue <em>demo_priority_queue</em>.</p><pre>package com.demo.consumer;<br><br>import org.slf4j.Logger;<br>import org.slf4j.LoggerFactory;<br>import org.springframework.amqp.rabbit.annotation.RabbitListener;<br>import org.springframework.beans.factory.annotation.Value;<br>import org.springframework.stereotype.Service;<br>import org.springframework.amqp.core.Message;<br><br>@Service<br>public class MessageQueueConsumer {<br>    public static final Logger LOGGER = LoggerFactory.getLogger(MessageQueueConsumer.class);<br><br>    @Value(&quot;${app.id}&quot;)<br>    private String appId;<br><br>    @RabbitListener(queues = {&quot;${rabbitmq.queue.name}&quot;})<br>    public void consumer(Message message) throws InterruptedException {<br>        int priority = message.getMessageProperties().getPriority();<br>        LOGGER.info(String.format(&quot;Consumer application [%s] received priority %d - data %s&quot;, appId, priority, new String(message.getBody())));<br>    }<br>}</pre><p><em>ConsumerApplication</em> defines the main method.</p><pre>package com.demo.consumer;<br><br>import org.springframework.boot.SpringApplication;<br>import org.springframework.boot.autoconfigure.SpringBootApplication;<br><br>@SpringBootApplication<br>public class ConsumerApplication {<br><br> public static void main(String[] args) {<br>  SpringApplication.run(ConsumerApplication.class, args);<br> }<br>}</pre><p>Once started the consumer application, it will consume messages from the queue <em>demo_priority_queue</em>.</p><pre>gradle bootRun --args=&#39;--app.id=consumer_app&#39;</pre><p><strong>Producer Application and Consumer Application Execution</strong></p><p>Execution of the <em>Producer Application </em>and publishing data to the message queue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*s06p5cxmhZ1n01tYmDj_7w.png" /></figure><p>Execution of the Consumer Application and consuming data from the message queue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*vyhWsCTjMfUd--Jg41xc-A.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c46dcea86e6d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kafka Replication and Fault Tolerance]]></title>
            <link>https://medium.com/@pawara/kafka-replication-and-fault-tolerance-02882534894b?source=rss-ef2234f38408------2</link>
            <guid isPermaLink="false">https://medium.com/p/02882534894b</guid>
            <category><![CDATA[kafka-partition]]></category>
            <category><![CDATA[kafka-topic]]></category>
            <category><![CDATA[kafka-replication]]></category>
            <category><![CDATA[apache-kafka]]></category>
            <dc:creator><![CDATA[Pawara Gunawardena]]></dc:creator>
            <pubDate>Mon, 31 Aug 2026 17:58:56 GMT</pubDate>
            <atom:updated>2026-08-31T17:58:56.995Z</atom:updated>
            <content:encoded><![CDATA[<p>A Kafka topic represents a stream of data, and a given topic can be identified by its name. A single Kafka topic contains a set of partitions. When messages are produced to a topic, they are directed to one of the topic’s partitions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8j7_Ic8Nqh2MwmtsSlOhEg.png" /></figure><h4>Kafka Broker</h4><p>In simple terms, a Kafka broker can be identified as a server. A collection of Kafka brokers forms a Kafka cluster.</p><p>A single broker has a set of topic partitions. Producer and consumer applications use these brokers to send and receive data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*RyVjcJiwDdhNb3awqnC5nQ.png" /></figure><h4>Kafka Topic Replication Factor</h4><p>Kafka topic partitions can be replicated across brokers. The replication factor of a topic defines the number of replicas for each partition in that topic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*PrbBmQdmzQZ2w4ekcHfFhg.png" /></figure><p>Replicating Kafka topic partitions across brokers ensures fault tolerance.</p><h4>Leader of a Partition</h4><p>One broker is designated as the leader of a given partition, and producer applications that need to write data to that partition send data to the leader. Other brokers that are assigned as followers replicate data from the leader to maintain the In-Sync Replicas (ISR).</p><p>By default, producer applications send data only to the partition’s leader broker.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZKe7feBcVuZ72vkcfD7D_A.png" /></figure><p>If a leader broker of a partition fails, one of the in-sync follower brokers becomes the new leader.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=02882534894b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Saga Design Pattern]]></title>
            <link>https://medium.com/@pawara/saga-design-pattern-12a5c1d032ae?source=rss-ef2234f38408------2</link>
            <guid isPermaLink="false">https://medium.com/p/12a5c1d032ae</guid>
            <category><![CDATA[saga-pattern]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[saga]]></category>
            <dc:creator><![CDATA[Pawara Gunawardena]]></dc:creator>
            <pubDate>Sat, 29 Aug 2026 20:32:39 GMT</pubDate>
            <atom:updated>2026-08-29T20:32:39.597Z</atom:updated>
            <content:encoded><![CDATA[<p>In an application, a transaction is a unit of work consisting of one or more operations.</p><p>Transactions are expected to adhere to the <em>ACID: Atomicity, Consistency, Isolation, Durability</em> properties.</p><p>When performing a transaction against a distributed system and/or databases of distributed services, it provides certain challenges and complications to preserve ACID properties compared to performing a transaction against a monolith system or against a single database.</p><p>The Saga design pattern provides a mechanism to perform a transaction in a distributed system by breaking the transaction into a sequence of local transactions.</p><h4>Transactions with Forward and Backward Recovery</h4><p>Local transactions provide the atomicity within the service and updates the service database. Once completed the local transaction successfully, it produces the message or event to initiate the local transaction of the next service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*qTr67mXVMofximbtHe280A.jpeg" /></figure><p>In Saga transactions, compensable transaction changes can be reverted by other compensating transactions. These compensable transactions allow backward recovery with compensation transactions.</p><p>Retryable transactions are idempotent and even with temporary failures, they can achieve forward recovery by retrying the original transaction to reach eventual consistency.</p><h4>Implementation Approaches</h4><ul><li><strong>Choreography</strong></li></ul><p>The saga choreography design pattern allows services to exchange messages/events without centralized controller.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*ZpH8W4d3YE9S77fnwu2KNA.jpeg" /></figure><ul><li><strong>Orchestration</strong></li></ul><p>The saga orchestration design pattern uses the centralized coordinator called as Orchestrator to manage and handle the transaction life cycle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*8CPbU5tn629vAsa09DU0hQ.jpeg" /></figure><p>Orchestrator interprets states and service responses of each local transaction and handles failure recovery by utilizing compensating transactions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12a5c1d032ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apache Kafka Consumer Application]]></title>
            <link>https://medium.com/@pawara/apache-kafka-consumer-application-9a823ba4dad0?source=rss-ef2234f38408------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a823ba4dad0</guid>
            <category><![CDATA[producer]]></category>
            <category><![CDATA[apache-kafka]]></category>
            <category><![CDATA[consumer]]></category>
            <category><![CDATA[kafka]]></category>
            <dc:creator><![CDATA[Pawara Gunawardena]]></dc:creator>
            <pubDate>Fri, 31 Jul 2026 18:00:53 GMT</pubDate>
            <atom:updated>2026-08-19T18:23:34.670Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://kafka.apache.org/">Apache Kafka</a> consumer can be identified as a Kafka client that consumes a stream of data from the Kafka cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*MXtDTkoTK6d2CCYpXBzi3g.png" /></figure><p>Let’s implement a simple Apache Kafka Consumer Application using <a href="https://www.java.com/">Java</a> language with <a href="https://spring.io/projects/spring-boot">Spring Boot</a>.</p><h4>Consumer</h4><p>Kafka Consumers read data from Kafka Topics, and the consumer can use the topic name to read data, and Kafka consumer follows the pull model to read data.</p><p>When there are multiple instances of the consumer application, they read as a group. A single consumer application instance of the group reads from a selected set of partitions of the topic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*HzuQtdfFVUSZPtHMadIGHw.png" /></figure><p>As illustrated in the image, two consumers from different consumer groups can read from the same partition. But, when considered a single consumer group, two consumers of the same consumer group will not read from the same partition. Also, as illustrated in the image, a single consumer can read data from multiple partitions.</p><p>For the demonstration, consider a spring boot application that consume data from the Kafka topic <em>product-events </em>and persists in the local database.</p><h4>Initialize the project</h4><ul><li>Visit <a href="https://start.spring.io/">Spring Initializr</a> and configure the project details</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5GOZI6SqTZT_JlCGlVaM4A.png" /></figure><p>Dependencies</p><ul><li>Spring Web</li><li>Spring Data JPA</li><li>MySQL Driver</li><li>Spring for Apache Kafka</li><li>Lombok</li></ul><p>Click on generate and it will download the initial project as a zip file. Extract the zip file into a folder and open it using a desired text editor or IDE.</p><h4>Implementation</h4><ul><li>Configurations</li></ul><p>Update the application.yml with respective details.</p><pre>server:<br>  port: 8080<br>spring:<br>  profiles:<br>    active: local<br>  config:<br>    activate:<br>      on-profile: local<br>  application:<br>    name: products-consumer<br>  datasource:<br>    url: jdbc:mysql://localhost:3306/db<br>    username: <br>    password: <br>    driver-class-name: com.mysql.cj.jdbc.Driver<br>  jpa:<br>    hibernate:<br>      ddl-auto: update<br>  kafka:<br>    consumer:<br>      bootstrap-servers: localhost:9092<br>      key-deserializer: org.apache.kafka.common.serialization.StringDeserializer<br>      value-deserializer: org.springframework.kafka.support.serializer.JsonDeserializer<br>      properties:<br>        spring:<br>          json:<br>            trusted:<br>              packages: &quot;com.demo.application.products.*&quot;<br>            value:<br>              default:<br>                type: &quot;com.demo.application.products.dto.ProductEvent&quot;</pre><ul><li>Model</li></ul><pre>package com.demo.application.products.model;<br><br>import jakarta.persistence.Column;<br>import jakarta.persistence.Entity;<br>import jakarta.persistence.Id;<br>import jakarta.persistence.Table;<br>import lombok.AllArgsConstructor;<br>import lombok.Getter;<br>import lombok.NoArgsConstructor;<br>import lombok.Setter;<br><br>@Entity<br>@Table(name=&quot;product&quot;)<br>@Getter<br>@Setter<br>@NoArgsConstructor<br>@AllArgsConstructor<br>public class Product {<br>    @Id<br>    private Long id;<br>    @Column(nullable = false, unique = true)<br>    private String productId;<br>    private String name;<br>    private Integer quantity;<br>    private String description;<br>}</pre><ul><li>Repository Layer</li></ul><pre>package com.demo.application.products.repository;<br><br>import com.demo.application.products.model.Product;<br>import org.springframework.data.jpa.repository.JpaRepository;<br><br>public interface ProductRepository extends JpaRepository&lt;Product, Long&gt; {<br>    Product findByProductId(String productId);<br>}</pre><ul><li>Data Transfer Objects (DTOs)</li></ul><pre>package com.demo.application.products.dto;<br><br>import com.demo.application.products.model.Product;<br><br>public record ProductEvent(<br>        String eventType,<br>        Product product<br>) {<br>}</pre><ul><li>Exceptions</li></ul><pre>package com.demo.application.products.exception;<br><br>public class ResourceNotFoundException extends Exception {<br>    public ResourceNotFoundException(String message) {<br>        super(message);<br>    }<br>}</pre><ul><li>Service Layer</li></ul><pre>package com.demo.application.products.service;<br><br>import com.demo.application.products.dto.ProductEvent;<br>import com.demo.application.products.exception.ResourceNotFoundException;<br>import com.demo.application.products.model.Product;<br>import com.demo.application.products.repository.ProductRepository;<br>import lombok.RequiredArgsConstructor;<br>import lombok.extern.slf4j.Slf4j;<br>import org.springframework.beans.BeanUtils;<br>import org.springframework.kafka.annotation.KafkaListener;<br>import org.springframework.stereotype.Service;<br><br>import java.lang.reflect.Field;<br>import java.util.ArrayList;<br>import java.util.Objects;<br><br>@Service<br>@RequiredArgsConstructor<br>@Slf4j<br>public class ProductService {<br>    private final ProductRepository productRepository;<br><br>    @KafkaListener(topics = &quot;product-events&quot;, groupId = &quot;product-event-group&quot;)<br>    public void processProductEvents(ProductEvent productEvent) throws ResourceNotFoundException, IllegalAccessException {<br>        Product product = productEvent.product();<br>        if (productEvent.eventType().equals(&quot;CreateProduct&quot;)) {<br>            log.info(&quot;Create product [{}] received.&quot;, product.toString());<br>            productRepository.save(product);<br>            log.info(&quot;Created product [{}] successfully.&quot;, product.getProductId());<br>        } else if (productEvent.eventType().equals(&quot;UpdateProduct&quot;)) {<br>            log.info(&quot;Update product [{}] received.&quot;, product.getProductId());<br>            Product existingProduct = productRepository.findByProductId(product.getProductId());<br><br>            if (Objects.isNull(existingProduct)) {<br>                throw new ResourceNotFoundException(String.format(&quot;Product not found with id: %s&quot;, product.getProductId()));<br>            }<br>            ArrayList&lt;String&gt; nullFieldsInProductRequest = getNullFields(product);<br>            BeanUtils.copyProperties(product, existingProduct, nullFieldsInProductRequest.toArray(String[]::new));<br>            productRepository.save(existingProduct);<br>            log.info(&quot;Updated product [{}] successfully.&quot;, product.getProductId());<br>        }<br>    }<br><br>    private ArrayList&lt;String&gt; getNullFields(Object object) throws IllegalAccessException {<br>        ArrayList&lt;String&gt; nullFields = new ArrayList&lt;&gt;();<br>        Field[] fields = object.getClass().getDeclaredFields();<br><br>        for (Field field: fields) {<br>            field.setAccessible(true);<br>            if (field.get(object) == null) {<br>                nullFields.add(field.getName());<br>            }<br>        }<br>        return nullFields;<br>    }<br>}</pre><h4>Produce Product Create and Product Update Events</h4><p>For demonstration, below uses the <a href="https://medium.com/@pawara/introduction-to-apache-kafka-command-line-interface-3bc240fe418c">Apache Kafka Command Line Interface (CLI)</a> tool <em>kafka-console-producer </em>to produce <em>product events</em> to the Kafka topic <em>product-events.</em></p><p>Console Producer:</p><pre>kafka-console-producer --bootstrap-server localhost:9092   --topic product-events</pre><p>Create Event(s):</p><pre>{&quot;eventType&quot;:&quot;CreateProduct&quot;,&quot;product&quot;:{&quot;id&quot;:10000,&quot;productId&quot;:&quot;10000&quot;,&quot;name&quot;:&quot;Product 10000&quot;,&quot;quantity&quot;:5,&quot;description&quot;:&quot;Product 10000 Description&quot;}}</pre><p>Update Event(s):</p><pre>{&quot;eventType&quot;:&quot;UpdateProduct&quot;,&quot;product&quot;:{&quot;id&quot;:10000,&quot;productId&quot;:&quot;10000&quot;,&quot;name&quot;:&quot;Product 10000&quot;,&quot;quantity&quot;:5,&quot;description&quot;:&quot;Updated Product 10000 Description&quot;}}</pre><p>Query and Validate Database:</p><pre>SELECT * FROM product;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a823ba4dad0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Observer Design Pattern]]></title>
            <link>https://medium.com/@pawara/observer-design-pattern-ad1c2a0fec09?source=rss-ef2234f38408------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad1c2a0fec09</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[object-oriented-software]]></category>
            <category><![CDATA[observer-design-pattern]]></category>
            <category><![CDATA[gang-of-four]]></category>
            <dc:creator><![CDATA[Pawara Gunawardena]]></dc:creator>
            <pubDate>Fri, 31 Jul 2026 17:28:22 GMT</pubDate>
            <atom:updated>2026-07-31T17:30:08.812Z</atom:updated>
            <content:encoded><![CDATA[<p>The Observer design pattern, also known as the Publish-Subscribe or Dependents, is a behavioral design pattern.</p><p>This observer pattern can be applied when a change to one object requires notifying other dependent objects. Here, the internal state change of one object can be reflected in another dependent object without tight coupling between objects.</p><p>The classes and respective objects initiate in this observer pattern can be identified as subject and observer(s).</p><h4>Design Diagram</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*1WSTjbBGcA7SK5n7buIZaQ.png" /></figure><p><strong><em>Subject:</em></strong> provides an interface for client for attaching and detaching observers, and this is aware of its observers</p><p><strong><em>Observer:</em></strong> provides the updating interface for <em>ConcreteObserver</em> object instances that should be notified of changes in the subject state.</p><p><strong><em>ConcreteSubject:</em></strong> implements the <em>Subject</em> and stores the subject state which has the interest of <em>ConcreteObserver</em> object instances. Notifies the attached observers when the subject state changes.</p><pre>for all o in observers {<br>    o -&gt; update()<br>}</pre><p><strong><em>ConcreteObserver:</em></strong> implements the <em>Observer</em> and stores the observer state that should stay consistent with the subject state.</p><pre>observerState = subject -&gt; getState ()</pre><h4>Implementation</h4><p>Consider a weather station which has multiple observers for the weather station state value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_d0FFYywxGonTFbkme3nvQ.png" /><figcaption>c</figcaption></figure><p><em>WeatherStation</em> provides the interface for client for attaching and detaching observers.</p><pre>#pragma once<br><br>#include &lt;unordered_set&gt;<br>#include &quot;../Observer/Observer.h&quot;<br><br>class WeatherStation {<br>public:<br>    virtual void attach(Observer* observer);<br>    virtual void detach(Observer* observer);<br>    virtual void notify() = 0;<br><br>protected:<br>    std::unordered_set&lt;Observer*&gt; observers;<br>};</pre><pre>#include &quot;WeatherStation.h&quot;<br><br>void WeatherStation::attach(Observer *observer) {<br>    observers.insert(observer);<br>}<br><br>void WeatherStation::detach(Observer *observer) {<br>    observers.erase(observer);<br>}</pre><p>Observer provides the updating interface for concrete observer object instances.</p><pre>#pragma once<br><br>#include &lt;string&gt;<br><br>class Observer {<br>public:<br>    virtual void update(std::string message) = 0;<br>    Observer();<br>private:<br>    static int observerCount;<br>protected:<br>    int currentObserverId;<br>};</pre><pre>#include &quot;Observer.h&quot;<br><br>Observer::Observer() {<br>    observerCount++;<br>    currentObserverId = observerCount;<br>}</pre><p>ConcreteWeatherStation implements the WeatherStation.</p><pre>#pragma once<br><br>#include &quot;../WeatherStation.h&quot;<br><br>class ConcreteWeatherStation: public WeatherStation {<br>public:<br>    ConcreteWeatherStation(const std::string &amp;stateMessage);<br>    void notify() override;<br>    void setState(std::string state);<br>    std::string getState();<br>private:<br>    std::string state;<br>};</pre><pre>#include &quot;ConcreteWeatherStation.h&quot;<br><br>void ConcreteWeatherStation::notify()<br>{<br>    std::unordered_set&lt;Observer *&gt;::iterator observersIterator;<br><br>    for (observersIterator = observers.begin();<br>         observersIterator != observers.end();<br>         observersIterator++)<br>    {<br>        Observer *currentObserver = *observersIterator;<br>        currentObserver-&gt;update(this-&gt;getState());<br>    }<br>}<br><br>ConcreteWeatherStation::ConcreteWeatherStation(const std::string &amp;state) {<br>    this-&gt;setState(state);<br>}<br><br>void ConcreteWeatherStation::setState(std::string state) {<br>    this-&gt;state = state;<br>    notify();<br>}<br><br>std::string ConcreteWeatherStation::getState() {<br>    return this-&gt;state;<br>}</pre><p><em>Dashboard</em> and <em>Forecast</em> implements the <em>Observer</em>.</p><pre>#pragma once<br><br>#include &quot;../Observer.h&quot;<br><br>class Dashboard: public Observer {<br>public:<br>    void update(std::string message) override;<br>    const std::string &amp;getWeatherState() const;<br>    void setWeatherState(const std::string &amp;stationState);<br>    Dashboard();<br>private:<br>    std::string weatherState;<br>};</pre><pre>#include &lt;iostream&gt;<br>#include &quot;Dashboard.h&quot;<br><br>void Dashboard::update(std::string value) {<br>    std::cout<br>            &lt;&lt; &quot;OBSERVER::&quot;<br>            &lt;&lt; this-&gt;currentObserverId<br>            &lt;&lt; &quot;:: UPDATE RECEIVED :: &quot;<br>            &lt;&lt; value<br>            &lt;&lt; std::endl;<br><br>    this-&gt;setWeatherState(value);<br>}<br><br>Dashboard::Dashboard() {}<br><br>const std::string&amp; Dashboard::getWeatherState() const {<br>    return weatherState;<br>}<br><br>void Dashboard::setWeatherState(const std::string &amp;weatherState) {<br>    this-&gt;weatherState = weatherState;<br>}</pre><pre>#pragma once<br><br><br>#include &quot;../Observer.h&quot;<br><br>class Forecast: public Observer {<br>public:<br>    void update(std::string message) override;<br>    const std::string &amp;getWeatherState() const;<br>    void setWeatherState(const std::string &amp;weatherState);<br>    Forecast();<br>private:<br>    std::string weatherState;<br>};</pre><pre>#include &lt;iostream&gt;<br>#include &quot;Forecast.h&quot;<br><br>void Forecast::update(std::string value) {<br>    std::cout<br>            &lt;&lt; &quot;OBSERVER::&quot;<br>            &lt;&lt; this-&gt;currentObserverId<br>            &lt;&lt; &quot;:: UPDATE RECEIVED :: &quot;<br>            &lt;&lt; value<br>            &lt;&lt; std::endl;<br><br>    this-&gt;setWeatherState(value);<br>}<br><br>Forecast::Forecast() {}<br><br>const std::string&amp; Forecast::getWeatherState() const {<br>    return weatherState;<br>}<br><br>void Forecast::setWeatherState(const std::string &amp;weatherState) {<br>    this-&gt;weatherState = weatherState;<br>}</pre><p>Client can attach or detach observer Dashboard, Forecast instances with subject WeatherStation type concrete ConcreteWeatherStation instance.</p><pre>#include &lt;iostream&gt;<br>#include &quot;Observer/Impl/Dashboard.h&quot;<br>#include &quot;Observer/Impl/Forecast.h&quot;<br>#include &quot;Subject/Impl/ConcreteWeatherStation.h&quot;<br><br>int Observer::observerCount = 0;<br><br>int main() {<br>    Dashboard* dashboard = new Dashboard();<br>    Forecast* concreteObserver2 = new Forecast();<br><br>    ConcreteWeatherStation* pWeatherStation = new ConcreteWeatherStation(&quot;NORMAL&quot;);<br>    pWeatherStation-&gt;attach(dashboard);<br>    pWeatherStation-&gt;attach(concreteObserver2);<br><br>    pWeatherStation-&gt;notify();<br><br>    pWeatherStation-&gt;setState(&quot;ADVISORY&quot;);<br><br>    pWeatherStation-&gt;detach(concreteObserver2);<br>    pWeatherStation-&gt;setState(&quot;WARNING&quot;);<br>    return 0;<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad1c2a0fec09" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Publish Subscribe with RabbitMQ Topic Exchange]]></title>
            <link>https://medium.com/@pawara/publish-subscribe-with-rabbitmq-topic-exchange-bb8b4bc50c47?source=rss-ef2234f38408------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb8b4bc50c47</guid>
            <category><![CDATA[pub-sub]]></category>
            <category><![CDATA[routing]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[message]]></category>
            <dc:creator><![CDATA[Pawara Gunawardena]]></dc:creator>
            <pubDate>Tue, 30 Jun 2026 17:49:36 GMT</pubDate>
            <atom:updated>2026-06-30T17:49:36.080Z</atom:updated>
            <content:encoded><![CDATA[<p>Publish-subscribe pattern allows multiple consumers to consume the same message.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*lc6b9asXTykPuFZRW2trWA.png" /></figure><h4>RabbitMQ</h4><p><a href="https://www.rabbitmq.com/">RabbitMQ</a> is an open source message broker software.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/0*_knFkVFgJcqbg4SS.png" /></figure><p>Originally implemented the AMQP and supports other protocols such as Streaming Text Oriented Messaging Protocol (STOMP), Message Queuing Telemetry Transport (MQTT). Message broker queue oriented RabbitMQ consumer receives the message.</p><h4>Installation of RabbitMQ</h4><p>The d<a href="https://www.rabbitmq.com/docs/download">ocumentation</a> explains several approaches to install the RabbitMQ.</p><p>Below examples experimented with the <a href="https://www.rabbitmq.com/docs/install-debian">Linux/Unix, Debian and Ubuntu distributions installation</a> of the RabbitMQ.</p><h4>Management Plugin</h4><p>The RabbitMQ documentation provides an overview of the <a href="https://www.rabbitmq.com/docs/management">management plugin</a> and explains steps to enable the plugin.</p><p>Once enable the plugin, visit <a href="http://localhost:15672/">http://localhost:15672/</a> from the web browser to access the Management UI.</p><h4>Publish-Subscribe Messages</h4><p>The <a href="https://medium.com/@pawara/publish-subscribe-with-rabbitmq-fanout-exchange-f32951583ee8">Fanout exchange</a> supports to broadcast messages to all the queues that bound with the exchange. Also, with the <a href="https://medium.com/@pawara/publish-subscribe-with-rabbitmq-direct-exchange-b41b1c236bbe">Direct exchange</a> it can define the routing key for bindings of the Direct exchange and a queue, and messages with particular routing key will be routed to that queue. If a larger amount of routing keys required, it will require bindings with those routing keys for the queue.</p><p>The Topic exchange can be used to avoid the larger amount of bindings.</p><ul><li><strong>Create Queues</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*4vjQiUOXj0yZW_XiiZuYbg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*6stcGpv84hXHvq_K81D7Ow.png" /></figure><ul><li><strong>Create an Exchange</strong></li></ul><p>Navigate to the Exchanges tab of the RabbitMQ Management UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*cwaUXBIYTgg4GP83UZiazA.png" /></figure><p>Current Bindings of the Exchange</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*N-33nIg6ZPIzPRawZ5u_ow.png" /></figure><p>Current Bindings of the Queues</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*sSjhcJg_irrglPxW8WcpWw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*Q6VmU9yM5aErXb7krnsnTw.png" /></figure><ul><li><strong>Create Bindings</strong></li></ul><p>Navigate to the Exchanges tab of the RabbitMQ Management UI and click on the Exchange name and expand the Bindings section.</p><p>When exchange receive a message to route with a routing key, wildcard character * in the routing key of the binding allows to contain additional single word addition to the given pattern.</p><p>When exchange receive a message to route with a routing key, wildcard character # in the routing key of the binding allows to contain zero or more words in addition to the given pattern.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*IToKnthSuF0IaORd3-YGAg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*dMkMgNlrKan9OjkEhMhdNQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*3_2zGYFaLW5zmeudsDRzJg.png" /></figure><p>Exchange should be updated with the bindings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*WB8fg_7TPl92MxedP0zBUg.png" /></figure><p>Also Queues should be updated with the bindings</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*TINp8YJDvMVRntCv8S_rRw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*7dzxCtpkcHpxN6HL6kqRTQ.png" /></figure><ul><li><strong>Publish message</strong></li></ul><p>Let’s navigate to the exchange and publish multiple messages with different routing keys.</p><p>Message 01</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*rUuUr4GHF4dPTSdEIq1lzw.png" /></figure><p>Message 02</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*UzvjycQqEiPoc4ciTn6E5w.png" /></figure><p>Message 03</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*gp_mfWt3_1obYhSep0Bx2w.png" /></figure><p>Message 04</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*-NVPtsGEOyiBa-9Uz5bQkA.png" /></figure><p>Message 05</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*l-gPPeLl2s3iKF98irv3lg.png" /></figure><p>Message 06</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*8sK_RmN3NTkHXUzjVkvsTw.png" /></figure><p>Message 07</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*le-Oe9z4oOvYz6jXG3zkww.png" /></figure><p>Message section of both queues should be updated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*ulbwLlUvu7ynk4ARnlvHbg.png" /></figure><p>First queue should be received the Message-1 and Second queue should be received the Message-1, Message-2, Message-3, Message-4, Message-5.</p><p>Because of not matching the message routing key with any pattern of routing keys of bindings the Message-6 and Message-7 will not be routed to any of queues bound with demo exchange.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JGDTW2cRVCe7QeGFqR-YCQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lTwNtgJzBOlUtTkU2Jm7PQ.png" /></figure><ul><li><strong>Consume Message</strong></li></ul><p>Click on the first queue and expand the Get Messages section. Update the Ack Mode value, Messages count and click on the Get Message(s).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aao2y9GHhfb3C_uR1R2OCg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aS78_tRCZRzhzKKiiJmA-A.png" /></figure><p>Similarly click on the second queue and expand the Get Messages section. Update the Ack Mode value, Messages count and click on the Get Message(s).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb8b4bc50c47" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Retry Design Pattern]]></title>
            <link>https://medium.com/@pawara/retry-design-pattern-4f4421b423d4?source=rss-ef2234f38408------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f4421b423d4</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[architecture]]></category>
            <dc:creator><![CDATA[Pawara Gunawardena]]></dc:creator>
            <pubDate>Tue, 30 Jun 2026 16:37:07 GMT</pubDate>
            <atom:updated>2026-06-30T16:37:07.703Z</atom:updated>
            <content:encoded><![CDATA[<p>The retry pattern provides a strategy that allows to automatically reattempt failed operations of an application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3qJJO3Tgcs9EK54kISWm8g.png" /></figure><p>In distributed computing, it has to work with services or resources over the network. There can be transient failures of different resources such as loss of network connectivity to components and services, random timeout of a busy external resource or service, temporary unavailability of an external resource or service.</p><p>In such occasions, retry pattern allows to handle and recover from transient failures of the operation by transparently retrying the failed operation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XRlS3qn2vXjUithTNpKGGQ.png" /></figure><h3>Implementation</h3><p>Below implements <em>sample-service</em> to demonstrate the retry pattern, and <em>sample-service</em> invokes the API of mock service called <em>demo-items-service.</em></p><h4>Demo Sample Service Project</h4><p>For the implementation here uses Java language <a href="https://spring.io/projects/spring-boot">Spring Boot</a> application and retry implements with <a href="https://resilience4j.readme.io/docs/getting-started">Resiliency4j</a> library.</p><p><strong>Model</strong></p><pre>package com.demo.sample.model;<br><br>import lombok.AllArgsConstructor;<br>import lombok.Builder;<br>import lombok.Data;<br>import lombok.NoArgsConstructor;<br><br>@AllArgsConstructor<br>@NoArgsConstructor<br>@Builder<br>@Data<br>public class Item {<br>    private String id;<br>    private String name;<br>    private String description;<br>}</pre><p><strong>Data Transfer Objects (DTOs)</strong></p><pre>package com.demo.sample.dto;<br><br>import lombok.AllArgsConstructor;<br>import lombok.Builder;<br>import lombok.Data;<br>import lombok.NoArgsConstructor;<br><br>@Data<br>@AllArgsConstructor<br>@NoArgsConstructor<br>@Builder<br>public class ItemResponse {<br>    private String id;<br>    private String name;<br>    private String description;<br>}</pre><p><strong>Request Client with Retry</strong></p><pre>package com.demo.sample.client;<br><br>import com.demo.sample.model.Item;<br>import io.github.resilience4j.retry.annotation.Retry;<br>import org.springframework.stereotype.Service;<br>import org.springframework.web.client.RestTemplate;<br>import lombok.extern.slf4j.Slf4j;<br><br>import java.util.Arrays;<br>import java.util.List;<br><br>@Service<br>@Slf4j<br>public class RequestClient {<br><br>    @Retry(name=&quot;retryGetAllItems&quot;,fallbackMethod = &quot;getAllItemsFallback&quot;)<br>    public List&lt;Item&gt; getAllItems() {<br>        log.info(&quot;Fetching items with retrying support&quot;);<br>        RestTemplate restTemplate = new RestTemplate();<br>        Item[] itemsArray = restTemplate.getForObject(&quot;http://localhost:3030/items&quot;, Item[].class);<br>        return Arrays.asList(itemsArray);<br>    }<br><br>    public List&lt;Item&gt; getAllItemsFallback(Exception e) {<br>        return List.of();<br>    }<br>}</pre><p><strong>Service Layer</strong></p><pre>package com.demo.sample.service;<br><br>import com.demo.sample.client.RequestClient;<br>import com.demo.sample.dto.ItemResponse;<br>import com.demo.sample.model.Item;<br>import lombok.extern.slf4j.Slf4j;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.stereotype.Service;<br><br>import java.util.List;<br><br>@Service<br>@Slf4j<br>public class DemoService {<br><br>    private final RequestClient requestClient;<br><br>    @Autowired<br>    public DemoService(final RequestClient requestClient) {<br>        this.requestClient = requestClient;<br>    }<br><br>    public List&lt;ItemResponse&gt; getAllItems() {<br>        List&lt;Item&gt; items = requestClient.getAllItems();<br>        log.info(&quot;Fetched [{}] items.&quot;, items.size());<br>        return items.stream().map(this::fromItemToItemResponse).toList();<br>    }<br><br>    private ItemResponse fromItemToItemResponse(Item item) {<br>        return ItemResponse.builder()<br>                .id(item.getId())<br>                .name(item.getName())<br>                .description(item.getDescription())<br>                .build();<br>    }<br>}</pre><p><strong>Controller Layer</strong></p><pre>package com.demo.sample.controller;<br><br>import com.demo.sample.dto.ItemResponse;<br>import com.demo.sample.service.DemoService;<br>import lombok.extern.slf4j.Slf4j;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.http.HttpStatus;<br>import org.springframework.web.bind.annotation.GetMapping;<br>import org.springframework.web.bind.annotation.RequestMapping;<br>import org.springframework.web.bind.annotation.ResponseStatus;<br>import org.springframework.web.bind.annotation.RestController;<br><br>import java.util.List;<br><br>@RestController<br>@RequestMapping(&quot;/api/items&quot;)<br>@Slf4j<br>public class DemoController {<br><br>    private final DemoService demoService;<br><br>    @Autowired<br>    public DemoController(final DemoService demoService) {<br>        this.demoService = demoService;<br>    }<br><br>    @GetMapping()<br>    @ResponseStatus(HttpStatus.OK)<br>    public List&lt;ItemResponse&gt; getAllItems() {<br>        log.info(&quot;Get all items request received.&quot;);<br>        return demoService.getAllItems();<br>    }<br>}</pre><p><strong>Application Configurations</strong></p><p>Update configurations <em>resources/application.properties</em></p><pre>resilience4j.retry.instances.retryGetAllItems.max-attempts=5<br>resilience4j.retry.instances.retryGetAllItems.wait-duration=15s</pre><p>If using YAML configurations file, update <em>resources/application.yml.</em></p><pre>resilience4j:<br>  retry:<br>    instances:<br>      retryGetAllItems:<br>        max-attempts: 5<br>        wait-duration: 15s</pre><p><a href="https://resilience4j.readme.io/docs/getting-started">Resiliency4j</a> library <a href="https://resilience4j.readme.io/docs/retry">Retry documentation</a> section provides further config properties with default values and descriptions.</p><h4>Demo Items Service</h4><p>For this demonstration project, <em>demo-items-service</em> rest service creates with <a href="https://www.npmjs.com/package/json-server">json-server</a> package.</p><p>Create folder for demo items service and initialize a separate project.</p><pre>npm init</pre><p>Below package.json file will be created.</p><pre>{<br>  &quot;name&quot;: &quot;demo-items-service&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;description&quot;: &quot;&quot;,<br>  &quot;main&quot;: &quot;index.js&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;<br>  },<br>  &quot;author&quot;: &quot;&quot;,<br>  &quot;license&quot;: &quot;ISC&quot;<br>}</pre><p>Let’s install dependencies in the demo items service project folder.</p><pre>npm i json-server</pre><p>Create a new JSON file inside the service folder and copy the JSON content below.</p><pre>{<br>    &quot;items&quot;: [<br>        {<br>            &quot;id&quot;: &quot;1&quot;,<br>            &quot;name&quot;: &quot;First item&quot;,<br>            &quot;description&quot;: &quot;First item description&quot;<br>        },<br>        {<br>            &quot;id&quot;: &quot;2&quot;,<br>            &quot;name&quot;: &quot;Second item&quot;,<br>            &quot;description&quot;: &quot;Second item description&quot;<br>        },<br>        {<br>            &quot;id&quot;: &quot;3&quot;,<br>            &quot;name&quot;: &quot;Third item&quot;,<br>            &quot;description&quot;: &quot;Third item description&quot;<br>        },<br>        {<br>            &quot;id&quot;: &quot;4&quot;,<br>            &quot;name&quot;: &quot;Fourth item&quot;,<br>            &quot;description&quot;: &quot;Fourth item description&quot;<br>        },<br>        {<br>            &quot;id&quot;: &quot;5&quot;,<br>            &quot;name&quot;: &quot;Fifth item&quot;,<br>            &quot;description&quot;: &quot;Fifth item description&quot;<br>        }<br>    ]<br>}</pre><p>Start the JSON server using the below command. The newly created JSON file path needs to be given as an argument.</p><pre>npx json-server --watch &lt;file-path&gt; --port &lt;demo-items-service-port&gt;</pre><p>For this project 3030 port uses for the demo items service.</p><h4>Retry Pattern</h4><p>Invoke the <em>/api/item</em> endpoint of the demo sample-service project.</p><pre>curl --location &#39;http://localhost:8080/api/items&#39;</pre><p>To demonstrate retry execution and fallback method invocation, the <em>demo-items-service</em> can be terminated while invoking <a href="http://localhost:8080/api/items"><em>localhost:8080/api/items</em></a>.</p><p>Restarting the <em>demo-items-service</em> during the retry phase will ensure that <a href="http://localhost:8080/api/items"><em>localhost:8080/api/items</em></a> successfully returns a valid, non-empty items array as the response.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f4421b423d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>