<?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"><channel><title><![CDATA[rsaw409]]></title><description><![CDATA[rsaw409]]></description><link>https://blog.rsaw409.me</link><generator>RSS for Node</generator><lastBuildDate>Thu, 16 Apr 2026 21:16:37 GMT</lastBuildDate><atom:link href="https://blog.rsaw409.me/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Kafka: Replications and ISR]]></title><description><![CDATA[In Apache Kafka, the replication factor refers to the number of copies (replicas) of a topic partition that are maintained across the Kafka cluster.
ISR stands for In-Sync Replicas. It is the set of all replicas (including the leader replica) that ar...]]></description><link>https://blog.rsaw409.me/kafka-replications-and-isr</link><guid isPermaLink="true">https://blog.rsaw409.me/kafka-replications-and-isr</guid><category><![CDATA[kafka]]></category><category><![CDATA[kafka broker]]></category><category><![CDATA[replication]]></category><category><![CDATA[kafka topic]]></category><category><![CDATA[kafka-partition]]></category><category><![CDATA[replicaset]]></category><dc:creator><![CDATA[Rohit Saw]]></dc:creator><pubDate>Wed, 04 Dec 2024 09:47:07 GMT</pubDate><content:encoded><![CDATA[<p>In <strong>Apache Kafka</strong>, the <strong>replication factor</strong> refers to the number of copies (replicas) of a topic partition that are maintained across the Kafka cluster.</p>
<p><strong>ISR</strong> stands for <strong>In-Sync Replicas.</strong> It is the set of all replicas (including the leader replica) that are <strong>in sync</strong> with the leader of a Kafka partition.</p>
<p>For example, if the replication factor is set to <code>3</code>, Kafka will maintain 3 copies of the data for that partition across different brokers. (1 leader + 2 followers)</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1733304343168/eb003c29-54d3-40c3-b7d8-36b2895d288b.png" alt class="image--center mx-auto" /></p>
<p>One replica is designated as the <strong>leader</strong>. All read and write operations for the partition are handled by this leader. Other replicas are <strong>followers</strong>, which replicate data from the leader to stay in sync.</p>
<h3 id="heading-importance-of-isr">Importance of ISR</h3>
<p><strong>High Availability</strong>: If the leader replica fails, one of the replicas in the ISR can take over as the new leader, ensuring no data loss or downtime.</p>
<p><strong>Durability Guarantees</strong>: Kafka can be configured to acknowledge writes only when data is written to all replicas in the ISR (<code>acks=all</code>), which ensures stronger durability.</p>
<p><strong>Replication Lag Monitoring</strong>: Kafka continuously monitors replicas to ensure they remain in sync. If a replica falls behind for too long, it is removed from the ISR.</p>
<h3 id="heading-trade-offs"><strong>Trade-Offs</strong></h3>
<p><strong>Increased Fault Tolerance vs. Resource Usage:</strong> Each replica consumes additional disk space on the brokers. For example, a replication factor of 3 triples the storage requirement for the same data.</p>
<p><strong>High Availability vs. Performance Overheads:</strong> A higher replication factor increases the time to propagate writes across all replicas. This is especially significant when using <code>acks=all</code>, as the leader waits for acknowledgments from all in-sync replicas (ISR) before confirming the write.</p>
<hr />
<p>Hope this helps to get some understanding of How Replication work in Kafka. Let me know if you have any other questions.</p>
<h3 id="heading-resources"><strong>Resources</strong></h3>
<ul>
<li><p><a target="_blank" href="https://kafka.js.org/"><strong>kafka.js.org</strong></a></p>
</li>
<li><p><a target="_blank" href="https://kafka.apache.org/"><strong>kafka.apache.org</strong></a></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Event Capturing in JavaScript]]></title><description><![CDATA[Event capturing occurs when a nested element gets clicked. The click event of its parent elements must be triggered before the click of the nested element.

Event capturing is not the default behavior of Javascript Events. In vanilla javaScript we ne...]]></description><link>https://blog.rsaw409.me/event-capturing-in-javascript</link><guid isPermaLink="true">https://blog.rsaw409.me/event-capturing-in-javascript</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[events]]></category><category><![CDATA[Event propagation]]></category><category><![CDATA[Event Capturing And Event Bubbling In JavaScript]]></category><category><![CDATA[event capturing]]></category><dc:creator><![CDATA[Rohit Saw]]></dc:creator><pubDate>Tue, 03 Dec 2024 06:07:51 GMT</pubDate><content:encoded><![CDATA[<p>Event capturing occurs when a nested element gets clicked. The click event of its parent elements must be triggered before the click of the nested element.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1733205961506/5ee08249-449e-45da-a08f-843b8192f2de.png" alt class="image--center mx-auto" /></p>
<p>Event capturing is not the default behavior of Javascript Events. In vanilla javaScript we need to pass <code>true</code> in the 3rd argument of <code>addEventListener</code> function to register the handler in event capturing mode.</p>
<p>In React.js we can register the capturing handler via <code>onClickCapture</code> function in component.</p>
<p>Now let's see this behavior live in React Application. Here I've created three <code>div</code> element with <code>onClickCapture</code> event handler so that we can <code>console.log</code> if this event handler gets executed on this element.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> <span class="hljs-string">"./styles.css"</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"App"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span>
        <span class="hljs-attr">className</span>=<span class="hljs-string">"green"</span>
        <span class="hljs-attr">onClickCapture</span>=<span class="hljs-string">{(e)</span> =&gt;</span> {
          console.log("green!");
        }}
      &gt;
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span>
          <span class="hljs-attr">className</span>=<span class="hljs-string">"yellow"</span>
          <span class="hljs-attr">onClickCapture</span>=<span class="hljs-string">{(e)</span> =&gt;</span> {
            console.log("yellow!");
          }}
        &gt;
          <span class="hljs-tag">&lt;<span class="hljs-name">div</span>
            <span class="hljs-attr">className</span>=<span class="hljs-string">"pink"</span>
            <span class="hljs-attr">onClickCapture</span>=<span class="hljs-string">{(e)</span> =&gt;</span> {
              console.log("pink!");
            }}
          &gt;<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<pre><code class="lang-css"><span class="hljs-selector-class">.App</span> {
    <span class="hljs-attribute">font-family</span>: sans-serif;
    <span class="hljs-attribute">text-align</span>: center;
  }

  <span class="hljs-selector-class">.green</span> {
    <span class="hljs-attribute">background-color</span>: green;
    <span class="hljs-attribute">width</span>: <span class="hljs-number">600px</span>;
    <span class="hljs-attribute">height</span>: <span class="hljs-number">600px</span>;
    <span class="hljs-attribute">position</span>: absolute;
  }

  <span class="hljs-selector-class">.yellow</span> {
    <span class="hljs-attribute">background-color</span>: yellow;
    <span class="hljs-attribute">width</span>: <span class="hljs-number">400px</span>;
    <span class="hljs-attribute">height</span>: <span class="hljs-number">400px</span>;
    <span class="hljs-attribute">position</span>: absolute;
    <span class="hljs-attribute">top</span>: <span class="hljs-number">100px</span>;
    <span class="hljs-attribute">left</span>: <span class="hljs-number">100px</span>;
  }

  <span class="hljs-selector-class">.pink</span> {
    <span class="hljs-attribute">background-color</span>: pink;
    <span class="hljs-attribute">width</span>: <span class="hljs-number">200px</span>;
    <span class="hljs-attribute">height</span>: <span class="hljs-number">200px</span>;
    <span class="hljs-attribute">position</span>: absolute;
    <span class="hljs-attribute">top</span>: <span class="hljs-number">100px</span>;
    <span class="hljs-attribute">left</span>: <span class="hljs-number">100px</span>;
  }
</code></pre>
<p>Now UI will look like this. So now we can inspect the console by clicking on these three different <code>div.</code></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1733205106348/f959932b-1f70-4888-a92b-32488d3eda9e.png" alt class="image--center mx-auto" /></p>
<p>If we click on the different color box. we get these outputs in consoles. which clearly shows how <code>click</code> events get propagated from the root ancestor and <code>onClickCapture</code> event handler gets executed for each of these <code>div.</code> We can stop this propagation at any <code>div</code> by calling <code>e.stopPropagation()</code> on any event handler so this event will not get propagated further.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1733205584751/590081ad-b98a-4c0c-9b3e-cf4afc4ec69c.png" alt class="image--center mx-auto" /></p>
<p>Hope this helps! Let me know if you have any other questions.</p>
<p><strong>Resources</strong></p>
<ol>
<li><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation"><strong>https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation</strong></a></li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Kafka: Topics, Partition & Consumers]]></title><description><![CDATA[Concepts
What is Kafka? Apache Kafka is an open-source distributed event streaming platform used by thousands of companies for high-performance data pipelines, streaming analytics, data integration, and mission-critical applications.
What is Topic? K...]]></description><link>https://blog.rsaw409.me/kafka-topics-partition-consumers</link><guid isPermaLink="true">https://blog.rsaw409.me/kafka-topics-partition-consumers</guid><category><![CDATA[kafka]]></category><category><![CDATA[kafka topic]]></category><category><![CDATA[kafka broker]]></category><category><![CDATA[Microservices]]></category><category><![CDATA[Node.js]]></category><dc:creator><![CDATA[Rohit Saw]]></dc:creator><pubDate>Fri, 10 Nov 2023 15:25:16 GMT</pubDate><content:encoded><![CDATA[<h3 id="heading-concepts">Concepts</h3>
<p><strong>What is Kafka?</strong> Apache Kafka is an open-source distributed event streaming platform used by thousands of companies for high-performance data pipelines, streaming analytics, data integration, and mission-critical applications.</p>
<p><strong>What is Topic?</strong> Kafka topics are the categories used to organize messages. Each topic has a name that is unique across the entire Kafka cluster. Messages are sent to and read from specific topics. In other words, producers write data to topics, and consumers read data from topics.</p>
<p><strong>What is Partition?</strong> Kafka Topic is divided into several partitions. Kafka guarantees the order of the messages sent within the same topic partition**.** Since a topic can be split into partitions over multiple machines, multiple consumers can read a topic in parallel. This organization sets Kafka up for high message throughput.</p>
<p><strong>What is Consumer?</strong> A consumer is the one client that consumes or reads data from the Kafka cluster via a topic. A consumer also knows from which broker, it should read the data. The consumer reads the data within each partition in an orderly manner.</p>
<p><strong>What is Consumer Group?</strong> A consumer group is a set of consumers cooperating to consume data from some topics. The partitions of the topics are divided among the consumers in the group so that each member receives a proportional share of the partitions from a topic.</p>
<h3 id="heading-implementation-in-nodejs">Implementation in Node.js</h3>
<p>Let's create our utility class for using Kafka.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { Kafka } <span class="hljs-keyword">from</span> <span class="hljs-string">"kafkajs"</span>;

<span class="hljs-comment">// Our Wrapper class for using kafka utility</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">KafkaWrapper</span> </span>{
  <span class="hljs-comment">// private variable for holding kafka client admin, producer </span>
  <span class="hljs-comment">// and list of consumers.</span>
  #admin;
  #producer;
  #consumers = [];

  <span class="hljs-comment">// initialization kafka client connected to locally running brokers.</span>
  <span class="hljs-keyword">static</span> #kafka = <span class="hljs-keyword">new</span> Kafka({
    <span class="hljs-attr">clientId</span>: <span class="hljs-string">"kafka-demo"</span>,
    <span class="hljs-attr">brokers</span>: [<span class="hljs-string">"localhost:9092"</span>],
  });

  <span class="hljs-comment">// Function to initialization kafka &amp; producers.</span>
  <span class="hljs-comment">// passed topics array will be created in kafka cluster</span>
  <span class="hljs-keyword">async</span> initProducer(topics) {
    <span class="hljs-built_in">this</span>.#admin = KafkaWrapper.#kafka.admin();
    <span class="hljs-keyword">await</span> <span class="hljs-built_in">this</span>.#admin.connect();
    <span class="hljs-keyword">await</span> <span class="hljs-built_in">this</span>.#admin.createTopics({
      <span class="hljs-attr">topics</span>: topics,
    });
    <span class="hljs-built_in">this</span>.#producer = KafkaWrapper.#kafka.producer();
  }

  <span class="hljs-comment">// Function to initialise new Consumer</span>
  <span class="hljs-comment">// groupId -&gt; id of group </span>
  <span class="hljs-comment">// topic -&gt; topic name for which this consumer is subscribed to.</span>
  <span class="hljs-comment">// callback -&gt; callback handler whenever this consumber this message on provided topic.</span>
  <span class="hljs-keyword">async</span> initConsumer(groupId, topic, callback) {
    <span class="hljs-built_in">this</span>.#consumers.push(KafkaWrapper.#kafka.consumer({ groupId }));
    <span class="hljs-keyword">await</span> <span class="hljs-built_in">this</span>.#consumers.at(<span class="hljs-number">-1</span>).connect();
    <span class="hljs-keyword">await</span> <span class="hljs-built_in">this</span>.#consumers.at(<span class="hljs-number">-1</span>).subscribe({ topic });
    <span class="hljs-keyword">await</span> <span class="hljs-built_in">this</span>.#consumers.at(<span class="hljs-number">-1</span>).run({
      <span class="hljs-attr">eachMessage</span>: <span class="hljs-keyword">async</span> (message) =&gt; {
        callback(message);
      },
    });
  }

  <span class="hljs-comment">// Function to send message into provided topic.</span>
  <span class="hljs-keyword">async</span> sendMessages(msg, topic) {
    <span class="hljs-keyword">await</span> <span class="hljs-built_in">this</span>.#producer.connect();
    <span class="hljs-keyword">await</span> <span class="hljs-built_in">this</span>.#producer.send({
      <span class="hljs-attr">topic</span>: topic,
      <span class="hljs-attr">messages</span>: [{ <span class="hljs-attr">value</span>: msg }],
    });
  }
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> KafkaWrapper;
</code></pre>
<p>Our code is self-explanatory. There are two important methods of class <code>sendMessages(msg, topic)</code> which will send a message to the topic provided via argument and <code>initConsumer(groupId, topic, callback)</code> that will create a new consumer inside the provided group, this will also subscribe to the provided topic and execute the provided callback function whenever a message is received on this consumer.</p>
<p>Now let's create a driver code.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// configuration varaiable for topic &amp; partition of topic.</span>
<span class="hljs-keyword">const</span> topic = <span class="hljs-string">"topic"</span>;
<span class="hljs-keyword">const</span> partition = <span class="hljs-number">3</span>;

<span class="hljs-comment">// object for storing recevied messages so that we can later print &amp; see.</span>
<span class="hljs-keyword">const</span> res = {};

<span class="hljs-comment">// Configuration array for consumers</span>
<span class="hljs-comment">// if there are N number of element in array </span>
<span class="hljs-comment">// then N number of consumber will be created with provided configuration</span>
<span class="hljs-keyword">const</span> consumers = [{ <span class="hljs-attr">consumer</span>: <span class="hljs-string">"consumer"</span>, <span class="hljs-attr">group</span>: <span class="hljs-string">"group"</span> }];

<span class="hljs-comment">// handler for received messages &amp; storing in res object.</span>
<span class="hljs-keyword">const</span> handleMessage = <span class="hljs-function">(<span class="hljs-params">consumerId, msg</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> { partition, message } = msg;
  <span class="hljs-keyword">if</span> (!res.hasOwnProperty(consumerId)) res[consumerId] = [];
  res[consumerId].push({ partition, <span class="hljs-attr">message</span>: message.value.toString() });
};

<span class="hljs-comment">// init kafka broker.</span>
<span class="hljs-keyword">const</span> broker = <span class="hljs-keyword">new</span> Kafka();
<span class="hljs-keyword">await</span> broker.initProducer([{ <span class="hljs-attr">topic</span>: topic, <span class="hljs-attr">numPartitions</span>: partition }]);

<span class="hljs-comment">// init consumers from consumer configuration array</span>
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> each <span class="hljs-keyword">of</span> consumers) {
  <span class="hljs-keyword">await</span> broker.initConsumer(each.group, topic, <span class="hljs-function">(<span class="hljs-params">msg</span>) =&gt;</span>
    handleMessage(each.consumer, msg)
  );
}

<span class="hljs-comment">// sending 10 messages to topic</span>
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">1</span>; i &lt;= <span class="hljs-number">10</span>; i++) {
  <span class="hljs-keyword">await</span> broker.sendMessages(<span class="hljs-string">`Hello <span class="hljs-subst">${i}</span>`</span>, topic);
}

<span class="hljs-comment">// printing received messages after some delay.</span>
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(res), <span class="hljs-number">2000</span>);
</code></pre>
<p>Now we have an interface to test our Kafka communication. we can create as many consumers within the same group or different groups by adding more configuration objects in the consumer array. we can also increase or decrease the partition of topics by changing <code>partition</code> variable.</p>
<h3 id="heading-examples">Examples</h3>
<p>Now we run our code as per the below images by configuring the number of partitions on the topic and the number of consumers subscribing to that topic.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1699357903326/0f24de09-e812-4b4e-a56b-c5fcc1a3830b.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1699627448012/88ca9cee-eaa9-44dd-8804-1e675cd27adf.png" alt class="image--center mx-auto" /></p>
<p><strong>Explanation</strong> - Here a topic is divided into 3 partitions and a consumer group with 3 members subscribes to that topic, then Kafka will assign each partition to each group member to distribute load and increase message throughput on that topic.</p>
<hr />
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1699358364344/e2fe2693-f84a-4e46-9bad-8bdd64701302.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1699628171175/e780faac-7bd2-4e2a-a4f1-e442c81f8b8a.png" alt class="image--center mx-auto" /></p>
<p><strong>Explanation</strong> - Here a topic is divided into 3 partitions and a single consumer subscribes to that topic, then Kafka will assign All partitions to that Consumer so that all messages get delivered and processed by that consumer.</p>
<hr />
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1699358957789/fddcbe2e-3c04-4766-8926-bc3a12334624.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1699628283268/1bda58af-74aa-4729-b3ef-f68b455b9ecc.png" alt class="image--center mx-auto" /></p>
<p><strong>Explanation</strong> - Here a topic is divided into 3 partitions and the Consumer group has only 2 members. In this case, Kafka will try to distribute loads and assign each partition to each group member and one member will get assigned to two partition. (Here in code <strong>Consumer B</strong> gets assigned to <strong>Partition 0 &amp; 1 i</strong>nstead of consumer A as in image).</p>
<hr />
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1699359570906/786116cc-39d0-4348-ad2a-ca6bb0ad0fc6.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1699628559320/1bfa808c-5a69-4c9d-b6b5-0177298588a1.png" alt class="image--center mx-auto" /></p>
<p><strong>Explanation</strong> - Here a topic is divided into two partitions and the Consumer group has three members. Even we have three members only two members will get assigned to partition because we have only two partition and additional members will sit idle without receiving any messages.</p>
<hr />
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1699629720110/348ee54f-5772-4d15-bbf4-687f5bcbba00.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1699629213215/21fc67d3-e13f-4328-8771-d4b17a2a4414.png" alt class="image--center mx-auto" /></p>
<p><strong>Explanation</strong> - Here a topic is divided into three partitions and there are two consumer group with different number of members inside group. Here you can see Kafka automatically distribute load so that each consumer group get all message.</p>
<p>In First Consumer Group, All partition get assigned to each member of group.</p>
<ul>
<li><p>ConsumerA get assigned to partition 2</p>
</li>
<li><p>ConsumerB get assigned to partition 0</p>
</li>
<li><p>ConsumerC get assigned to partition 1</p>
</li>
</ul>
<p>In Second Group,</p>
<ul>
<li><p>ConsumerD get assigned to partition 1</p>
</li>
<li><p>ConsumerE get assigned to partition 0 &amp; 2.</p>
</li>
</ul>
<hr />
<p>Hope this helps to get some understanding of How Kafka works. Let me know if you have any other questions.</p>
<h3 id="heading-resources">Resources</h3>
<ul>
<li><p><a target="_blank" href="https://kafka.js.org/"><strong>https://kafka.js.org/</strong></a></p>
</li>
<li><p><a target="_blank" href="https://kafka.apache.org/"><strong>https://kafka.apache.org/</strong></a></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Microservice Communication with Kafka]]></title><description><![CDATA[Overview
Communication between Microservices can be categorized into two types, Synchronous and Asynchronous Communication. while REST and gRPC are Synchronous ways of communication, Kafka communications are asynchronous and do not wait for a respons...]]></description><link>https://blog.rsaw409.me/microservice-communication-with-kafka</link><guid isPermaLink="true">https://blog.rsaw409.me/microservice-communication-with-kafka</guid><category><![CDATA[Node.js]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Microservices]]></category><category><![CDATA[kafka]]></category><category><![CDATA[kafka broker]]></category><dc:creator><![CDATA[Rohit Saw]]></dc:creator><pubDate>Tue, 31 Oct 2023 16:29:18 GMT</pubDate><content:encoded><![CDATA[<h3 id="heading-overview">Overview</h3>
<p>Communication between Microservices can be categorized into two types, Synchronous and Asynchronous Communication. while REST and gRPC are Synchronous ways of communication, Kafka communications are asynchronous and do not wait for a response. Here we will see the local setup of Kafka in node.js and communications between services with Kafka queue.</p>
<h3 id="heading-installation">Installation</h3>
<p>To install Apache Kafka, Java is the only prerequisite. Make Sure at least Java 11 is already installed in your system.</p>
<ul>
<li><p>Download the latest version of Apache Kafka from the official <a target="_blank" href="https://kafka.apache.org/downloads">site</a> under Binary Downloads.</p>
</li>
<li><p>Extract the contents (double click in the Finder) to a directory of your choice.</p>
</li>
<li><p>Now you have to start two services <strong>zookeeper</strong> and <strong>kafka</strong> from downloaded binaries.</p>
</li>
<li><p>Suppose the extracted directory is kafka_2.13-3.60 (The name of the directory may be different based on your installed Kafka version), Go to the Root Directory where you have extracted Kafka and run the following command to start zookeeper.</p>
<pre><code class="lang-bash">  kafka_2.13-3.6.0/bin/zookeeper-server-start.sh kafka_2.13-3.6.0/config/zookeeper.properties
</code></pre>
</li>
<li><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698500802237/43a21ed5-5f69-436d-8762-4747d232528d.png" alt class="image--center mx-auto" /></p>
</li>
<li><p>Open another Terminal window and run the following command to start the local Kafka server.</p>
</li>
</ul>
<pre><code class="lang-bash">kafka_2.13-3.6.0/bin/kafka-server-start.sh kafka_2.13-3.6.0/config/server.properties
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698500911859/cb660f6d-d88c-46f4-8c72-198458c69444.png" alt class="image--center mx-auto" /></p>
<ul>
<li><p>Kafka is Now Started on <code>localhost:9092</code> . Ensure both terminals are running always otherwise you will shut down the zookeeper or Kafka.</p>
</li>
<li><p>you can also make a single executable script to run both commands at different terminals as per your operating system. (In macOS you can use something similar to this to start both as a single command).</p>
</li>
<li><p>you can read more about downloaded Kafka binaries on the official <a target="_blank" href="https://kafka.apache.org/intro">site</a>.</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698769299307/4978d017-538f-4086-a1f7-4420d497d9a1.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-setup-in-nodejs">Setup in Node.js</h3>
<p>We must install the Kafka client library for node.js to use our locally running Kafka server. for this tutorial, we will be installing <a target="_blank" href="https://kafka.js.org/">kafkaJS</a> from <a target="_blank" href="https://www.npmjs.com/package/kafkajs">npm</a>.</p>
<p>To utilize Kafka for microservice communications, we need to write some boilerplate code for different roles such as producer, consumer, and admin in the Kafka client library such that the producer will produce messages in some topic, and then a consumer can consume that message. with the help of the admin client users can configure their Kafka clients.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698766783261/981b77a9-ce76-408d-a4e8-57ea9ef9a787.png" alt class="image--center mx-auto" /></p>
<p>In the <code>admin.js</code> file, we need to provide the address of the running Kafka broker during initialization, In this case, our local Kafka instance is running at <code>localhost:9092.</code> we can also create a topic and use that topic in producer and consumer files for sending and receiving messages as per the above templates. For now, we are just consoling received messages.</p>
<p>Now our basic template is ready we just need the driver code to use our <code>sendMessage</code> function. for that, we have created <code>index.js</code> to act as both producer as well as consumer based on passed <code>argv</code> from the command line. In producer mode, it will continuously send messages using our <code>sendMessage</code> function. In consumer mode, it will subscribe to the topic and start listening to it using <code>initConsumer</code>.</p>
<p>Now open two terminals and enter the following command.</p>
<ul>
<li><p>npm start producer</p>
</li>
<li><p>npm start consumer</p>
</li>
</ul>
<p>Note: - you may also need to add the <code>start</code> command in the script section of the <code>package.json</code> file as per your folder structure to run the <code>index.js</code> file</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698767838995/5e6b4a79-cde5-4023-b7ea-d038e68f9620.png" alt class="image--center mx-auto" /></p>
<p>First, start the consumer using the above command and then start the producer and see the message passing between these two services in action as below.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698768302812/d24159e4-4112-474c-8442-fec30dc0522b.gif" alt class="image--center mx-auto" /></p>
<p>Hope this helps to get some understanding of Kafka with node.js. Let me know if you have any other questions.</p>
<h3 id="heading-resources">Resources</h3>
<ol>
<li><p><a target="_blank" href="https://kafka.js.org/">https://kafka.js.org/</a></p>
</li>
<li><p><a target="_blank" href="https://kafka.apache.org/intro">https://kafka.apache.org/</a></p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Generator Function in JavaScript]]></title><description><![CDATA[Generator Function is used to Pause and Resume the execution of the function with its context (variable bindings) saved across re-entrances. This allows you to generate values on-the-fly, without having to generate all of the values at once.
A genera...]]></description><link>https://blog.rsaw409.me/generator-function-in-javascript</link><guid isPermaLink="true">https://blog.rsaw409.me/generator-function-in-javascript</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Generator function]]></category><category><![CDATA[generator]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[optimization]]></category><dc:creator><![CDATA[Rohit Saw]]></dc:creator><pubDate>Mon, 31 Jul 2023 10:32:36 GMT</pubDate><content:encoded><![CDATA[<p>Generator Function is used to Pause and Resume the execution of the function with its context (variable <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/Binding">bindings</a>) saved across re-entrances. This allows you to generate values on-the-fly, without having to generate all of the values at once.</p>
<p>A generator is <strong>a special type of function that does not return a single value, instead, it returns an iterator object with a sequence of values</strong>. In a generator function, a yield statement is used rather than a return statement.</p>
<p>we can directly loop over returned iterator from the generator function or we can get the next value from the iterator object by calling <code>next()</code> method of iterator which will return an object <code>{ value: any, done: boolean }</code> where <code>value</code> is any value that is <code>yield</code> by generator function and <code>done</code> is a boolean flag to indicate if the execution of the generator function is complete.</p>
<p>A <code>return</code> statement in a generator, when executed, will make the generator finish (i.e. the <code>done</code> property of the object returned by it will be set to <code>true</code>).</p>
<h3 id="heading-the-implementation">The implementation</h3>
<p>we can create a generator function in javascript by using <code>function*</code> and <code>yield</code> syntax. here is an example of a Fibonacci generator that will generate the next Fibonacci number on the fly.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span>* <span class="hljs-title">fibonacci</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-keyword">let</span> a = <span class="hljs-number">0</span>;
    <span class="hljs-keyword">let</span> b = <span class="hljs-number">1</span>;

    <span class="hljs-keyword">while</span> (<span class="hljs-literal">true</span>){
        <span class="hljs-keyword">yield</span> a;
        <span class="hljs-keyword">let</span> tmp = a;
        a = b;
        b = tmp + b;
    }
}

<span class="hljs-keyword">const</span> fibb = fibonacci();

<span class="hljs-comment">// Generating first 10 fibonacci number on fly</span>
<span class="hljs-keyword">for</span>(<span class="hljs-keyword">let</span> i=<span class="hljs-number">0</span>; i&lt;<span class="hljs-number">10</span>; i++){
    <span class="hljs-built_in">console</span>.log(fibb.next().value)
}

<span class="hljs-comment">/* output 
0
1
1
2
3
5
8
13
21
34
------------------------------   */</span>
</code></pre>
<h3 id="heading-advantage">Advantage</h3>
<ol>
<li><p>Lazy Evaluation: Suppose there is a large or infinite stream of data. we cannot spend our whole life evaluating that data. Hence we can use Generator function to evaluate as and when required.</p>
</li>
<li><p>Memory Efficient: Generator functions are memory efficient because only those data and those computations that are necessary are used. eg: Suppose we want to read and process all files in a particular directory, we can always write a generator function to read and process files one by one as required.</p>
</li>
<li><p>Time-efficient when compared to overhead in managing intermediary lists as shown below image.</p>
</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1690799142882/3067b757-d3a7-46d4-8376-f0ec7be9c863.png" alt class="image--center mx-auto" /></p>
<p>Hope this helps! Let me know if you have any other questions.</p>
<p><strong>Resources</strong></p>
<ol>
<li><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*</a></li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Event Bubbling in JavaScript]]></title><description><![CDATA[Event Bubbling is a concept of event propagation in the DOM. when an event occurs inside an HTML element. it gets propagated or bubbles up to its parent and ancestor element in the DOM tree until it gets to the root element.

Now let's see this behav...]]></description><link>https://blog.rsaw409.me/event-bubbling-in-javascript</link><guid isPermaLink="true">https://blog.rsaw409.me/event-bubbling-in-javascript</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[eventbubbling]]></category><category><![CDATA[React]]></category><category><![CDATA[Event Capturing And Event Bubbling In JavaScript]]></category><category><![CDATA[Event propagation]]></category><dc:creator><![CDATA[Rohit Saw]]></dc:creator><pubDate>Mon, 31 Jul 2023 07:16:17 GMT</pubDate><content:encoded><![CDATA[<p>Event Bubbling is a concept of event propagation in the DOM. when an event occurs inside an HTML element. it gets propagated or bubbles up to its parent and ancestor element in the DOM tree until it gets to the root element.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1690785713634/fb3fb1e0-ecbe-45ee-b3e5-4d6c206d2407.jpeg" alt class="image--center mx-auto" /></p>
<p>Now let's see this behavior live in React Application. Here I've created three <code>div</code> element with <code>onClick</code> event handler so that we can <code>console.log</code> if this event handler gets executed on this element.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> <span class="hljs-string">"./styles.css"</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"App"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span>
        <span class="hljs-attr">className</span>=<span class="hljs-string">"green"</span>
        <span class="hljs-attr">onClick</span>=<span class="hljs-string">{(e)</span> =&gt;</span> {
          console.log("green!");
        }}
      &gt;
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span>
          <span class="hljs-attr">className</span>=<span class="hljs-string">"yellow"</span>
          <span class="hljs-attr">onClick</span>=<span class="hljs-string">{(e)</span> =&gt;</span> {
            console.log("yellow!");
          }}
        &gt;
          <span class="hljs-tag">&lt;<span class="hljs-name">div</span>
            <span class="hljs-attr">className</span>=<span class="hljs-string">"pink"</span>
            <span class="hljs-attr">onClick</span>=<span class="hljs-string">{(e)</span> =&gt;</span> {
              console.log("pink!");
            }}
          &gt;<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<pre><code class="lang-css"><span class="hljs-selector-class">.App</span> {
  <span class="hljs-attribute">font-family</span>: sans-serif;
  <span class="hljs-attribute">text-align</span>: center;
}

<span class="hljs-selector-class">.green</span> {
  <span class="hljs-attribute">background-color</span>: green;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">600px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">600px</span>;
  <span class="hljs-attribute">position</span>: absolute;
}

<span class="hljs-selector-class">.yellow</span> {
  <span class="hljs-attribute">background-color</span>: yellow;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">400px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">400px</span>;
  <span class="hljs-attribute">position</span>: absolute;
  <span class="hljs-attribute">top</span>: <span class="hljs-number">100px</span>;
  <span class="hljs-attribute">left</span>: <span class="hljs-number">100px</span>;
}

<span class="hljs-selector-class">.pink</span> {
  <span class="hljs-attribute">background-color</span>: pink;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">200px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">200px</span>;
  <span class="hljs-attribute">position</span>: absolute;
  <span class="hljs-attribute">top</span>: <span class="hljs-number">100px</span>;
  <span class="hljs-attribute">left</span>: <span class="hljs-number">100px</span>;
}
</code></pre>
<p>Now UI will look like this. So now when we inspect the console by clicking on these three different <code>div.</code></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1690641076633/4a8bd8ac-8aec-47c2-90e4-6dbb22e01083.png" alt class="image--center mx-auto" /></p>
<p>If we click on the different color box. we get these outputs in consoles. which clearly shows how <code>click</code> events get propagated till the root ancestor and <code>onClick</code> event handler gets executed for each of these <code>div.</code> We can stop this propagation at any <code>div</code> by calling <code>e.stopPropagation()</code> on any event handler so this event will not get propagated further.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1690787354269/ab79a708-413d-4645-8326-c734350672b8.jpeg" alt class="image--center mx-auto" /></p>
<p>Hope this helps! Let me know if you have any other questions.</p>
<p><strong>Resources</strong></p>
<ol>
<li><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation">https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation</a></li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Distributed Lock in MicroServices]]></title><description><![CDATA[Distributed locking is a technique to manage many applications or instances of applications that try to access the same resource. The primary purpose is to allow only one of many applications to access the same resource simultaneously.
The Problem
In...]]></description><link>https://blog.rsaw409.me/distributed-lock-in-microservices</link><guid isPermaLink="true">https://blog.rsaw409.me/distributed-lock-in-microservices</guid><category><![CDATA[mutex]]></category><category><![CDATA[Redis]]></category><category><![CDATA[PostgreSQL]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[distributed lock]]></category><dc:creator><![CDATA[Rohit Saw]]></dc:creator><pubDate>Sat, 29 Jul 2023 08:26:20 GMT</pubDate><content:encoded><![CDATA[<p>Distributed locking is <strong>a technique to manage many applications or instances of applications that try to access the same resource</strong>. The primary purpose is to allow only one of many applications to access the same resource simultaneously.</p>
<h3 id="heading-the-problem">The Problem</h3>
<p>In Software Engineering, there are scenarios when we want to place a mutex lock in some section of code before executing that section and want no other application can access that code while some service is still in that critical section. There are many scenarios in which distributed locks can help us</p>
<p>Suppose there is a microservice with 3 pods named A, B, and C and a scheduled cron job that runs every day at 12:00 AM for some routine task. Because this cron job is written inside the microservice so always 3 instances of the cron job will run at 12:00 AM every day. This will cause unnecessary complexity and may corrupt data of routine tasks. So where we can place distributed mutex lock so only one pod can execute this routine task while for other pods this section of code is locked for execution.</p>
<h3 id="heading-redlock">Redlock</h3>
<p>If your software uses Redis then you can use <strong>Redlock</strong> distributed lock<strong>,</strong> an Algorithm proposed by Redis. This Algorithm implementation is already available in different programming languages. you can read more about it on the official <a target="_blank" href="https://redis.io/docs/manual/patterns/distributed-locks/">site</a>.</p>
<p>Sample implementation in Javascript</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Creating Redlock instance for some key with help of any library implementation.</span>
<span class="hljs-keyword">const</span> mutex = <span class="hljs-keyword">new</span> RedLock(<span class="hljs-string">"keyToLock"</span>)

<span class="hljs-comment">// trying to acquire lock if it is available to acquire.</span>
<span class="hljs-keyword">const</span> isLockAcquired = <span class="hljs-keyword">await</span> mutex.tryAcquire();

<span class="hljs-comment">// if lock is acquired successfully the execute critical code.</span>
<span class="hljs-keyword">if</span> (isLockAcquired){
    scheduleTask()

    <span class="hljs-comment">// once task is done, release lock for key</span>
    <span class="hljs-keyword">await</span> mutex.release()
} <span class="hljs-keyword">else</span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"task is already running in some other pod."</span>)
}
</code></pre>
<h3 id="heading-postgres-advisory-locks">Postgres Advisory Locks</h3>
<p>Postgres Advisory Locks are a great solution for arbitrary application locks, particularly in scenarios where you are already using Postgres and have a need to block concurrent mutations to a resource (that resource DOES NOT have to be data in Postgres).</p>
<p>There are two types of Postgres Advisory Locks: session and transaction.</p>
<p><strong>Session Locks:</strong> Session locks, once acquired, are held until they are manually released or the database client is disconnected:</p>
<pre><code class="lang-pgsql"><span class="hljs-comment">-- Acquire a lock using an arbitrary BigInt. </span>
<span class="hljs-comment">-- if fails to acquire a lock, an error will be returned to the client.</span>
<span class="hljs-keyword">SELECT</span> pg_advisory_lock(<span class="hljs-number">123</span>);

<span class="hljs-comment">-- Unlock</span>
<span class="hljs-keyword">SELECT</span> pg_advisory_unlock(<span class="hljs-number">123</span>);

<span class="hljs-comment">-- return "true" is the lock is acquired, "false" if not.</span>
<span class="hljs-keyword">SELECT</span> pg_try_advisory_lock(<span class="hljs-number">123</span>);
</code></pre>
<p><strong>Transaction Locks:</strong> Transactions locks differ only in that they are released at the end of a transaction. Transaction Advisory Locks differ only in <code>_xact</code> on function names:</p>
<pre><code class="lang-pgsql"><span class="hljs-keyword">SELECT</span> pg_advisory_xact_lock(<span class="hljs-number">123</span>);

<span class="hljs-keyword">SELECT</span> pg_advisory_xact_unlock(<span class="hljs-number">123</span>);

<span class="hljs-keyword">SELECT</span> pg_try_advisory_xact_lock(<span class="hljs-number">123</span>);
</code></pre>
<p>Hope this helps! Let me know if you have any other questions.</p>
<h3 id="heading-resources">Resources</h3>
<ol>
<li><p><a target="_blank" href="https://redis.io/docs/manual/patterns/distributed-locks/">https://redis.io/docs/manual/patterns/distributed-locks/</a></p>
</li>
<li><p><a target="_blank" href="https://redis.com/glossary/redlock/">https://redis.com/glossary/redlock/</a></p>
</li>
<li><p><a target="_blank" href="https://www.postgresql.org/docs/current/explicit-locking.html#ADVISORY-LOCKS">https://www.postgresql.org/docs/current/explicit-locking.html#ADVISORY-LOCKS</a></p>
</li>
<li><p><a target="_blank" href="https://rclayton.silvrback.com/distributed-locking-with-postgres-advisory-locks">https://rclayton.silvrback.com/distributed-locking-with-postgres-advisory-locks</a></p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Named Parameters in JavaScript]]></title><description><![CDATA[What is Named Parameters
Named means that when you call a function, you attach the argument to a label. Named arguments enable you to specify an argument for a parameter by matching the argument with its name rather than with its position in the para...]]></description><link>https://blog.rsaw409.me/named-parameters-in-javascript</link><guid isPermaLink="true">https://blog.rsaw409.me/named-parameters-in-javascript</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Object Destructuring in JavaScript]]></category><category><![CDATA[default parameter]]></category><category><![CDATA[named parameters]]></category><category><![CDATA[named arguments]]></category><dc:creator><![CDATA[Rohit Saw]]></dc:creator><pubDate>Sun, 23 Jul 2023 08:00:28 GMT</pubDate><content:encoded><![CDATA[<h3 id="heading-what-is-named-parameters">What is Named <strong>Parameters</strong></h3>
<p><em>Named</em> means that when you call a function, you attach the argument to a label. <em>Named arguments</em> enable you to specify an argument for a parameter by matching the argument with its name rather than with its position in the parameter list. So you can pass an argument to Function in any order irrespective of its position.</p>
<p>Named parameters are supported explicitly in many languages like Python, Dart, CSharp, Ruby, Scala, and Kotlin. JavaScript, by default, does not support Named Parameters. However, you can do something similar using object literals and destructuring.</p>
<h3 id="heading-object-literals-and-destructuring">Object Literals and Destructuring</h3>
<p>The destructuring assignment is a cool feature that came along with JavaScript ES6. It makes it possible to unpack values from arrays, or properties from objects, into distinct variables. Here We are unpacking variables a &amp; b from the object a.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> obj = { <span class="hljs-attr">a</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">b</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">c</span>: <span class="hljs-number">3</span> }
<span class="hljs-keyword">let</span> { a, b } = obj 
<span class="hljs-built_in">console</span>.log(a, b)
</code></pre>
<h3 id="heading-named-parameter-in-javascript">Named Parameter in Javascript</h3>
<p>Using Object literals and destructuring we can implement Named Parameters in Javascript. You can avoid errors when calling the function without any arguments by assigning the object to the empty object, <code>{}</code>, even if you have default values set up.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> placeOrder = <span class="hljs-function">(<span class="hljs-params">{ 
    productId = <span class="hljs-string">'defaultId'</span>, 
    productName = <span class="hljs-string">'defaultProductName'</span>,
    sellerName = <span class="hljs-string">'defaultSellerName'</span>
    } = {}</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Order Placed -&gt;"</span>, productId, productName, sellerName);
}
placeOrder({ 
    <span class="hljs-attr">productId</span>: <span class="hljs-string">"1"</span>, 
    <span class="hljs-attr">productName</span>: <span class="hljs-string">"computer"</span>, 
    <span class="hljs-attr">sellerName</span>: <span class="hljs-string">"Amazon"</span> 
})
<span class="hljs-comment">// Order Placed -&gt; 1 computer Amazon</span>

placeOrder({ 
    <span class="hljs-attr">productId</span>: <span class="hljs-string">"2"</span>, 
    <span class="hljs-attr">productName</span>: <span class="hljs-string">"mobile"</span>
})
<span class="hljs-comment">// Order Placed -&gt; 2 mobile defaultSellerName</span>

placeOrder()
<span class="hljs-comment">// Order Placed -&gt; defaultId defaultProductName defaultSellerName</span>
</code></pre>
<p>Named parameters, by default, are <strong>optional</strong>. But you can easily make them required by validating parameters before executing the function.</p>
<p>Hope this helps! Let me know if you have any other questions.</p>
<h3 id="heading-resources">Resources</h3>
<ol>
<li><p><a target="_blank" href="https://en.wikipedia.org/wiki/Named_parameter">https://en.wikipedia.org/wiki/Named_parameter</a></p>
</li>
<li><p><a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/named-and-optional-arguments">https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/named-and-optional-arguments</a></p>
</li>
<li><p><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment</a></p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Microservices Design Pattern]]></title><description><![CDATA[Proxy Server Pattern is one of the Design Patterns in Microservices Architecture Where one server acts as a dedicated proxy server for the outside world to all microservices.
Architecture Design

In This pattern, All Services (A, B, C, and D) can be ...]]></description><link>https://blog.rsaw409.me/microservices-design-pattern</link><guid isPermaLink="true">https://blog.rsaw409.me/microservices-design-pattern</guid><category><![CDATA[Microservices]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[Express.js]]></category><category><![CDATA[design patterns]]></category><category><![CDATA[Proxy Server]]></category><dc:creator><![CDATA[Rohit Saw]]></dc:creator><pubDate>Sat, 22 Jul 2023 16:07:41 GMT</pubDate><content:encoded><![CDATA[<p>Proxy Server Pattern is one of the Design Patterns in Microservices Architecture Where one server acts as a dedicated proxy server for the outside world to all microservices.</p>
<h2 id="heading-architecture-design">Architecture Design</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1690036657924/00b93f84-2a9f-4622-9553-e286efe19458.png" alt class="image--center mx-auto" /></p>
<p>In This pattern, All Services (A, B, C, and D) can be secured behind a firewall and accessed only by Our Proxy Server. Frontend only needs to call a single service (Proxy Server) for all requests and Proxy Server takes care of calling the correct service for frontend. to All Microservices can still communicate through Synchronized and Asynchronized Messaging Tools if needed.</p>
<h2 id="heading-implementation-in-nodejs">Implementation in Node.js</h2>
<p>We can use any HTTP client library also for implementing our proxy server. Here we are going to use the <a target="_blank" href="https://www.npmjs.com/package/http-proxy">http-proxy</a> npm package for implementing our proxy server because of its inbuilt capability for handling proxies request.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> httpProxy <span class="hljs-keyword">from</span> <span class="hljs-string">"http-proxy"</span>;

<span class="hljs-keyword">const</span> proxyServer = httpProxy.createProxyServer();

proxyServer.on(<span class="hljs-string">"proxyReq"</span>, <span class="hljs-function">(<span class="hljs-params">proxyReq,req,res,options</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> body = req.body;
    <span class="hljs-keyword">if</span> (!body) <span class="hljs-keyword">return</span> ;

    <span class="hljs-keyword">const</span> contentType = proxyReq.getHeader(<span class="hljs-string">"Content-Type"</span>);
    <span class="hljs-keyword">if</span> (contentType){
        <span class="hljs-keyword">const</span> bodyData = <span class="hljs-built_in">JSON</span>.stringify(body)
        proxyReq.setHeader(<span class="hljs-string">"Content-Length"</span>, Buffer.byteLength(bodyData);
        proxyReq.write(bodyData);
    }
})

<span class="hljs-keyword">const</span> handleRequest = <span class="hljs-function">(<span class="hljs-params">{ target }</span>) =&gt;</span> <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
    proxyServer.web(req, res, { target }, <span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
        <span class="hljs-keyword">return</span> res.status(<span class="hljs-number">503</span>).send({ <span class="hljs-attr">message</span> : error.message });
    });
}    
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> handleRequest;
</code></pre>
<p>Here Our <strong>handleRequest</strong> function returns the middleware function which we can use as a Request handler for incoming HTTP requests but before that let's create our index.js file for separating individual microservices API with some prefix in API.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> express <span class="hljs-keyword">from</span> <span class="hljs-string">"express"</span>;
<span class="hljs-keyword">import</span> serviceARoutes <span class="hljs-keyword">from</span> <span class="hljs-string">"serviceARoutes.js"</span>;
<span class="hljs-keyword">import</span> serviceBRoutes <span class="hljs-keyword">from</span> <span class="hljs-string">"serviceBRoutes.js"</span>;
<span class="hljs-keyword">import</span> serviceCRoutes <span class="hljs-keyword">from</span> <span class="hljs-string">"serviceCRoutes.js"</span>;
<span class="hljs-keyword">import</span> serviceDRoutes <span class="hljs-keyword">from</span> <span class="hljs-string">"serviceDRoutes.js"</span>;

<span class="hljs-keyword">const</span> app = express();

app.use(<span class="hljs-string">"/serviceA"</span>, serviceARoutes);
app.use(<span class="hljs-string">"/serviceB"</span>, serviceBRoutes);
app.use(<span class="hljs-string">"/serviceC"</span>, serviceCRoutes);
app.use(<span class="hljs-string">"/serviceD"</span>, serviceDRoutes);

app.listen(<span class="hljs-number">3000</span>)
</code></pre>
<p>Now suppose our microservices are deployed in some cloud provider with the following address.</p>
<p>Proxy Server -&gt; https://proxy-service.com</p>
<p>Service A -&gt; https://serviceA.com</p>
<p>Service B -&gt; https://serviceB.com</p>
<p>Service C -&gt; https://serviceC.com</p>
<p>Service D -&gt; https://serviceD.com</p>
<p>Now let's create a route file for Service A, Similar file can be created also for other services with API which you want to expose, and make sure these API is available in the respective microservice.</p>
<p>Now our handler just transfers the request to provided target option and returns the same response to the Frontend it receives from that target microservice.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> express <span class="hljs-keyword">from</span> <span class="hljs-string">"express"</span>;

<span class="hljs-keyword">const</span> router = express.Router();

router.get(<span class="hljs-string">"/someApi"</span>, handleRequest(
    { <span class="hljs-attr">target</span> : <span class="hljs-string">'https://serviceA.com'</span>}
));
router.post(<span class="hljs-string">"/someOtherApi"</span>, handleRequest(
    { <span class="hljs-attr">target</span> : <span class="hljs-string">'https://serviceA.com'</span>}
));

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> router;
</code></pre>
<p>So Now Frontend can access Api from all services using only the proxy server instead of calling individuals service as shown below</p>
<p><code>https://proxy-service.com/serviceA/&lt;api&gt; instead of https://serviceA.com/&lt;api&gt;</code></p>
<p><code>https://proxy-service.com/serviceB/&lt;api&gt; instead of https://serviceB.com/&lt;api&gt;</code></p>
<p>Hope this helps! Let me know if you have any other questions.</p>
<h3 id="heading-sources">Sources</h3>
<ol>
<li><p><a target="_blank" href="https://www.npmjs.com/package/http-proxy">https://www.npmjs.com/package/http-proxy</a></p>
</li>
<li><p><a target="_blank" href="https://www.npmjs.com/package/http-proxy-middleware">https://www.npmjs.com/package/http-proxy-middleware</a></p>
</li>
<li><p><a target="_blank" href="https://www.tutorialspoint.com/microservices_design_patterns/microservices_design_patterns_proxy.htm">https://www.tutorialspoint.com/microservices_design_patterns/microservices_design_patterns_proxy.htm</a></p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[MineSweeper in React.js using BFS]]></title><description><![CDATA[Introduction
Have you ever heard of minesweeper? It is a little classic game that debuted back in 1990 as part of Windows Entertainment.
The rules are simple. There is an N X N board in which some of the squares have bombs you have to find all Square...]]></description><link>https://blog.rsaw409.me/minesweeper-in-reactjs-using-bfs</link><guid isPermaLink="true">https://blog.rsaw409.me/minesweeper-in-reactjs-using-bfs</guid><category><![CDATA[React]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[algorithm]]></category><category><![CDATA[BFS]]></category><category><![CDATA[projects]]></category><dc:creator><![CDATA[Rohit Saw]]></dc:creator><pubDate>Sat, 04 Mar 2023 08:19:05 GMT</pubDate><content:encoded><![CDATA[<h3 id="heading-introduction">Introduction</h3>
<p>Have you ever heard of minesweeper? It is a little classic game that debuted back in 1990 as part of Windows Entertainment.</p>
<p>The rules are simple. There is an N X N board in which some of the squares have bombs you have to find all Square which does not have bombs and you have to mark all bombs correctly. A square in the board can either be a bomb or a numerical value representing the number of bombs adjacent to it.</p>
<p>Eg – If a square has 2. It means there are 2 bombs out of 8 adjacent squares. If Square have 0 values means that its adjacent have no bombs and all adjacent will become visible with their values</p>
<p>If you haven’t played this game, you can give it a try with google minesweeper <a target="_blank" href="https://g.co/kgs/hkJDz7">Here</a> to get an idea of this classic game.</p>
<p>After playing this game I realized that This game is nothing but a good example of the famous graph traversal algorithm Breadth-first search (BFS). This game logic can be made with BFS Algorithm.</p>
<p>Here is a very simple version of this game that we are going to build with React.js</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1677916392856/3e599eba-d96e-46be-af78-fada55840e4b.jpeg" alt class="image--center mx-auto" /></p>
<p>The game is over as soon as you click on any bomb.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1677916427967/44bb9195-dac1-452a-83a4-7a22e3da5c5a.jpeg" alt class="image--center mx-auto" /></p>
<h3 id="heading-generating-board">Generating Board</h3>
<p>Here we are considering an 8X8 board with the number of mines that we can manage for the game difficulties level. For generating the board, we need to take care of a few things</p>
<ul>
<li><p>The random distributions of the bomb in some of the squares of the board, so some square contains mines.</p>
</li>
<li><p>If Square has no bomb then populate its value with the count of its nearby bombs.</p>
</li>
</ul>
<p>Below codeSnap contains one way of doing this, where each square contains id, value, and two Boolean to indicate its state (isVisible, isFlag).</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1677916583546/7545b126-827b-446c-a883-8447b5255e67.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-component">Component</h3>
<ul>
<li>Square - The building block of this game is Each Square which can contain either a bomb, flag, or numerical value indicating the total number of nearby bombs. Two event handlers for left click and right click we are passing in props to handle the event properly. Left click to show value and right click to mark with the flag for a potential bomb.</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1677916803330/46ae340b-8a2d-4435-99a1-67440d7d9b12.png" alt class="image--center mx-auto" /></p>
<ul>
<li>Board -  The main component of this game that holds all Individual Square as well as all logic of the game. Here we are using two state variables with useState (board, &amp; noOfBombs). Also, we are using react useEffect to set the newly generated Board whenever noOf bombs change by the user. Second useEffect is used here to handle the wrong move by the user which leads to Game Over or if there are no mines left on the board then the user wins this game and the board is reset., And two functions Related to handling clicks.</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1677917042729/2d015d6e-6a72-49d0-9e43-c8b40a947e53.png" alt class="image--center mx-auto" /></p>
<p>The right-click is used to mark the current Square with a flag, and the Click is doing a BFS search from the current Square if it has no bomb and makes all Adjacent Square visible which has no bombs nearby. "tmp" Array is used here to mark the visited square.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1677917179773/6bed21c9-ca71-4c27-9098-c6f4ca1343fd.png" alt class="image--center mx-auto" /></p>
<p>And At last, we are returning the board with some minor styling and Now we only need to render this Board Component in React App that we are doing here.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1677917244930/26f9bb22-93aa-4abd-9f8a-657bd8bd680f.png" alt class="image--center mx-auto" /></p>
<p>Now We Can Run Our React App to see this Game in Action. The full Code can be found in below GitHub Repository.</p>
<h1 id="heading-edit">Edit-</h1>
<p>Here is the live clone of the google minesweeper game.</p>
<p><a target="_blank" href="https://minesweeper-60xh.onrender.com/">Click Here!</a></p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://github.com/rohitsaw/Mini-Game">https://github.com/rohitsaw/Mini-Game</a></div>
]]></content:encoded></item></channel></rss>