<?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 Yash on Medium]]></title>
        <description><![CDATA[Stories by Yash on Medium]]></description>
        <link>https://medium.com/@239yash?source=rss-b471f8e51704------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*pRTOIhm6itJ-KZOnnGIgYQ.jpeg</url>
            <title>Stories by Yash on Medium</title>
            <link>https://medium.com/@239yash?source=rss-b471f8e51704------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 15:38:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@239yash/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[Building resiliency in spring boot applications in case of dependency failures — Implementing…]]></title>
            <link>https://medium.com/@239yash/building-resiliency-in-spring-boot-applications-in-case-of-dependency-failures-implementing-e9152d406c82?source=rss-b471f8e51704------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9152d406c82</guid>
            <category><![CDATA[circuit-breaker]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[resilience]]></category>
            <category><![CDATA[resilience4j]]></category>
            <category><![CDATA[spring]]></category>
            <dc:creator><![CDATA[Yash]]></dc:creator>
            <pubDate>Fri, 24 Nov 2023 02:14:26 GMT</pubDate>
            <atom:updated>2023-11-25T11:04:57.183Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building resiliency in spring boot applications in case of dependency failures — Implementing Circuit Breaker (Resilience4j)🚀</h3><h3>Problem Statement:</h3><p>Recently, I built a flow in my spring boot application in which I was taking some input from Users via an API and posting that data to a third-party vendor by calling their outbound API. Flow was very simple and straightforward, the front end will call my API and I will pass that data directly to that third party using their API.</p><p><strong>It&#39;s pretty much simple. Now, What happened?</strong><br>After deploying the changes, after a few days, I got to know that data was not getting passed to that third party. And, I was like how? It was an effortless flow.</p><p><strong>What happened -&gt;</strong> The service of that third-party vendor went down due to some issues. And I was like, I do not have the data to reflow it. I started storing failed data in a database. In case it fails again, We can reflow the failed cases. I implemented the same and everything was working fine. After some days, I got to know that their services started failing again. I was like how? What happened -&gt; They faced downtime in peak hours due to some issues at their end but end users tried to submit the data repeatedly, which caused a thundering herd issue at their end. They tried to recover but because of overload, They couldn&#39;t recover fast. Yet, Another problem to solve!</p><p>Here comes the <strong>Circuit Breaker</strong> in the picture. We got on to a solution, If the vendor’s service goes down. I will stop calling their API for some time and store the form data in a database created during downtime. After, the vendor’s Service is up. I will reflow the failed forms data.</p><blockquote><a href="https://resilience4j.readme.io/docs/circuitbreaker"><strong>Resilience4j</strong></a> — Resilience4j is a lightweight fault tolerance library inspired by Netflix Hystrix, but designed for functional programming.</blockquote><p>We are going to use Circuit Breaker from Resilience4j and will be implementing this with Spring Boot/Java.</p><h3>General Working:</h3><p>Initially, the circuit breaker is always in the <strong>CLOSED</strong> state. Circuit Breaker triggers the circuit <strong>OPEN</strong> when it encounters repetitive failures from that third party. When the circuit is <strong>OPEN</strong>, No calls are made to the failing third party. After some time, the Circuit moves to the <strong>HALF_OPEN</strong> state, To check whether our third party(some function/API call) is working fine by allowing a few calls to it. If those calls are successful, the Circuit moves to state <strong>CLOSED</strong> otherwise it moves back to <strong>OPEN</strong> again and the same process is repeated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/0*Vy0WgkLRT8DbmONh.jpg" /><figcaption>Image Credits — resilience4j docs</figcaption></figure><p>Let’s go towards the implementation directly — <br>I have created a spring boot project using a <a href="https://start.spring.io/">spring initializer</a>. This is what my project structure looks like 👇🏽👇🏽</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*F4YdZT0yBJPPMzPuejWxSg.png" /><figcaption>Folder Structure</figcaption></figure><p>You can see, that I have created a few general packages like config, controllers, services, and custom exceptions.</p><h3>Code:</h3><p>We have created a config class for creating a Circuit Breaker instance initially when our applications spin up for the first time. As you can see, there is a [@]<strong>Bean</strong> annotation applied on a method named createCircuitBreakerInstance, This method creates a circuit breaker instance and stores it in our class variable. Now, You can see some parameters that I have configured while creating my instance like <strong>failureRateThreshold</strong>(% value), <strong>minimumNumberOfCalls</strong>(minimum number of calls required for initiating the work of our circuit breaker), and much more. You can specify the number of calls to be made in the <strong>HALF_OPEN</strong> state, and how you want the transition to the <strong>HALF_OPEN</strong> state(Manual/Auto). In the <strong>recordExceptions</strong> parameter, I have added our custom exception which is to be captured. You can read about these parameters <a href="https://resilience4j.readme.io/v1.7.0/docs/circuitbreaker#create-and-configure-a-circuitbreaker">here</a>. I have created a public get method too, for fetching the instance anywhere in my code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc253f61168075aee5c75774e70e76d1/href">https://medium.com/media/dc253f61168075aee5c75774e70e76d1/href</a></iframe><p>Time to create an API Controller that consists of a simple endpoint.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf8cb2441df1c68738810bee9ef5043d/href">https://medium.com/media/cf8cb2441df1c68738810bee9ef5043d/href</a></iframe><p>Now, our very own custom exception TestException, will be recorded by our circuit breaker instance.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d80b4ca8ecaadeab5d4eb4e039544d6/href">https://medium.com/media/9d80b4ca8ecaadeab5d4eb4e039544d6/href</a></iframe><p>Time to create our service class. The method named thirdPartyServiceCall always throws our custom exception just for testing purposes. I have created a counter variable too for counting the number of calls made to our service method testMethod.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e09ac26103fb528d97d0abe05595b21/href">https://medium.com/media/1e09ac26103fb528d97d0abe05595b21/href</a></iframe><h3>Testing:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vFmFIzUvSx__8SoXxx2NpQ.png" /><figcaption>Logs printed</figcaption></figure><p>As you can see when I started hitting the API, Logs started printing up in our console. So, Initially, the circuit breaker was in the <strong>CLOSED</strong> state. When the failure threshold was crossed, It moved to the OPEN state. Then after some time, it moved to the <strong>HALF_OPEN</strong> state, tried a few calls to the third-party method and after recording failures again, It moved to the <strong>OPEN</strong> state. If the calls made in the <strong>HALF_OPEN</strong> state were to be successful then the circuit breaker would have moved to the <strong>CLOSED</strong> state.</p><h3>UseCases:</h3><ol><li>Let’s say you want to store the failed cases data for reflow after some time, You can use a circuit breaker there.</li><li>You don&#39;t want to burden the third party’s system in case of failures, You can use a circuit breaker there.</li><li>The circuit breaker can be moved to the <strong>OPEN</strong> state <strong>manually</strong> by hitting hooks provided by resilience4j. So, Let’s say you need to close the calls to third-party methods according to your use case(Let’s say during peak hours or some other exercise). In that case, the circuit breaker will always be in an <strong>OPEN</strong> state only until you move it to the <strong>CLOSED</strong> state. You can read about those hooks <a href="https://resilience4j.readme.io/v1.7.0/docs/examples#transition-to-states-manually">here</a>.</li></ol><p>Lot’s of circuit things today 🤣🚀<br>Thanks for visiting this page!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9152d406c82" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to create custom annotations in SpringBoot for validating data ]]></title>
            <link>https://medium.com/@239yash/how-to-create-custom-annotations-in-springboot-for-validating-data-5ae765d2b001?source=rss-b471f8e51704------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ae765d2b001</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[validation]]></category>
            <category><![CDATA[exception-handling]]></category>
            <category><![CDATA[annotations]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Yash]]></dc:creator>
            <pubDate>Wed, 05 Apr 2023 20:49:44 GMT</pubDate>
            <atom:updated>2023-04-05T20:49:44.851Z</atom:updated>
            <content:encoded><![CDATA[<p>In large Spring Boot projects when we are dealing with a lot of incoming data then validating that data is quite a challenge and a huge payload for developers. Bad data can obviously break things! Why validate data?</p><p>Let’s say we have many incoming DTOs and in all of those DTOs we have fields of a similar type such as Emails, Mobile Numbers, URLs, and Date of Birth. In all these fields, data should be in the correct format else things will not work. For example — The date of Birth can be in the format <strong>23/01/1999</strong> but it cannot be in the format <strong>23/13/19999</strong>, This is wrong. Hence validating such data is utmost required! How to validate data?</p><p>One simple approach is whenever we get this data, We’ll call some generic function passing these fields. That function will validate data according to our logic. One more approach is to use <strong>Annotations 💥. </strong>You might have seen some variables with <strong>@</strong> prefixed before them. Using annotations is quite a clean way to validate data fields. What is Java Annotation?</p><h3>Java Annotations</h3><p>In Java SE 5, annotations were added as a type of syntactic metadata that could be added to program constructions. Annotations can be handled at compile time and don’t directly affect how the code works. Annotations have a number of uses, among them:</p><p><strong>Information for the compiler</strong> — Annotations can be used by the compiler to detect errors or suppress warnings.<br><strong>Compile-time and deployment-time processing</strong> — Software tools can process annotation information to generate code, XML files, and so forth.<br><strong>Runtime processing</strong> — Some annotations are available to be examined at runtime.</p><h3>Validating a field that contains only URLs</h3><p>In this article, we will be creating a custom annotation for validating our incoming data. Our custom annotation will validate a field that can only have URLs. For example —</p><p><a href="https://medium.com/@239yash">https://medium.com/@239yash</a> — Valid URL<br><a href="https://medium.com/@239yash">https://medium/@239yash</a> — Invalid URL</p><p>Let’s start!”<br>I have created a spring boot project using <a href="https://start.spring.io/">spring initializer</a>. This is what my project structure looks like 👇🏽👇🏽</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LNisoX4y0Bei2Z7EYUyNbw.png" /><figcaption>Project Structure</figcaption></figure><p>You can see, I made a package named annotations. In this package, I have implemented the logic for my annotations. Then, I am having a package for controllers and right after that, I am having a package for exception handlers for handling the error thrown when invalid data is caught! Let’s dig deep into the classes and files.</p><pre>package com.demoapp.customannotations.annotations;<br><br>import jakarta.validation.Constraint;<br>import jakarta.validation.Payload;<br>import java.lang.annotation.ElementType;<br>import java.lang.annotation.Retention;<br>import java.lang.annotation.RetentionPolicy;<br>import java.lang.annotation.Target;<br><br>// Declaring an annotation for validating URLs<br>// Retention is the time period<br>// Till what time you want your annotation to work around.<br>@Retention(RetentionPolicy.RUNTIME)<br><br>// Target gives you that on what instance you can use this annotation<br>@Target(ElementType.FIELD)<br><br>// Defined the constraint and the Validator Class!<br>@Constraint(validatedBy = UrlValidatorImpl.class)<br><br>public @interface UrlValidatorAnnotation {<br><br>    // Error message which would be sent, You can set default value<br>    String message() default &quot;Invalid Url Entered!&quot;;<br><br>    // Group of constraints<br>    Class&lt;?&gt;[] groups() default {};<br><br>    Class&lt;? extends Payload&gt;[] payload() default {};<br>}</pre><p>The above code is for declaring the annotation named as UrlValidatorAnnotation.</p><pre>package com.demoapp.customannotations.annotations;<br><br>import jakarta.validation.ConstraintValidator;<br>import jakarta.validation.ConstraintValidatorContext;<br>import java.net.MalformedURLException;<br>import java.net.URISyntaxException;<br>import java.net.URL;<br><br>public class UrlValidatorImpl implements<br>        ConstraintValidator&lt;UrlValidatorAnnotation, String&gt; {<br><br>    @Override<br>    public boolean isValid(String url, <br>                           ConstraintValidatorContext constraintValidatorContext) {<br>        try {<br>            new URL(url).toURI();<br>            return true;<br>        } catch (MalformedURLException | URISyntaxException e) {<br>            return false;<br>        }<br>    }<br>}</pre><p>The above code is the implementation of the Validator class, We have overridden the isValid function which will tell us whether the given URL is valid or not. I have used <strong>java.net.URL</strong> for validation purposes.</p><pre>package com.demoapp.customannotations.exceptions;<br><br>import org.springframework.context.support.DefaultMessageSourceResolvable;<br>import org.springframework.http.HttpStatus;<br>import org.springframework.http.ResponseEntity;<br>import org.springframework.web.bind.MethodArgumentNotValidException;<br>import org.springframework.web.bind.annotation.ControllerAdvice;<br>import org.springframework.web.bind.annotation.ExceptionHandler;<br>import org.springframework.web.bind.annotation.ResponseBody;<br>import java.util.List;<br><br>@ControllerAdvice<br>public class CustomExceptionHandler {<br>    @ExceptionHandler(MethodArgumentNotValidException.class)<br>    @ResponseBody<br>    public ResponseEntity&lt;List&lt;String&gt;&gt; processUnmergeException(<br>            final MethodArgumentNotValidException ex) {<br><br>        List&lt;String&gt; list = ex.getBindingResult().getAllErrors().stream()<br>                .map(DefaultMessageSourceResolvable::getDefaultMessage)<br>                .toList();<br><br>        return new ResponseEntity&lt;&gt;(list, HttpStatus.BAD_REQUEST);<br>    }<br>}</pre><p>Above code is for Exception handling where we are going to throw BAD_REQUEST if the input URL is not correct.</p><pre>package com.demoapp.customannotations.controllers;<br><br>import com.demoapp.customannotations.annotations.UrlValidatorAnnotation;<br>import jakarta.validation.Valid;<br>import lombok.AllArgsConstructor;<br>import lombok.Getter;<br>import lombok.Setter;<br>import org.springframework.web.bind.annotation.GetMapping;<br>import org.springframework.web.bind.annotation.RequestBody;<br>import org.springframework.web.bind.annotation.RequestMapping;<br>import org.springframework.web.bind.annotation.RestController;<br><br>@AllArgsConstructor<br>@RestController<br>@RequestMapping(&quot;/annotation&quot;)<br>public class TestController {<br><br>// Class for Request DTO which have annotated field.<br>    @Getter<br>    @Setter<br>    @AllArgsConstructor<br>    public static class RequestDto {<br>        @UrlValidatorAnnotation()<br>        private String url;<br>        private String name;<br>    }<br><br>    @GetMapping(&quot;/test&quot;)<br>    public String testAnnotation(@Valid @RequestBody RequestDto dto) {<br>        return &quot;I am done testing annotation with url - &quot; + dto.getUrl();<br>    }<br>}</pre><p>At last, I have created a Controller class for implementing a controller that can intake data in the request body and can process it. You can see that I have introduced one more class named as <strong>RequestDto</strong> which has some fields. There is one field named as <strong>url</strong> and I have annotated that field with our custom annotation. Now, In our controller, we have used <strong>Valid</strong> annotation which is going to help us in applying all other annotations which are used in our <strong>RequestDto</strong> class.</p><p>Now, Let’s try our App in action, and here are the results —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ri5nUnZJKm5dRc2CPpilKg.png" /><figcaption>Success Case</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tdDKVh4StDsV42-XoCVi7g.png" /><figcaption>Error case!</figcaption></figure><h3>Conclusion</h3><p>In this article, we have seen how we can create our own custom annotations for validating data and other broad use cases.</p><p>Thanks for visiting this page!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ae765d2b001" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Snappy data compression in NodeJs]]></title>
            <link>https://medium.com/@239yash/snappy-data-compression-in-nodejs-2701f6f399ae?source=rss-b471f8e51704------2</link>
            <guid isPermaLink="false">https://medium.com/p/2701f6f399ae</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[snappy]]></category>
            <category><![CDATA[compression]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[blob]]></category>
            <dc:creator><![CDATA[Yash]]></dc:creator>
            <pubDate>Mon, 03 Apr 2023 03:34:20 GMT</pubDate>
            <atom:updated>2023-04-03T03:34:20.775Z</atom:updated>
            <content:encoded><![CDATA[<p>Compression of data is always required when we are dealing with large data sets. Why?</p><p>Let’s say we are transmitting huge chunks of data over the internet from a database to our front-end clients. Whenever we are transmitting data, That is quite a slow process as we are passing it in the form of streams. You can read more about data messages and packets. Now, the Larger the size of the data more time it will take to get successfully transmitted and the problem is we don’t want to wait that much. The solution is Data Compression.</p><h3>What is Data Compression?</h3><p>A decrease in the number of bits required to represent data is known as data compression. Data compression can reduce network bandwidth and storage hardware expenses while accelerating file transfers and preserving store capacity. Text compression can be as simple as removing all repetitive strings, inserting a single repeat character to indicate a string of repeated characters, and substituting a smaller bit string for a frequently occurring bit string. Software that does compression utilizes an algorithm or formula to decide how to reduce the amount of the data.</p><h3>Snappy Data Compression?</h3><p>Snappy is a library for compression and decompression. It focuses on extremely fast speeds and moderate compression rather than maximal compression or compatibility with any other compression library. It is free &amp; Google is licensed under a BSD-type license.</p><h3>Why Snappy?</h3><p>It can compress data @ about 250 MB/sec (or higher). It has handled petabytes of data at Google. Snappy compression is a dictionary-in-data sliding-window compression algorithm, meaning that it does not store its dictionary separately from the compressed data stream, but rather uses back-references to indicate repeated data sequences.</p><p>In this article, we will go over how to implement Snappy compression on data in Node.Js applications. We will be using <a href="https://www.npmjs.com/package/snappy">https://www.npmjs.com/package/snappy</a> for our demo application. I have used one more package to get the byte size of the data — <a href="https://www.npmjs.com/package/node-blob">https://www.npmjs.com/package/node-blob</a></p><h3>Let’s jump on to code -</h3><pre>npm init<br>npm install express snappy node-blob</pre><pre>const express = require(&quot;express&quot;);<br>const snappy = require(&quot;snappy&quot;);<br>const Blob = require(&#39;node-blob&#39;);<br><br>// I have made a testData.js file, In this file I am storing dummy test data.<br>// This data is in the format of array of Javascript objects. Something around 1 lakh lines.<br>const testData = require(&quot;./testData&quot;);<br><br>const app = express();<br>const port = 3000;<br><br>// Function for calculating the byte size of data.<br>const testDataSizeCalculator = async () =&gt; {<br>    try {<br><br>        // Creating Blob to get the byte size of test data<br>        const buffer = new Blob([JSON.stringify(testData)]);<br>        console.log(&quot;Size of UnCompressed test Data in Bytes - &quot; + buffer.size);<br><br>    } catch(err) {<br>        console.log(err);<br>    }<br>}<br><br>// Function for compression &amp; UnCompression.<br>const compressData = async () =&gt; {<br>    try {<br><br>        // Compress the data<br>        const compressed = await snappy.compressSync(JSON.stringify(testData));<br>        console.log(&quot;Size of Compressed Data in Bytes - &quot; + compressed.byteLength);<br><br>        // Uncompress the data<br>        const unCompressedData = await snappy.uncompressSync(compressed);<br>        console.log(&quot;Size after Uncompression is done on Compressed Data in Bytes - &quot; + unCompressedData.byteLength);<br><br>    } catch(err) {<br>        console.log(err);<br>    }<br>}<br><br>// Testing endpoint such that we can test on API hit!<br>app.get(&quot;/test&quot;, async (req, res) =&gt; {<br><br>    // Checking the byte size of test data<br>    testDataSizeCalculator();<br><br>    // Checking the byte size of compressed data<br>    compressData();<br><br>    res.status(200).send(&quot;done!&quot;);<br>});</pre><h3>Output:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l23dz3SESa_XGXWfkLysZg.png" /><figcaption>Output in terminal</figcaption></figure><h3>UseCases?</h3><p>We can keep this compressed data in our Redis cache as Redis can store such data. On ingestion, You can compress the data and on fetch, you can UnCompress the data. When we are communicating with different services and data is being sent over, Instead of sending raw data we can compress the data for much faster transmission.</p><h3>Credits:</h3><p><a href="https://github.com/Brooooooklyn/snappy">GitHub - Brooooooklyn/snappy: Fastest Snappy compression library in Node.js</a></p><h3>Conclusion:</h3><p>In this article, we have seen how snappy can reduce the size of data to a great extent and in a much faster way.<br>Thanks for visiting this page!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2701f6f399ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reducing Docker image build time by Caching Node modules, and using a multi-stage build process.]]></title>
            <link>https://medium.com/@239yash/reducing-docker-image-build-time-by-caching-node-modules-and-using-a-multi-stage-build-process-f5d84e196346?source=rss-b471f8e51704------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5d84e196346</guid>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[dockerfiles]]></category>
            <category><![CDATA[multi-stage-builds]]></category>
            <dc:creator><![CDATA[Yash]]></dc:creator>
            <pubDate>Mon, 20 Mar 2023 02:56:25 GMT</pubDate>
            <atom:updated>2024-03-17T13:51:37.616Z</atom:updated>
            <content:encoded><![CDATA[<p>Nowadays, We are using <a href="https://docs.docker.com/"><strong>Docker</strong></a> every day to build and deploy our applications. Docker image build time is already optimized but can we optimize it further? <strong>Yes, We can.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1eUfz4me0lGDFWLu.png" /></figure><p><strong>Let’s consider a simple Docker file first -</strong></p><pre>FROM node:lts-alpine<br>WORKDIR /app<br>COPY package.json ./<br>RUN npm install<br>COPY . .<br>EXPOSE 3000<br>CMD [&quot;npm&quot;, &quot;start&quot;]</pre><p><strong>The command for building up the Docker file -</strong></p><pre># -t is used for tagging the image.<br># Using a dot(.) in the end specifies the path of the Dockerfile.<br><br>docker build -t my-app .</pre><p>When we build this image. Let’s say it takes 2 minutes to build. Once the image is built, Let’s try rebuilding this image again. What we can notice — That now it does not take that much time. Now it is built in only a few seconds only. Why? Docker uses some sort of caching. If anything changes in your repository. For example — You have changed some code in your files. Docker will invalidate that cache and will start the build process from scratch, Again it will take minutes to build. Previously, We didn’t make any changes to the repository, That’s why the cache was in action and the image was built in seconds only for the second time.</p><h3>Problem Statement -</h3><p>There is one more thing that got noticed every single time after edits in our repository when we build our Docker image, the <strong>npm install</strong> command is executed and our node modules are installed again and again. However, we haven’t made any changes in the <strong>package.json</strong> files. The installation of dependencies is a very slow process and we don’t want this process to be executed every time we are building our Docker images as we haven’t made any changes in the <strong>package.json</strong> files.</p><p>Now, The question is how we can curb this time. The answer is to apply <strong>caching of node modules by using multi-stage builds</strong> in our Docker image.</p><h3>Approach -</h3><p>In multi-stage builds. The first stage will be installing our dependencies, and setting up work directories, and our second stage is going to run our application by importing code in the Docker environment. If you make changes in your code, The cache of the first stage will remain intact and can be reused. In this way, while building we can save the execution time of the first stage process i.e. — Installation of dependencies. If we change something in our package.json then obviously the whole image will be built from scratch.</p><h3>Implementation -</h3><pre># First Stage<br>FROM node:10.14.0 AS installer<br>WORKDIR /app<br><br># Copying package.json &amp; package-lock.json.<br># Why we have used * symbol? Check this -&gt; https://docs.docker.com/engine/reference/builder/#copy<br>COPY package*.json .<br><br># Running npm install now. As you can in this stage we only copied package.json &amp; package-lock.json files<br>RUN npm install<br><br># Second Stage<br># Using Alpine images to curb down the image size<br>FROM node:lts-alpine as release<br><br>WORKDIR /app<br><br># Copying all the contents from previous stage(used - - from) into current stage<br>COPY --from=installer /app /app<br><br># Copying all the repo content into our Docker environment<br>COPY . .<br><br># Triggering the start command to run the application<br>CMD [&#39;npm&#39;, &#39;start&#39;]</pre><p>When we start building this image. It will take a few minutes to get built. Now, For testing let’s make some code-level changes in our repository. Triggering the build command again. What happened? It got built in seconds only because we are using the multi-stage building and caching the dependencies installation in our first stage only. Moreover to reduce the image size, use the docker ignore(.<strong>dockerignore</strong>) file too to avoid copying unnecessary content into your Docker environment.</p><h3>Conclusion -</h3><p>We reduced our Docker image build time by caching Node modules, using a multi-stage build process.</p><p>Thanks for Visiting this page!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5d84e196346" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to implement Redis pipelining in Node.Js using ioredis]]></title>
            <link>https://medium.com/@239yash/how-to-implement-redis-pipelining-in-node-js-using-ioredis-ba3eab32f1a7?source=rss-b471f8e51704------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba3eab32f1a7</guid>
            <category><![CDATA[node]]></category>
            <category><![CDATA[pipeling]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[ioredis]]></category>
            <category><![CDATA[redis]]></category>
            <dc:creator><![CDATA[Yash]]></dc:creator>
            <pubDate>Wed, 15 Mar 2023 20:00:33 GMT</pubDate>
            <atom:updated>2023-03-16T06:18:20.509Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi, This article goes over how to implement pipelining in Redis using ioredis in Node.Js</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/0*uEcxiTFcMBG5GwkF" /></figure><p>We all know Redis is used as an in-memory cache. Why caching?<br>Sometimes our use case is fetching some piece of data again and again from our databases or some other data factory. We know that database operations are costly and quite slow when the data set is very large. So, what we do is we create a layer over our databases, <strong>Caching layer</strong>. This layer serves as a temporary storage for data and it is lightning-fast in nature. Redis serves us as this caching layer. If the data you’re looking for is present in your Redis cache, you don’t have to make a request to your database which means you save time and serve data faster to your client/front end. Redis stores data in key-value pair data structures.</p><p>For installing Redis on your machine, Please check out this — <a href="https://redis.io/docs/getting-started/installation/"><strong>https://redis.io/docs/getting-started/installation/</strong></a><br>Now, Once Redis is installed on your machine we need a Redis client through which our Node.Js application can connect to the Redis server. We&#39;ll be using <strong>ioredis — </strong><a href="https://www.npmjs.com/package/ioredis"><strong>https://www.npmjs.com/package/ioredis</strong></a></p><p>Installing ioredis on our machine —</p><pre>npm install ioredis</pre><h3><strong>Our problem statement —</strong></h3><ol><li>Let’s say we are generating a lot of data in form of key-value pairs in our applications which are to be used again in near future and will become invalid after a certain amount of time.</li><li>We want this data to be served lightning-fast to our clients or front end.</li></ol><h3>Approaches —</h3><ol><li><strong>Basic Approach — </strong><br>We can store these pairs in our SQL or no-SQL databases. The insert and fetch operations on databases are not that optimized. Database calls are quite costly, and slow too.</li><li><strong>Caching Approach — </strong><br>We can store these pairs in our Redis cache. The GET operations are very fast. Once the data is invalid, We’ll remove that pair from our Redis cache.</li></ol><p><strong>Now, the major issue is how to feed data to Redis. What we know is that we are generating data on a very high frequency. We can SET data in Redis sequentially. But why? Why SET data sequentially, Who needs to wait for the response from the data SET operation? We will use Redis pipelining here!</strong></p><p>Redis pipelining is a technique for improving performance by issuing multiple commands at once without waiting for the response to each individual command. Pipelining is supported by most Redis clients. This document describes the problem that pipelining is designed to solve and how pipelining works in Redis.</p><h3>Implementation for Redis pipelining —</h3><pre>// Configuring an Express app.<br>const express = require(&quot;express&quot;);<br>const Redis = require(&quot;ioredis&quot;);<br>const app = express();<br>const port = 3000;<br><br>// Setting up Redis config. There are many ways for connecting to Redis server.<br>// You can check this -&gt; https://github.com/luin/ioredis#connect-to-redis<br>const redis = new Redis({<br>    port: 6379, <br>    host: &quot;127.0.0.1&quot;, <br>    username: &quot;default&quot;, <br>    password: &quot;changeit&quot;,<br>    db: 1<br>});<br><br>// I have added 2 endpoints to show the differences how sequential commands<br>// works, And how the pipelining works in Redis<br>// run-sequential endpoint is triggering a for loop which sequentially<br>// executes 50,000 SET operations in Redis server.<br><br>app.get(&quot;/run-sequential&quot;, async (req, res) =&gt; {<br>    console.time(&quot;sequential time&quot;);<br>    for (let i = 0; i &lt; 50000; i++) {<br>        await setKeyFunction(&quot;foo&quot;, &quot;test-test&quot;)<br>    }<br>    console.timeEnd(&quot;sequential time&quot;);<br>    res.send(&quot;OK&quot;);<br>});<br><br>// run-pipeline endpoint is creating a pipeline object.<br>// In the for loop we are batching commands in that pipeline object.<br>// After for loop, We are executing the pipeling with 50,000 commands in it.<br><br>app.get(&quot;/run-pipeline&quot;, async (req, res) =&gt; {<br>    console.time(&quot;pipeline time&quot;);<br>    const pipeline = redis.pipeline();<br>    for (let i = 0; i &lt; 50000; i++) {<br>        pipeline.set(&quot;foo&quot;, &quot;test-test&quot;);<br>    }<br>    await pipeline.exec();<br>    console.timeEnd(&quot;pipeline time&quot;);<br>    res.send(&quot;OK&quot;);<br>});<br><br>// An async function for setting a key-value pair in Redis cache<br>const setKeyFunction = async (name, value) =&gt; {<br>    return await redis.set(name, value);<br>}<br><br>app.listen(port, () =&gt; {<br>    console.log(`Io-Redis pipelining demo app listening on port ${port}`);<br>});</pre><h3>Running the application by command —</h3><pre>nodemon index.js </pre><h3><strong>Result time —</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*Vm3pi5UfXMdb_IcxeJGecg.png" /><figcaption>Logs printed show time taken by sequential call &amp; Pipeling call</figcaption></figure><p>As we can see clearly — The pipeline process took something around 243 ms whereas the sequential process took something around 2.6 seconds. This is a huge difference.</p><h3><strong>In the article, What we have seen -</strong></h3><p>1. How Redis pipelining can save plenty of our time by executing multiple commands in a single go.<br>2. Pipelining is not just a way to reduce the latency cost associated with the round trip time, it actually greatly improves the number of operations you can perform per second in a given Redis server.</p><p><strong>Thanks for Visiting this page!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba3eab32f1a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Processing bulk MongoDB documents using batch cursors in Python using pymongo]]></title>
            <link>https://medium.com/@239yash/processing-bulk-mongodb-documents-using-batch-cursors-in-python-f6fe57fe01ba?source=rss-b471f8e51704------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6fe57fe01ba</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[pymongo]]></category>
            <category><![CDATA[batch]]></category>
            <category><![CDATA[cursor]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Yash]]></dc:creator>
            <pubDate>Thu, 02 Mar 2023 09:49:08 GMT</pubDate>
            <atom:updated>2023-03-02T09:50:39.191Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine you have 1 million documents in your MongoDB collection and you want to iterate over all of them one by one and perform some operations on those documents. For example — the document has the following fields in schema -&gt;<br><strong><em>1. userName<br>2. firstName<br>3. lastName<br>4. emailId<br>5. mobileNumber</em></strong></p><p>Let’s say you have to send emails to these users. The email address is kept in the <strong><em>emailId</em></strong> field and you have to inject the <strong><em>firstName</em></strong> &amp; <strong><em>lastName</em></strong> fields in your email templates. Now, How you will iterate on all of them?</p><p>We cannot import all 1 million documents in our code at runtime as this will freeze our code. 1 million is a lot. What we can do is import documents in batches such that calls to our MongoDB server are also fewer in number and our code, and memory can also handle a single batch of documents during execution. Here is the example code —</p><pre># We are using pymongo package here<br>import pymongo as pmg<br><br># Parameters required for fetching documents -<br><br># Projection - Why to import whole document, We&#39;ll import only required fields.<br>projection = {&quot;firstName&quot; : True, &quot;lastName&quot; : True, &quot;emailId&quot;: True, &quot;_id&quot; : False}<br># Query parameter, for different conditions.<br>query = {}<br># Database name<br>dbName = &#39;userDatabase&#39;<br># Collection name<br>collectionName = &#39;users&#39;<br># Enter your MongoDB cluster URL<br>mongoUrl = &quot;&quot;<br><br># Function to connect to our MongoDB Cluster<br>def mongoConnection():<br>    try:<br>     # Fetching client using pymongo<br>        client = pmg.MongoClient(mongoUrl)<br>        # Holding our database<br>        mydatabase = client[dbName]<br>        return mydatabase<br>    except Exception as e:<br>        print(&quot;Error occured while connecting to database!&quot;)<br>        return False<br><br>def iteratingFunction():<br>    try:<br>        db = mongoConnection()<br>        # Fetching the collection<br>        collection = db[collectionName]<br>        batch = collection.find(query = query, projection = projection, batch_size = 1000)<br>        <br>        for doc in batch:<br>         print(doc[&quot;emailId&quot;])<br><br>    except Exception as e:<br>     print(&quot;Error occured!&quot;)<br><br>iteratingFunction()</pre><p>Here, our batch size is 1000, If the query provided by us matches more than 1000 documents then once 1000 documents are processed in for loop, Our cursor will fetch another 1000 documents. For Example —</p><ol><li>Total of 9000 documents matching the query — So, a total of 9 calls will be there to DB.</li><li>Total of 5500 documents matching the query — So, a total of 6 calls will be there to DB, 5 calls with 1000 documents each, and 1 single call with the remaining 500 documents.</li></ol><p>Conclusion — <br>1. Using batch cursors, We can optimize our code where bulk fetch operations are executed.<br>2. Memory usage by code is very less, No need to import all the documents in a single call.<br>3. DB queries are highly optimized, with No extra load on our database.</p><p>Thanks for visiting this page!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6fe57fe01ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying React Applications using Docker in 2 ways — MultiStage builds, and Nginx.]]></title>
            <link>https://medium.com/@239yash/deploying-react-applications-using-docker-in-2-ways-multistage-builds-and-nginx-77e6e95417c3?source=rss-b471f8e51704------2</link>
            <guid isPermaLink="false">https://medium.com/p/77e6e95417c3</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[dockerfiles]]></category>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[multi-stage-dockerfile]]></category>
            <dc:creator><![CDATA[Yash]]></dc:creator>
            <pubDate>Thu, 02 Mar 2023 02:39:08 GMT</pubDate>
            <atom:updated>2023-03-02T02:40:34.434Z</atom:updated>
            <content:encoded><![CDATA[<h4>Deploying React Applications using Docker in 2 ways — MultiStage builds, and Nginx.</h4><p>Docker is an open platform for developing, shipping, and running applications. Docker ensures quick delivery of your software by providing isolation between your app and the infrastructure. Docker packages and runs everything inside a loosely isolated environment called the container.</p><p><strong>Basic Terminologies -</strong></p><p><strong>1. Docker Image —</strong> A Docker image serves as a map or roadmap of how an application or service will be hosted and work in a docker container. Images are immutable, Once up! You cannot edit them. The only possible way is to make a new image. Images are built using commands written in a docker file.<br><strong>2. Docker Containers —</strong> Docker containers are a sought of isolated servers or executions where you can deploy your applications or services. In an analogy of OOPS, You can say a docker image is a class, and a docker container is an object or instance of that class. When we need to scale up, We can deploy as many as applications we want.<br><strong>3. Docker File —</strong> A docker file is a text file where we determine all the instructions to build our docker image. It’s like a batch script, the first line states the base image, to begin with, and then follow the instructions to install required programs, copy files, and so on, until you get the working environment you need.<br><strong>4. Volumes — </strong>Offer a writable filesystem that the container can use. Since images are read-only but most programs need to write to the filesystem, volumes add a writable layer, on top of the container image, so the programs have access to a writable filesystem. The program doesn’t know it’s accessing a layered filesystem, it’s just the filesystem as usual. Volumes live in the host system and are managed by Docker.</p><p>Now, We need to host our react application using docker. Here, We will see 2 ways to deploy react applications via Docker.</p><blockquote>The first way is to directly run the application in development mode inside the container which is a very naive approach and simple one. The second approach is to use a multistage build using Nginx.</blockquote><p>I am assuming here that you already got your React application up &amp; running. So, let’s directly jump onto the docker file creation and deployments. Create a Docker File in the main folder named Dockerfile without any extension.</p><h4>First Approach -</h4><pre>FROM node:lts-alpine<br>WORKDIR /app<br>COPY package.json ./<br>RUN npm install<br>COPY . .<br>EXPOSE 3000<br>CMD [&quot;npm&quot;, &quot;start&quot;]</pre><p>Here, We are using the node alpine image as a base image to get an optimized and small-sized image. After that, We specified the working directory of our project. After this, We copied the package.json file and triggered the rpm install command. In the last steps, we copied everything in our image and initiated the rpm start command.</p><p>This approach is quite naive &amp; not production ready. Moreover, the image size can also be reduced using a multistage build process. Here, we are just starting a React application inside a Docker container.</p><p>Generally, To deploy React applications, We create build files and deploy those build files on servers. The build object of React applications is simple HTML, JS, and CSS, and these can be easily exposed using a server. We’ll solve all these issues in our second approach.</p><h4>Second Approach -</h4><pre># Stage 1<br># We are using Node alpine base image to reduce the size of our image<br>FROM node:14-alpine as build<br>WORKDIR /app<br>ENV PATH /app/node_modules/.bin:$PATH<br>COPY package.json ./<br>COPY package-lock.json ./<br><br># Installing all the dependencies<br>RUN npm install - silent<br>RUN npm install react-scripts -g<br>COPY . .<br><br># Creating a build for our application<br>RUN npm run build<br><br><br># Stage 2<br># nginx<br>FROM nginx:stable-alpine<br><br># Copying build fields from previous stage into this stage<br>COPY - from=build /app/build /usr/share/nginx/html<br><br># Copying all the Nginx Configurations in our docker environment<br>COPY nginx/nginx.conf /etc/nginx/conf.d/default.conf<br>EXPOSE 80<br><br># Running an Nginx server with all build files on it<br>CMD [&quot;nginx&quot;, &quot;-g&quot;, &quot;daemon off;&quot;]</pre><p>Here, We are using multi-stage builds. This approach is going to help us in reducing the image size and get a production-ready build that will be deployed on the Nginx server. Moreover, to reduce the image size, We can create a docker ignore file. This file is similar to the git ignore file. We can create a file with no extension in the main folder named .dockerignore and you can add —</p><blockquote><em>.git<br>*.md<br>.gitignore<br>/node_modules</em></blockquote><p>and other stuff in that file. Now, We have to try the following commands and your React application will be up and running.</p><pre>docker build -t my-react-app.</pre><ol><li><strong>-t</strong> is used for tagging the image.</li><li>Using a <strong>dot(.) </strong>in the end specifies the path of the Dockerfile. You can also push your image to the Docker hub by installing Docker Desktop software.</li></ol><pre>docker run - rm -it -p 8080:80 my-react-app</pre><p>This command will initiate the start of your React application.</p><p>In the article, What we have seen -<br>1. Create a Dockerfile for the React application in 3 ways.<br>2. Creating React application Docker image from the Dockerfile<br>3. Building the docker image.<br>4. Running the Docker Container</p><p>Thanks for Visiting this page!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77e6e95417c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>