<?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 Ritik Chourasiya on Medium]]></title>
        <description><![CDATA[Stories by Ritik Chourasiya on Medium]]></description>
        <link>https://medium.com/@ritikchourasiya?source=rss-1a8ce9e1f0a4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*d9mkjHeIAy-SDVeEazdDQw.png</url>
            <title>Stories by Ritik Chourasiya on Medium</title>
            <link>https://medium.com/@ritikchourasiya?source=rss-1a8ce9e1f0a4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 15:17:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ritikchourasiya/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[Message Queue — Fundamentals to Advanced]]></title>
            <link>https://ritikchourasiya.medium.com/message-queue-fundamentals-to-advanced-5e20e9cf69dc?source=rss-1a8ce9e1f0a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e20e9cf69dc</guid>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[message-queue]]></category>
            <dc:creator><![CDATA[Ritik Chourasiya]]></dc:creator>
            <pubDate>Fri, 13 Jun 2025 05:20:02 GMT</pubDate>
            <atom:updated>2025-06-13T05:20:02.924Z</atom:updated>
            <content:encoded><![CDATA[<h3>Message Queue — Fundamentals to Advanced</h3><pre>                   ┌────────────┐<br>                   │  Producer  │<br>                   └─────┬──────┘<br>                         │  Sends message<br>                         ▼<br>                  ┌─────────────┐<br>                  │ Message     │<br>                  │  Broker     │  RabbitMQ / Kafka<br>                  └─────┬───────┘<br>                        │<br>        ┌───────────────┴───────────────┐<br>        ▼                               ▼<br> ┌────────────┐                  ┌────────────┐<br> │ Consumer 1 │                  │ Consumer 2 │   Competing workers<br> └────┬───────┘                  └────┬───────┘<br>      │ ACK/NACK                      │<br>      ▼                               ▼<br> ┌───────────────┐            ┌────────────────────┐<br> │ Ack: Done     │            │ Nack: Retry or DLQ │<br> └───────────────┘            └────────────────────┘<br>                                  /<br>                                 /<br>                                /<br>                     ┌───────────────┐<br>                     │ Dead Letter   │<br>                     │    Queue      │<br>                     └───────────────┘</pre><h3>🔍 1. Why Queues?</h3><p>Queues solve a big problem in backend systems:</p><h3>🔗 a. Decoupling</h3><p>Without a queue:</p><pre>Client → API → EmailService → SMTP → Success/Failure</pre><p>➡ If SMTP fails, your whole flow breaks.</p><p>With a queue:</p><pre>Client → API → Queue → EmailWorker → SMTP</pre><p>✅ Your API responds fast; email gets processed <em>eventually</em>, even if SMTP is down briefly.</p><h3>📊 b. Buffering</h3><p>Imagine you get a spike of 100,000 orders at once.</p><p>Your DB or 3rd-party API may choke.</p><p>Queue acts like a <strong>traffic controller</strong> — storing tasks temporarily:</p><pre>[100k Orders] → Queue → 10 workers → DB</pre><h3>♻️ c. Retry Mechanism</h3><p>If a worker fails to send an email or write to DB, you can retry:</p><ul><li>After 5 sec</li><li>Up to 3 times</li><li>Then send to <strong>Dead Letter Queue (DLQ)</strong></li></ul><h3>🚦 d. Backpressure Handling</h3><p>Backpressure = system says “I can’t handle more right now.”</p><p>Queue helps:</p><ul><li>Accepts requests at high rate</li><li>Workers pull at safe pace</li><li>Prevents crashing under load</li></ul><h3>🧱 2. Key Terminology (with examples)</h3><h3>🧑‍💻 Producer</h3><p>The app that <strong>sends messages</strong> to the queue.</p><pre>channel.sendToQueue(&#39;email&#39;, Buffer.from(JSON.stringify({ to: &quot;user@gmail.com&quot; })));</pre><h3>👷 Consumer</h3><p>The service that <strong>receives and processes</strong> messages.</p><pre>channel.consume(&#39;email&#39;, (msg) =&gt; {<br>  // send email<br>  channel.ack(msg);<br>});+</pre><h3>🧠 Message Broker</h3><p>The <strong>middleman</strong> that stores and routes messages.</p><p>Examples:</p><ul><li>RabbitMQ 🐰 (queues)</li><li>Kafka 🐘 (topics + partitions)</li><li>Redis Streams</li><li>AWS SQS / SNS</li></ul><p>It ensures:</p><ul><li>Delivery</li><li>Routing (via exchange)</li><li>Persistence (durable queues)</li></ul><h3>📬 Queue (RabbitMQ, Redis)</h3><ul><li>FIFO (First-In-First-Out)</li><li>Simple: each message is delivered to one consumer</li><li>Good for <strong>background jobs</strong>, <strong>email</strong>, <strong>image processing</strong></li></ul><pre>Queue: &#39;task_queue&#39;<br>→ Worker1<br>→ Worker2 (competing consumers)</pre><h3>📢 Topic (Kafka)</h3><ul><li>Supports <strong>publish/subscribe</strong> pattern</li><li>One message can go to <strong>multiple consumers</strong></li><li>Each consumer group reads independently</li></ul><p><strong>Use case:</strong> Logging, real-time analytics</p><h3>✅ 3. Message Acknowledgements</h3><h3>✅ ack(): Acknowledge</h3><ul><li>Message processed successfully</li><li>Broker removes it from the queue</li></ul><pre>channel.ack(msg);</pre><h3>❌ nack() or Reject</h3><ul><li>Message failed</li><li>Can either requeue or discard</li></ul><pre>channel.nack(msg, false, true); // requeue</pre><h3>💀 4. DLQ (Dead Letter Queue)</h3><p>A <strong>special queue</strong> where messages go after:</p><ul><li>Too many retries</li><li>Invalid format</li><li>Consumer error</li></ul><p>This lets you:</p><ul><li>Analyze failures later</li><li>Avoid infinite retry loops</li></ul><h3>Example:</h3><pre>email_queue (→ retry x3)<br>   ↓<br>dead_letter_queue</pre><h3>💡 Real-World Analogy</h3><p><em>Think of a queue like a </em><strong><em>restaurant order system</em></strong><em>:</em></p><ul><li>Customer (Producer): places an order</li><li>Waiter (Message Broker): takes the order</li><li>Kitchen (Consumer): prepares the dish</li><li>Order Completed (ack): serve to customer</li><li>If chef fails → retry → if fails again → log the issue (DLQ)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e20e9cf69dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Step-by-Step NGINX Server Block Setup]]></title>
            <link>https://ritikchourasiya.medium.com/step-by-step-nginx-server-block-setup-7f803165cae8?source=rss-1a8ce9e1f0a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f803165cae8</guid>
            <category><![CDATA[nginx-reverse-proxy]]></category>
            <category><![CDATA[nginx-hosting]]></category>
            <category><![CDATA[nginx]]></category>
            <dc:creator><![CDATA[Ritik Chourasiya]]></dc:creator>
            <pubDate>Tue, 10 Jun 2025 03:06:19 GMT</pubDate>
            <atom:updated>2025-06-10T03:06:19.953Z</atom:updated>
            <content:encoded><![CDATA[<p>Step 1: Install NGINX (if not already installed)</p><pre>sudo apt update<br>sudo apt install nginx</pre><h3>Step 2: Create a Directory for Your Site</h3><p>This will hold your website’s files.</p><pre>sudo mkdir -p /var/www/example.com/html</pre><p>Set ownership and permissions:</p><pre>sudo chown -R $USER:$USER /var/www/example.com/html<br>sudo chmod -R 755 /var/www/example.com</pre><p>Step 3: Add a Sample index.html (optional)</p><pre>nano /var/www/example.com/html/index.html</pre><h3>Step 4: Create the NGINX Server Block File</h3><p>Create a new config file in /etc/nginx/sites-available/:</p><pre>sudo nano /etc/nginx/sites-available/example.com</pre><p>Paste this configuration:</p><pre>server {<br>    listen 80;<br>    listen [::]:80;<br><br>    server_name example.com www.example.com;<br><br>    root /var/www/example.com/html;<br>    index index.html index.htm;<br><br>    access_log /var/log/nginx/example.com.access.log;<br>    error_log /var/log/nginx/example.com.error.log;<br><br>    location / {<br>        try_files $uri $uri/ =404;<br>    }<br><br><br>    # reverse proxy for backend<br>    location /api/ {<br>        proxy_pass http://localhost:5000;<br>        proxy_http_version 1.1;<br>        proxy_set_header Upgrade $http_upgrade;<br>        proxy_set_header Connection &#39;upgrade&#39;;<br>        proxy_set_header Host $host;<br>        proxy_cache_bypass $http_upgrade;<br>    }<br>}</pre><h3>Step 5: Enable the Server Block</h3><p>Create a symlink to sites-enabled:</p><pre>sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/</pre><p>Step 6: Test NGINX Configuration</p><pre>sudo nginx -t<br><br>sudo systemctl reload nginx</pre><p>Bonus: Secure with SSL (Optional but Recommended)</p><p>Install Certbot and get a free SSL certificate:</p><pre>sudo apt install certbot python3-certbot-nginx<br>sudo certbot --nginx -d example.com -d www.example.com</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f803165cae8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the Difference Between PUT and PATCH in REST APIs]]></title>
            <link>https://ritikchourasiya.medium.com/understanding-the-difference-between-put-and-patch-in-rest-apis-024c2a93558c?source=rss-1a8ce9e1f0a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/024c2a93558c</guid>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Ritik Chourasiya]]></dc:creator>
            <pubDate>Sun, 28 Jul 2024 06:01:55 GMT</pubDate>
            <atom:updated>2024-07-28T06:01:55.540Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o-8Pw7p-kQusA0KJxVm_pg.png" /><figcaption>Difference Between PUT and PATCH in REST APIs</figcaption></figure><p>Today, I want to delve into a topic that often comes up when working with REST APIs: the difference between PUT and PATCH. As a software engineer, I frequently use both methods, and understanding their distinct roles can make a big difference in how we design and interact with our APIs. So, let’s break it down!</p><h4>The Full Replacement Power of PUT</h4><p>First up, let’s talk about PUT. Think of PUT like giving your API a completely new blueprint for a resource. When you send a PUT request, you&#39;re essentially saying, &quot;<em>Here&#39;s the new version of the resource. Replace everything you have with this.</em>&quot;</p><p>Here’s a little example to illustrate:</p><pre>PUT /users/1<br>Content-Type: application/json<br>{<br>  &quot;id&quot;: 1,<br>  &quot;name&quot;: &quot;John Doe&quot;,<br>  &quot;email&quot;: &quot;john.doe@example.com&quot;,<br>  &quot;age&quot;: 30<br>}</pre><p>In this request, I’m updating the user with ID 1, providing the complete set of user details. If any fields are missing in the request, they get reset to their default values. It’s like redecorating your entire room instead of just changing the curtains.</p><p>In this request, I’m updating the user with ID 1, providing the complete set of user details. If any fields are missing in the request, they get reset to their default values. It’s like redecorating your entire room instead of just changing the curtains.</p><p>One key thing to remember is that PUT is idempotent. This fancy word means that no matter how many times you send the same PUT request, the result will always be the same. Imagine repainting your room the same color over and over again – it looks the same after each coat.</p><h4>The Precision of PATCH</h4><p>On the other hand, PATCH is more like a scalpel than a sledgehammer. With PATCH, you’re making precise updates to specific parts of a resource without touching the rest. It’s perfect for those times when you just want to change the curtains without redecorating the entire room.</p><p>Here’s an example of a PATCH request:</p><pre>PATCH /users/1<br>Content-Type: application/json<br><br>{<br>  &quot;age&quot;: 31<br>}</pre><p>In this case, I’m only updating the age of the user with ID 1. The rest of the user’s information remains unchanged. It’s a quick and efficient way to make small updates.</p><p>PATCH can be idempotent, but it’s not a guarantee. The result can vary based on the current state of the resource. Imagine adjusting the brightness of a lamp in a room; depending on the current brightness, the effect of your action might be different each time.</p><h4>When to Use What</h4><p>So, when should you use PUT versus PATCH? Here’s my rule of thumb:</p><ul><li>Use <strong>PUT</strong> when you want to update a resource entirely. It’s like starting fresh with a new blueprint.</li><li>Use <strong>PATCH</strong> when you only need to make small, specific updates. It’s like making tweaks without a full overhaul.</li></ul><p>Understanding these differences not only helps in designing better APIs but also ensures that your applications are efficient and maintainable.</p><p>I hope this clears up the confusion between PUT and PATCH. Feel free to share your thoughts or any experiences you’ve had with these methods. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=024c2a93558c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Save Your Production Server by Mastering GitHub Branching and Merging]]></title>
            <link>https://ritikchourasiya.medium.com/save-your-production-server-by-mastering-github-branching-and-merging-d6f8bd864fc9?source=rss-1a8ce9e1f0a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6f8bd864fc9</guid>
            <category><![CDATA[git-branching-strategy]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[github-branching]]></category>
            <category><![CDATA[git-branching]]></category>
            <category><![CDATA[github]]></category>
            <dc:creator><![CDATA[Ritik Chourasiya]]></dc:creator>
            <pubDate>Sat, 27 Jul 2024 06:28:04 GMT</pubDate>
            <atom:updated>2024-07-27T06:28:04.266Z</atom:updated>
            <content:encoded><![CDATA[<p>Managing code changes and collaboration efficiently is crucial for any development team. One of the best practices for achieving this is using a well-defined branching and merging strategy. In this blog, we’ll walk you through a step-by-step guide on how to use develop and production branches in GitHub, including how to handle merge conflicts and raise pull requests (PRs).</p><h3>Why We Need a Branching and Merging Strategy</h3><p>Imagine you’re developing a new feature for your application. Without a clear strategy, integrating your work could lead to conflicts, instability, and deployment issues. A structured approach not only streamlines development but also safeguards the stability of your production code.</p><h4>Scenario: Developing a New Feature</h4><p><strong>Step 1: Creating a Feature Branch</strong></p><p>To add a new feature, you start by creating a feature branch from the production branch. This ensures your work is based on the latest stable code.</p><pre>git checkout production<br>git pull origin production<br>git checkout -b feature/user-authentication</pre><p><strong>Step 2: Developing and Testing</strong></p><p>Develop the user authentication feature on your feature/user-authentication branch. Regular commits and pushes keep your work up-to-date and backed up.</p><pre>git add .<br>git commit -m &quot;Add login functionality&quot;<br>git push origin feature/user-authentication</pre><p><strong>Step 3: Integrating into Develop</strong></p><p>Once the feature is complete and tested, create a PR to merge it into the develop branch. This step allows the feature to be tested alongside other ongoing developments.</p><p>However, you might encounter merge conflicts due to simultaneous changes by other developers. To resolve this, merge the develop branch into your feature branch, fix any conflicts, and then merge your feature branch back into develop. But what if the develop branch contains untested or buggy code? You don’t want these issues to affect your production code.</p><p>Here’s where a robust branching strategy comes into play.</p><h4>The Branching Strategy</h4><p>Our strategy uses two primary branches:</p><ul><li><strong>Develop</strong>: This is the integration branch for all feature development. It holds the latest code ready for testing and integration.</li><li><strong>Production</strong>: This branch contains stable, production-ready code. Features are merged into production only after thorough testing in the develop branch.</li></ul><h3>Step-by-Step Workflow</h3><p><strong>1. Creating a Feature Branch</strong></p><p>Start by creating a feature branch from the production branch. This ensures your new feature is based on the latest stable code.</p><pre>git checkout production<br>git pull origin production<br>git checkout -b feature/your-feature-name</pre><p>Replace your-feature-name with a descriptive name for your feature.</p><p><strong>2. Developing and Testing Your Feature</strong></p><p>Work on your feature branch. Implement the necessary changes and test them thoroughly. Commit your changes regularly to keep your feature branch updated.</p><pre>git add .<br>git commit -m &quot;Describe your changes&quot;<br>git push origin feature/your-feature-name</pre><p><strong>3. Merging into Develop</strong></p><p>Once you’re satisfied with your feature and it’s ready for integration, create a PR from your feature branch to the develop branch. This allows your feature to be tested and integrated with other features.</p><h3>Handling Merge Conflicts</h3><p>Merge conflicts can be tricky, but with a systematic approach, you can resolve them efficiently.</p><p><strong>a. Create a Merge Branch from Develop</strong></p><pre>git checkout develop<br>git pull origin develop<br>git checkout -b merge/feature-into-develop</pre><p><strong>b. Merge Your Feature Branch into the Merge Branch</strong></p><pre>git merge feature/your-feature-name</pre><p><strong>c. Resolve Any Merge Conflicts</strong></p><p>Edit the conflicting files to resolve the conflicts. After resolving, add and commit the changes.</p><pre>git add .<br>git commit -m &quot;Resolve merge conflicts between feature branch and develop&quot;</pre><p><strong>d. Push the Merge Branch and Create a PR</strong></p><pre>git push origin merge/feature-into-develop</pre><p>Create a PR from merge/feature-into-develop to develop on GitHub.</p><h3>4. Raising a PR to Production</h3><p>After your feature has been merged into develop and has passed all tests, prepare to merge it into production.</p><pre>git checkout production<br>git pull origin production<br>git checkout -b merge/develop-into-production<br>git merge develop<br>git push origin merge/develop-into-production</pre><p>Create a PR from merge/develop-into-production to production on GitHub.</p><p>By following this branching and merging strategy, you can ensure smooth feature integration and maintain the stability of your production code. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6f8bd864fc9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understand Cognitive Complexity: A Key to Cleaner, More Maintainable Code]]></title>
            <link>https://ritikchourasiya.medium.com/understand-cognitive-complexity-a-key-to-cleaner-more-maintainable-code-45bd210a1d8e?source=rss-1a8ce9e1f0a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/45bd210a1d8e</guid>
            <category><![CDATA[clean-code-principle]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[code-quality]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Ritik Chourasiya]]></dc:creator>
            <pubDate>Sun, 30 Jun 2024 10:54:58 GMT</pubDate>
            <atom:updated>2024-06-30T10:54:58.470Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nV9bVHdE2MCgArxD9tKmUA.png" /><figcaption>Understand Cognitive Complexity</figcaption></figure><p>As software developers, we strive to write code that is not only functional but also easy to understand and maintain. One crucial metric that helps us achieve this is Cognitive Complexity. Unlike traditional complexity metrics such as Cyclomatic Complexity, which focus on the number of paths through the code, Cognitive Complexity measures how difficult the code is for a human to understand.</p><h3>What is Cognitive Complexity?</h3><p>Cognitive Complexity assesses the mental effort required to understand a piece of code. It takes into account several factors:</p><ul><li>Control Structures: Each control structure (e.g., if statements, loops) increases cognitive complexity. Nested control structures add more to the score than sequential ones.</li><li>Nesting: Deeper nesting of control structures increases the complexity score significantly because it requires a developer to hold more context in mind.</li><li>Recursion and Indirection: Recursion, complex expressions, and other forms of indirection (e.g., callbacks, promise chains) increase cognitive complexity.</li><li>Boolean Expressions: Complex boolean expressions and ternary operators contribute to cognitive complexity due to the mental effort required to parse and understand them.</li><li>Logical Structure: Code that jumps around a lot (e.g., multiple return statements, breaking out of loops) is harder to follow and thus has a higher cognitive complexity.</li></ul><h3>Why Does Cognitive Complexity Matter?</h3><p>The goal of Cognitive Complexity is to reflect how the code’s structure impacts a developer’s ability to understand and maintain it. By keeping cognitive complexity low, you ensure that your codebase remains clean, understandable, and maintainable.</p><h3>Example of Cognitive Complexity Calculation</h3><p>Consider the following code snippet:</p><pre>const processOrder = (order, user, discountCode) =&gt; {<br>    let total = 0;<br>    let discount = 0;<br>    let tax = 0.08;<br>    let discountApplied = false;<br><br>    if (order.items &amp;&amp; order.items.length &gt; 0) { // +1<br>        for (let i = 0; i &lt; order.items.length; i++) { // +1<br>            let item = order.items[i];<br><br>            if (item.quantity &gt; 0) { // +1<br>                let itemTotal = item.price * item.quantity;<br><br>                if (item.onSale) { // +1<br>                    itemTotal = itemTotal * 0.9; // 10% discount for sale items<br>                }<br><br>                total += itemTotal;<br>            }<br>        }<br><br>        if (discountCode &amp;&amp; !discountApplied) { // +1<br>            if (discountCode === &quot;SAVE10&quot;) { // +1<br>                discount = total * 0.1;<br>            } else if (discountCode === &quot;SAVE20&quot;) { // +1<br>                discount = total * 0.2;<br>            } else if (discountCode === &quot;SAVE30&quot; &amp;&amp; user.isPremium) { // +2<br>                discount = total * 0.3;<br>            } else { // +1<br>                console.log(&quot;Invalid discount code or conditions not met.&quot;);<br>            }<br>            discountApplied = true;<br>        }<br><br>        total -= discount;<br>        total += total * tax;<br>        console.log(&quot;Total after discounts and tax:&quot;, total);<br>    } else { // +1<br>        console.log(&quot;Order has no items.&quot;);<br>    }<br>}; </pre><h3>Cognitive Complexity Calculation</h3><ol><li>Top-level if statement (if (order.items &amp;&amp; order.items.length &gt; 0)) adds +1.</li><li>for loop adds +1.</li><li>Nested if statement inside the loop (if (item.quantity &gt; 0)) adds +1.</li><li>Another nested if statement inside the previous if (if (item.onSale)) adds +1.</li><li>Top-level if statement after the loop (if (discountCode &amp;&amp; !discountApplied)) adds +1.</li><li>Nested if statement inside the discount code check (if (discountCode === “SAVE10”)) adds +1.</li><li>else if statement inside the discount code check (else if (discountCode === “SAVE20”)) adds +1.</li><li>Another else if statement with additional condition (else if (discountCode === “SAVE30” &amp;&amp; user.isPremium)) adds +2 (1 for the condition, and an additional 1 for the logical AND).</li><li>Final else statement inside the discount code check (else) adds +1.</li><li>Final else statement at the top level (else) adds +1.</li></ol><h3>Total Cognitive Complexity</h3><p>Summing up all the individual contributions, the total cognitive complexity is:</p><p>1 (top-level if) + 1 (for loop) + 1 (nested if) + 1 (nested if) + 1 (top-level if after loop) + 1 (nested if) + 1 (else if) + 2 (else if with additional condition) + 1 (final else in discount code check) + 1 (final top-level else) = 11</p><p>The total Cognitive Complexity here is 11.</p><h3>Refactored Function with Reduced Cognitive Complexity</h3><p>To reduce cognitive complexity, we can break this function into smaller helper functions, each handling a single responsibility.</p><p>Step 1: Extract Helper Functions</p><pre>const calculateItemTotal = (item) =&gt; {<br>    let itemTotal = item.price * item.quantity;<br>    if (item.onSale) {<br>        itemTotal *= 0.9; // 10% discount for sale items<br>    }<br>    return itemTotal;<br>};<br><br>const applyDiscount = (total, discountCode, user) =&gt; {<br>    let discount = 0;<br>    if (discountCode === &quot;SAVE10&quot;) {<br>        discount = total * 0.1;<br>    } else if (discountCode === &quot;SAVE20&quot;) {<br>        discount = total * 0.2;<br>    } else if (discountCode === &quot;SAVE30&quot; &amp;&amp; user.isPremium) {<br>        discount = total * 0.3;<br>    } else {<br>        console.log(&quot;Invalid discount code or conditions not met.&quot;);<br>    }<br>    return discount;<br>};<br><br>const calculateTotalWithTax = (total, taxRate) =&gt; {<br>    return total + (total * taxRate);<br>};</pre><p>Step 2: Refactor the Main Function</p><pre>const processOrder = (order, user, discountCode) =&gt; {<br>    const taxRate = 0.08;<br>    let total = 0;<br><br>    if (order.items &amp;&amp; order.items.length &gt; 0) {<br>        for (let i = 0; i &lt; order.items.length; i++) {<br>            const item = order.items[i];<br>            if (item.quantity &gt; 0) {<br>                total += calculateItemTotal(item);<br>            }<br>        }<br><br>        const discount = applyDiscount(total, discountCode, user);<br>        total -= discount;<br>        total = calculateTotalWithTax(total, taxRate);<br><br>        console.log(&quot;Total after discounts and tax:&quot;, total);<br>    } else {<br>        console.log(&quot;Order has no items.&quot;);<br>    }<br>};</pre><h3>Tips to reducing Cognitive Complexity</h3><p>Refactoring code to reduce cognitive complexity might involve:</p><ul><li>Breaking Down Large Functions: Decompose large functions into smaller, single-responsibility functions.</li><li>Flattening Control Structures: Simplify deeply nested control structures.</li><li>Simplifying Boolean Expressions: Break down complex boolean expressions into simpler statements.</li><li>Reducing Control Flow Changes: Minimize the number of control flow changes, such as early returns or breaks.</li></ul><h3>Benefits of Low Cognitive Complexity</h3><ul><li>Maintainability: Easier to understand and modify.</li><li>Readability: More approachable for new developers.</li><li>Lower Bug Risk: Less complex code is less prone to errors.</li></ul><p>By focusing on reducing cognitive complexity, you can create a codebase that is not only efficient but also a joy to work with. Let’s strive for cleaner, more maintainable code!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45bd210a1d8e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Step-by-Step Guide: How to Use Websentry GitHub Action]]></title>
            <link>https://ritikchourasiya.medium.com/step-by-step-guide-how-to-use-websentry-github-action-03ad3dae99b5?source=rss-1a8ce9e1f0a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/03ad3dae99b5</guid>
            <category><![CDATA[website-monitoring]]></category>
            <category><![CDATA[websentry]]></category>
            <category><![CDATA[monitoring-tools]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[github]]></category>
            <dc:creator><![CDATA[Ritik Chourasiya]]></dc:creator>
            <pubDate>Tue, 31 Oct 2023 12:24:17 GMT</pubDate>
            <atom:updated>2023-10-31T12:24:17.660Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*YhGHF-w5wUcgVe73VZ78CQ.png" /></figure><p>Welcome to Websentry, a powerful GitHub Action that simplifies website health monitoring.</p><p>With Websentry, you can effortlessly check the availability of your websites and receive real-time reports on their status.</p><p>Whether you’re a website owner, developer, or part of an operations team, Websentry provides a reliable solution for ensuring your online presence remains uninterrupted.</p><p>Let’s get started with a step-by-step guide on how to use Websentry to monitor the health of your websites.</p><h3>Prerequisites</h3><p>Before we dive into the setup, make sure you have the following prerequisites in place:</p><ol><li><strong>GitHub Repository: </strong>You’ll need a GitHub repository where you want to monitor website health.</li><li><strong>Basic Knowledge of GitHub Actions: </strong>Familiarity with GitHub Actions will be helpful as we’ll be setting up the workflow there.</li></ol><h3>Installation</h3><p>We’ll start by creating a GitHub Actions workflow that uses Websentry. Follow these steps:</p><p><strong>1. Access Your GitHub Repository: </strong>Open your GitHub repository where you want to set up website health monitoring with Websentry.</p><p><strong>2. Create a Workflow File: </strong>Inside your repository, navigate to the .github/workflows directory. If it doesn&#39;t exist, you can create it. Create a new YAML file for your Websentry workflow, for example, health_check.yml.</p><p><strong>3. Edit the Workflow File:</strong> Open the health_check.yml file for editing and add the following content:</p><pre>name: Website Health Check<br><br>on:<br>  schedule:<br>    - cron: &#39;0 * * * *&#39;  # Run every hour<br><br>jobs:<br>  website-health-check:<br>    runs-on: ubuntu-latest<br>    name: Website Health Check<br>    steps:<br>      - name: Check out code<br>        uses: actions/checkout@v2<br>      - name: Setup Go<br>        uses: actions/setup-go@v2<br>        with:<br>          go-version: &#39;1.16&#39;  # Use the Go version you need<br>      - name: Websentry Action<br>        uses: theritikchoure/websentry@main<br>        with:<br>          website-url: &#39;example.com,example2.com&#39;  # Set the website URLs you want to check<br>          max-retries: &#39;10&#39;<br>          retry-interval: &#39;5s&#39;<br>          request-timeout: &#39;10s&#39;</pre><p>In this YAML file, we have defined the schedule for running the workflow (every hour in this example). You can customize the schedule according to your needs.</p><p>Make sure to replace &#39;example.com,example2.com&#39; with the website URLs you want to monitor. You can also adjust the max-retries, retry-interval, and request-timeout values as needed.</p><p><strong>4. Commit Changes: </strong>Save the changes to the health_check.yml file and commit them to your GitHub repository.</p><h3>Usage</h3><p>With the Websentry GitHub Action set up in your repository, it will continuously monitor the health of the specified websites and provide instant status reports.</p><h3>Configuration</h3><p>You can customize Websentry by specifying the following input parameters in your GitHub Actions workflow:</p><ul><li><strong>website-url: </strong>The URLs of the websites you want to monitor.</li><li><strong>max-retries: </strong>The maximum number of retries for checking the websites’ health.</li><li><strong>retry-interval:</strong> The time interval between retry attempts.</li><li><strong>request-timeout: </strong>The timeout for HTTP requests.</li></ul><h3>Monitoring Reports</h3><p>Websentry provides detailed monitoring reports for each website you track. These reports include:</p><ul><li><strong>Availability Status:</strong> Instant updates on whether the website is up or down.</li><li><strong>Response Time:</strong> Measured time taken to receive a response.</li><li><strong>Content Length:</strong> Size of the retrieved content.</li><li><strong>Redirect URL:</strong> Details on any URL redirections.</li><li>Server Information: Information about the web server.</li><li><strong>Content Type:</strong> Type of content returned by the server.</li><li><strong>SSL Status:</strong> Indication of whether SSL is enabled.</li></ul><h3>Conclusion</h3><p>By following these steps, you’ve set up Websentry to monitor the health of your specified websites, ensuring that your online presence remains uninterrupted.</p><p>Websentry will run at the scheduled intervals and provide you with instant status reports, helping you quickly identify and address any issues.</p><p>Remember to regularly review the monitoring reports to ensure the continuous health of your websites and online services.</p><p>I hope that Websentry proves to be a valuable tool for maintaining the reliability of your online presence.</p><p>Links —</p><p>Websentry Github Action — <a href="https://github.com/marketplace/actions/websentry-action">WebSentry Action · Actions · GitHub Marketplace</a></p><p>Github Repo — <a href="https://github.com/theritikchoure/websentry">Websentry at Github by Ritik Chourasiya</a></p><p>Author — Ritik Chourasiya (<a href="https://github.com/theritikchoure/">Github</a>) (<a href="https://www.linkedin.com/in/ritikchourasiya/">Linkedin</a>)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=03ad3dae99b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LogX — Enhance Your GoLang Projects with Colorful Logging]]></title>
            <link>https://ritikchourasiya.medium.com/logx-enhance-your-golang-projects-with-colorful-logging-1f93df825cd8?source=rss-1a8ce9e1f0a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f93df825cd8</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[logx]]></category>
            <category><![CDATA[go-lang-package]]></category>
            <category><![CDATA[go-logging]]></category>
            <category><![CDATA[logging]]></category>
            <dc:creator><![CDATA[Ritik Chourasiya]]></dc:creator>
            <pubDate>Sun, 15 Oct 2023 03:53:41 GMT</pubDate>
            <atom:updated>2023-10-15T03:53:41.602Z</atom:updated>
            <content:encoded><![CDATA[<h3>LogX — Enhance Your GoLang Projects with Colorful Logging</h3><p>Logging is a critical aspect of software development. It helps you track your application’s behavior, find bugs, and monitor its performance.</p><p>However, plain text logs can be challenging to navigate, especially in complex applications.</p><p>That’s where the “logx” package comes in. This GoLang package allows you to add color and formatting to your console log messages, making it easier to distinguish different types of log entries or to add emphasis to specific messages.</p><p>In this guide, we’ll show you how to make the most of “logx” and enhance your GoLang projects.</p><h4>Prerequisites</h4><p>Before you get started with “logx,” there are a few prerequisites you need to meet:</p><ul><li>You should have GoLang installed on your system.</li><li>A basic understanding of GoLang programming is helpful.</li></ul><p>If you’re new to GoLang, you can follow the installation guide for your specific platform on the official GoLang website.</p><h4>Installation</h4><p>The first step is to install the “logx” package into your GoLang project. It’s a straightforward process using the go get command:</p><pre>go get github.com/theritikchoure/logx</pre><p>Don’t forget to import “logx” in your GoLang code:</p><pre>import &quot;github.com/theritikchoure/logx&quot;</pre><p>Now you’re ready to add some color to your logs.</p><h4>Enabling Colorful Logging</h4><p>By default, colorized logging is disabled in “logx.” You can enable or disable it by modifying the ColoringEnabled variable in your code. Setting it to true will enable colored output, while setting it to false will disable it (which is the default behavior):</p><pre>logx.ColoringEnabled = true // Enable colorized logging<br>logx.ColoringEnabled = false // Disable colorized logging (default)</pre><h4>Basic Logging</h4><p>The “logx” package provides the Log function to print log messages with specified foreground and background colors. If coloring is enabled, it will print colorful log entries; otherwise, it will print plain text.</p><pre>logx.Log(&quot;This is a log message&quot;, logx.FGRED, logx.BGGREEN)</pre><p>With a simple function call, you can make your logs more visually appealing and easier to distinguish.</p><h4>Formatted Logging</h4><p>For more complex log entries, you can use the Logf function. It works similarly to Go&#39;s fmt.Printf and allows you to format log messages and specify colors:</p><pre>logx.Logf(&quot;User: %s logged in.&quot;, logx.FGBLUE, logx.BGWHITE, &quot;JohnDoe&quot;)</pre><p>This is handy when you need to insert dynamic values into your log messages.</p><h4>Log Levels</h4><p>To make your log entries even more informative, “logx” supports log levels like INFO, WARNING, ERROR, and SUCCESS. You can use the LogWithLevel function to display log messages with predefined background colors corresponding to these levels:</p><pre>logx.LogWithLevel(&quot;An error occurred&quot;, &quot;ERROR&quot;)</pre><p>It’s an excellent way to categorize and distinguish log entries based on their significance.</p><h4>Multiple Messages</h4><p>Sometimes, you may want to log multiple messages with customized formatting options. “logx” provides the LogM function for this purpose. You can combine color codes and formatting options to create visually appealing log entries:</p><pre>logx.LogM([]string{&quot;Applying&quot;, &quot;updates...&quot;}, logx.FGBLUE, logx.BGYELLOW, logx.BOLD, logx.UNDERLINE)</pre><p>With “logx,” you have the flexibility to design logs that suit your project’s needs.</p><h4>Timestamps</h4><p>Adding timestamps to your log entries can help you understand when specific events occurred. The LogWithTimestamp function simplifies this task:</p><pre>logx.LogWithTimestamp(&quot;System restarted&quot;, logx.FGCYAN, logx.BGWHITE)</pre><p>Now you can track the timing of critical events effortlessly.</p><h4>Logging to a File</h4><p>In addition to standard output, “logx” allows you to log messages to a file. The LogToFile function opens the specified file for appending and logs the message to both the file and standard output:</p><pre>logx.LogToFile(&quot;Log entry written to file&quot;, logx.FGRED, logx.BGGREEN, &quot;log.txt&quot;)</pre><p>This feature is handy for archiving logs and analyzing them later.</p><h4>Best Practices</h4><p>To make the most of “logx,” consider the following best practices:</p><ul><li>Use appropriate log levels (INFO, WARNING, ERROR) to categorize log messages.</li><li>Maintain clean and organized logs by following a consistent format.</li><li>Embrace colorful logging to enhance log entry distinction.</li></ul><h4>Conclusion</h4><p>Incorporating colorful and formatted logging into your GoLang projects is a simple yet powerful way to make your logs more informative and visually appealing. “logx” provides an easy-to-use package for achieving this goal, and this guide has demonstrated how to use it effectively. By categorizing log entries, adding timestamps, and employing best practices, you can improve your application’s log quality and save time debugging issues.</p><h4>Additional Resources</h4><p>For more details and community support, check out the official “logx” documentation and the GitHub repository:</p><ul><li><a href="https://github.com/theritikchoure/logx">logx GitHub Repository</a></li></ul><p>Start using “logx” today and experience a new level of clarity and organization in your GoLang projects.</p><p><strong>Author’s Note</strong></p><p>As the author of “logx,” I’m thrilled to see developers embracing this package. It was created with the goal of simplifying log management in GoLang, and I’m excited to hear your feedback, answer your questions, and help you get the most out of “logx.”</p><p>I hope this blog helps you use “logx” effectively in your GoLang projects. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f93df825cd8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Preventing MongoDB NoSQL Injection Attacks: Securing Your Node.js]]></title>
            <link>https://ritikchourasiya.medium.com/preventing-mongodb-nosql-injection-attacks-securing-your-node-js-56215ef7455?source=rss-1a8ce9e1f0a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/56215ef7455</guid>
            <category><![CDATA[nosql-injection]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[nosql]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Ritik Chourasiya]]></dc:creator>
            <pubDate>Thu, 29 Jun 2023 15:39:49 GMT</pubDate>
            <atom:updated>2023-06-29T15:39:49.760Z</atom:updated>
            <content:encoded><![CDATA[<h3>Preventing MongoDB NoSQL Injection Attacks: Securing Your Node.js Express Application with Code Examples</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yed0T_9GD2nYeDb8oqlx6Q.png" /><figcaption>Preventing MongoDB NoSQL Injection Attacks</figcaption></figure><p><strong>MongoDB </strong>has become a popular choice for developers due to its flexibility and scalability. However, just like any other database, <strong>MongoDB </strong>is susceptible to security vulnerabilities, one of which is <strong>NoSQL injection</strong>.</p><p>This type of attack occurs when user input is not properly sanitized and is directly used in database queries, allowing attackers to manipulate queries and gain unauthorized access to sensitive data.</p><p>In this blog post, we will delve into the concept of <strong>NoSQL injection attacks</strong>, explore the risks they pose, and discuss effective <strong>prevention techniques using Node.js and Express</strong>, along with practical code examples.</p><h4>Understanding NoSQL Injection:</h4><p>NoSQL injection is an attack that specifically targets NoSQL databases, including MongoDB. It takes advantage of poorly sanitized user input, which is incorporated into database queries without proper validation.</p><p>By injecting malicious code, attackers can exploit this vulnerability to alter query logic, gain unauthorized access to sensitive data, or even corrupt the entire database.</p><p>Here’s a simplified example to demonstrate the concept, without providing code for an actual attack:</p><p>Suppose you have a MongoDB query in your application that looks like this:</p><pre>const username = req.body.username;<br>const password = req.body.password;<br><br>const query = {<br>  username: username,<br>  password: password<br>};<br><br>UserModel.find(query, (err, result) =&gt; {<br>  // Handle the result<br>});</pre><p>In this example, the code retrieves the username and password from user input and constructs a query object to find a user in the database. However, if the input is not properly validated, it can be exploited for a NoSQL injection attack.</p><p>An attacker might craft a malicious payload by manipulating the input, such as entering {&quot;$ne&quot;: null} as the password input. This payload exploits the $ne (not equal) operator to bypass authentication, potentially allowing unauthorized access to user accounts.</p><p>To prevent such attacks, you need to implement proper input validation, sanitize user input, and use parameterized queries or prepared statements, we will discuss next.</p><h4>The Risks of NoSQL Injection:</h4><p>NoSQL injection attacks can have severe consequences, jeopardizing the security and integrity of your application.</p><p>The potential risks include unauthorized access to confidential information, leakage of sensitive data, manipulation or corruption of data, and potentially even a complete loss of critical information.</p><p>Applications that handle user authentication, financial transactions, or personal data are particularly vulnerable. Therefore, it is crucial to understand and mitigate NoSQL injection vulnerabilities to protect your application and its users.</p><h4>Preventing NoSQL Injection Attacks:</h4><p><strong>👉 1. Sanitize and Validate User Input:</strong> Always sanitize and validate user input before incorporating it into database queries. Implement robust input validation mechanisms using libraries or custom logic to ensure that the input data adheres to the expected format, type, and constraints.</p><p>This step acts as a crucial line of defense, preventing malicious input from reaching the database.</p><p><strong>👉 2. Parameterized Queries: </strong>Instead of directly concatenating user input into queries, utilize parameterized queries or prepared statements.</p><p>Parameterization separates the query structure from the input data, effectively preventing injection attacks.</p><p>Most MongoDB libraries and drivers offer built-in support for parameterized queries, making it easier to implement this preventive measure.</p><pre>const name = req.body.name; // User input<br>const query = { name: { $eq: name } };<br><br>// Using parameterized query with Mongoose<br>UserModel.find(query, (err, result) =&gt; {<br>  // Handle the result<br>});</pre><p><strong>👉 3. Object-Document Mapping (ODM) or Object-Relational Mapping (ORM) Libraries: </strong>Consider leveraging ODM or ORM libraries such as Mongoose when working with MongoDB. These libraries provide an abstraction layer that handles input sanitization, query construction, and data schema validation for you.</p><p>By utilizing an ODM or ORM, you automatically benefit from built-in protections against NoSQL injection, reducing the risk of vulnerabilities in your code.</p><pre>// Mongoose example with validation and sanitization<br>const userSchema = new mongoose.Schema({<br>  name: { type: String, required: true },<br>  age: { type: Number, min: 0, max: 150 },<br>});<br>const UserModel = mongoose.model(&#39;User&#39;, userSchema);<br><br>const name = req.body.name; // User input<br>const query = UserModel.find({ name: name });<br><br>query.exec((err, result) =&gt; {<br>  // Handle the result<br>});</pre><p><strong>👉 4. Least Privilege Principle:</strong> Adhere to the principle of least privilege when configuring database access. Ensure that the database user or role used by your application has the minimum necessary privileges required for its intended functionality.</p><p>By restricting access rights to only the essential collections and operations, you can significantly reduce the potential impact of a successful injection attack.</p><p><strong>👉 5. Regularly Update Dependencies: </strong>Keep your MongoDB driver and other dependencies up to date. Developers frequently release security patches and updates to address vulnerabilities.</p><p>Staying informed about the latest updates and promptly applying them to your application helps ensure that you have the latest security fixes, reducing the risk of potential exploits.</p><h4>Conclusion:</h4><p>NoSQL injection attacks pose a significant threat to the security of MongoDB-based applications. By following the prevention techniques outlined in this article, you can substantially mitigate the risk of such attacks.</p><p>Sanitizing and validating user input, implementing parameterized queries, utilizing ODM/ORM libraries, adhering to the least privilege principle, and regularly updating dependencies are essential steps in safeguarding your application against NoSQL injection vulnerabilities.</p><p>Remember that security is an ongoing process, and it is crucial to stay informed about the latest security practices, patches, and advisories. By adopting a proactive approach to security, you can effectively protect your MongoDB-based applications from potential NoSQL injection vulnerabilities.</p><blockquote>Happy coding and keep your applications secure!</blockquote><p>Connect on LinkedIn — <a href="https://www.linkedin.com/in/ritikchourasiya/"><strong><em>@ritikchourasiya</em></strong></a></p><p>Connect on Github — <a href="https://github.com/theritikchoure"><strong><em>@theritikchoure</em></strong></a></p><p>Portfolio — <a href="https://theritikchoure.github.io/"><strong><em>theritikchoure.github.io</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56215ef7455" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the Difference between CSR and SSR Rendering]]></title>
            <link>https://ritikchourasiya.medium.com/understanding-the-difference-between-csr-and-ssr-rendering-d2fa0eee50e?source=rss-1a8ce9e1f0a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2fa0eee50e</guid>
            <category><![CDATA[server-side-rendering]]></category>
            <category><![CDATA[rendering]]></category>
            <category><![CDATA[client-side-rendering]]></category>
            <dc:creator><![CDATA[Ritik Chourasiya]]></dc:creator>
            <pubDate>Wed, 28 Jun 2023 06:01:55 GMT</pubDate>
            <atom:updated>2023-06-28T06:01:55.711Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r8uru3g9HVLioxvsiDW4_A.png" /><figcaption>Difference between CSR and SSR Rendering</figcaption></figure><p>In the realm of web development, rendering techniques play a crucial role in delivering engaging user experiences. Two popular rendering approaches are <strong>Client-Side Rendering (CSR)</strong> and <strong>Server-Side Rendering (SSR)</strong>.</p><p>Both methods have their own advantages and considerations, making it important for developers to understand the differences between them. In this article, we will explore <strong>CSR </strong>and <strong>SSR </strong>rendering, highlighting their distinctions and providing relevant examples to clarify their use cases.</p><h4>Client-Side Rendering (CSR)</h4><p>CSR, also known as client-side rendering, is a technique where the rendering process occurs on the client-side, typically in the user’s web browser.</p><p>In CSR, the server sends a minimal HTML document along with JavaScript files to the client. The JavaScript code is responsible for fetching data from an API and manipulating the Document Object Model (DOM) to update the user interface.</p><p><strong>🎯Advantages of CSR:</strong></p><ol><li><strong>Enhanced interactivity: </strong>CSR enables highly interactive web applications as the client can update the UI without making additional requests to the server. This results in a smooth and responsive user experience.</li><li><strong>Improved performance:</strong> Once the initial page load is complete, subsequent interactions can be faster since the client-side rendering avoids full page refreshes. Only the necessary components or data are fetched, reducing the server load and improving overall performance.</li></ol><p><strong>Example of CSR:</strong></p><p>Consider a social media feed that displays a list of posts. With CSR, the initial HTML and JavaScript are sent to the client. The JavaScript code then retrieves the post data from an API and dynamically renders the posts in the user’s browser.</p><p>As the user scrolls, additional posts can be fetched asynchronously, allowing for seamless pagination without reloading the entire page.</p><h4>Server-Side Rendering (SSR)</h4><p>SSR, or server-side rendering, is an alternative rendering technique where the server generates a fully rendered HTML page for each request and sends it to the client. In SSR, the server handles both the rendering and data fetching processes, ensuring that the client receives a complete and ready-to-display page.</p><p><strong>🎯Advantages of SSR:</strong></p><ol><li><strong>Improved SEO:</strong> Search engine crawlers can easily parse the fully rendered HTML page, making SSR favorable for websites that heavily rely on organic search traffic. This approach ensures that search engines index the content accurately and comprehensively.</li><li><strong>Initial load performance:</strong> SSR can provide a better initial load performance compared to CSR because the server sends a fully rendered page. This can be particularly beneficial for content-heavy websites or applications where fast page load times are crucial.</li></ol><p><strong>Example of SSR:</strong></p><p>Imagine an e-commerce website with various product listings. With SSR, when a user visits a product page, the server renders the complete HTML, including the product information, images, and relevant data.</p><p>This ensures that the user sees the entire page immediately, regardless of their device’s processing power or internet speed.</p><h4>Choosing the Right Approach</h4><p>The choice between CSR and SSR depends on the specific requirements of your project. Here are some key considerations:</p><ol><li><strong>Application complexity:</strong> CSR is well-suited for dynamic and highly interactive applications, such as single-page applications (SPAs) or real-time collaboration tools. SSR, on the other hand, is a good fit for content-focused websites or applications that require excellent SEO performance.</li><li><strong>Time to first render:</strong> If providing a fast initial page load is a priority, SSR can be advantageous. However, if subsequent interactions and responsiveness are crucial, CSR may be the better choice.</li><li><strong>Development and maintenance: </strong>CSR can be more complex to implement and maintain due to the separation of the client and server logic. SSR simplifies development as it requires fewer JavaScript dependencies and enables easier debugging and testing.</li></ol><p>Client-Side Rendering (CSR) and Server-Side Rendering (SSR) are two prominent rendering techniques in web development, each with its unique benefits. CSR excels in interactivity and performance, while SSR offers advantages in SEO and initial load performance.</p><p>By understanding the differences and considering the requirements of your project, you can make an informed decision on which rendering approach best suits your needs.</p><p>Remember that hybrid approaches, like <a href="https://www.patterns.dev/posts/static-rendering"><strong><em>Static Site Generation (SSG)</em></strong></a> and <a href="https://www.patterns.dev/posts/incremental-static-rendering"><strong><em>Incremental Static Regeneration (ISR)</em></strong></a>, also exist and may provide additional options to explore for optimal rendering strategies in specific scenarios.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2fa0eee50e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Magic of Bloom Filters: A Probabilistic Data Structure for Checking Username Existence]]></title>
            <link>https://ritikchourasiya.medium.com/the-magic-of-bloom-filters-a-probabilistic-data-structure-for-checking-username-existence-6f3aa1f50afa?source=rss-1a8ce9e1f0a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f3aa1f50afa</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ritik-chourasiya]]></category>
            <category><![CDATA[bloom-filter]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Ritik Chourasiya]]></dc:creator>
            <pubDate>Mon, 26 Jun 2023 13:06:11 GMT</pubDate>
            <atom:updated>2023-06-26T13:06:11.271Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YBzT6QaEbPwNUQSuBOjgzw.png" /><figcaption>Bloom filter — Ritik Chourasiya</figcaption></figure><p>Have you ever wondered how computer programs quickly determine if a username already exists? Well, they often use a clever and efficient probabilistic data structure called a Bloom filter.</p><p>In this blog, we will explore Bloom filters, understand their probabilistic nature, and learn how they work by using the example of checking if a username exists or not.</p><h4>What is a Bloom filter?</h4><p>A Bloom filter is a special kind of data structure that allows us to quickly check if an item is a member of a set. It provides us with two possible answers: “definitely not in the set” or “maybe in the set.” However, it is important to note that Bloom filters have a probabilistic nature and can sometimes provide false positives.</p><h4>Why we need bloom filters?</h4><p>Bloom filters are useful in situations where we need to quickly check if an item might exist in a large set, while minimizing the amount of memory required.</p><p>They provide a way to perform approximate existence checks with a trade-off of a small chance of false positives. Here’s an example to illustrate the need for Bloom filters:</p><p>Imagine you have a social media website with millions of registered users. Whenever a new user signs up, you want to ensure that their chosen username is unique and doesn’t already exist in your database.</p><p>One approach might be to store all the usernames in a list and perform a linear search every time a new user signs up. However, with millions of usernames, this can become slow and resource-intensive.</p><p>Here’s where a Bloom filter comes to the rescue. Instead of storing the entire list of usernames, you can create a Bloom filter with a much smaller memory footprint. When a user signs up, you can quickly check if their chosen username might already exist in the set by querying the Bloom filter.</p><p>If the Bloom filter says the username is not in the set, you can allow the user to proceed. However, if the Bloom filter indicates a potential match, you can perform a secondary, more accurate check using a traditional data structure (e.g., a hash table) to confirm the username’s existence.</p><h4>Example: Checking if a username exists</h4><p>Let’s imagine we have a website where users can create accounts with unique usernames. To ensure that no two users have the same username, we can utilize a Bloom filter to quickly check if a username already exists.</p><ol><li><strong>👉 Setting up the Bloom filter:</strong> First, we create an empty Bloom filter with multiple compartments or “buckets.” Each bucket is initially empty and represented by a single bit. The more buckets we have, the lower the chance of false positives, but the larger the Bloom filter becomes in memory.</li><li><strong>👉Adding usernames: </strong>As new users sign up, we hash their usernames using multiple hash functions. Each hash function generates a unique index in the Bloom filter. We then set the corresponding bits at those indexes to 1, indicating the presence of a username.</li><li><strong>👉Checking if a username exists: </strong>Now, let’s say a user named John wants to sign up. Before we allow John to create an account, we perform a lookup in the Bloom filter. We hash John using the same hash functions and check the corresponding bits in the Bloom filter. If any of the bits are not set to 1, we can be certain that John does not exist in the username set. However, if all the bits are set to 1, we have a “maybe” scenario, and further verification is required.</li><li><strong>👉Handling false positives:</strong> One of the interesting aspects of Bloom filters is that they can produce false positives but never false negatives. A false positive occurs when the Bloom filter indicates that a username exists, even though it might not be present in the actual username set. To mitigate this, we usually employ additional data structures, such as a traditional hash table, to store the actual usernames. If the Bloom filter suggests a potential match, we cross-verify the username in the hash table to confirm its existence.</li></ol><h4>Implementation of a Bloom filter in JavaScript</h4><p>we define a BloomFilter class with the specified size and number of hash functions in the constructor. The bitArray is an array of booleans representing the Bloom filter&#39;s bits.</p><p>The add method adds an item (username) to the Bloom filter by calculating the hash values using the getHashValues method and setting the corresponding bits in the bitArray to true.</p><p>The contains method checks if an item (username) might exist in the Bloom filter. It retrieves the hash values using the getHashValues method and checks if all the corresponding bits in the bitArray are true. If any bit is false, it means the item is definitely not in the filter.</p><p>The getHashValues method generates multiple hash values for an item using a simple custom hash function. We append a number (0 to numHashFunctions - 1) to the item to create unique hash values.</p><p>The hash method is a custom hash function that calculates a hash value for a string.</p><p>In the example usage, we create a BloomFilter instance with a size of 100 and two hash functions. We add some usernames (&quot;amy,&quot; &quot;john,&quot; and &quot;emma&quot;) to the Bloom filter using the add method. Finally, we check if the username &quot;john&quot; might exist in the Bloom filter using the contains method and print the appropriate message.</p><pre>class BloomFilter {<br>  constructor(size, numHashFunctions) {<br>    this.size = size;<br>    this.numHashFunctions = numHashFunctions;<br>    this.bitArray = new Array(size).fill(false);<br>  }<br><br>  add(item) {<br>    const hashValues = this.getHashValues(item);<br>    hashValues.forEach((hashValue) =&gt; {<br>      this.bitArray[hashValue] = true;<br>    });<br>  }<br><br>  contains(item) {<br>    const hashValues = this.getHashValues(item);<br>    for (let i = 0; i &lt; hashValues.length; i++) {<br>      if (!this.bitArray[hashValues[i]]) {<br>        return false;<br>      }<br>    }<br>    return true;<br>  }<br><br>  getHashValues(item) {<br>    const hashValues = [];<br>    for (let i = 0; i &lt; this.numHashFunctions; i++) {<br>      const hash = this.hash(`${item}${i}`);<br>      const index = hash % this.size;<br>      hashValues.push(index);<br>    }<br>    return hashValues;<br>  }<br><br>  hash(item) {<br>    let hash = 0;<br>    for (let i = 0; i &lt; item.length; i++) {<br>      hash = (hash &lt;&lt; 5) + hash + item.charCodeAt(i);<br>      hash = hash &amp; hash; // Convert to 32bit integer<br>      hash = Math.abs(hash);<br>    }<br>    return hash;<br>  }<br>}<br><br>// Example usage<br>const bloomFilter = new BloomFilter(100, 2);<br><br>// Adding usernames to the Bloom filter<br>bloomFilter.add(&quot;amy&quot;);<br>bloomFilter.add(&quot;john&quot;);<br>bloomFilter.add(&quot;emma&quot;);<br><br>// Checking if a username exists<br>const username = &quot;john&quot;;<br>if (bloomFilter.contains(username)) {<br>  console.log(`The username &#39;${username}&#39; may exist.`);<br>} else {<br>  console.log(`The username &#39;${username}&#39; does not exist.`);<br>}</pre><p>This custom implementation provides a basic understanding of how a Bloom filter works, but in practice, you might need to consider more robust hash functions, tuning parameters based on expected false positive rates, and other optimizations.</p><h4>Benefits of using a Bloom filter</h4><ol><li><strong>Space efficiency:</strong> Bloom filters require much less memory compared to storing the entire set of usernames.</li><li><strong>Fast membership checks:</strong> Bloom filters provide constant-time lookups, allowing for quick existence checks.</li><li><strong>Reduced resource usage: </strong>By using a Bloom filter as a preliminary check, you can avoid unnecessary database queries, saving processing power and database load.</li></ol><p>Though Bloom filters may occasionally produce false positives (indicating an item is present when it’s not), they offer an efficient and scalable solution for approximate membership queries in large datasets.</p><p>By combining Bloom filters with secondary verification methods, we can achieve a balance between speed and accuracy, making them valuable tools in scenarios where approximate existence checks are acceptable and resource optimization is crucial.</p><h4>Conclusion</h4><p>Bloom filters are powerful probabilistic data structures that enable efficient membership checking. They find wide applications in scenarios where quick existence checks are required, such as determining username availability.</p><p>While Bloom filters provide fast responses, we should be aware that they can occasionally produce false positives. By combining Bloom filters with other data structures, we can achieve higher accuracy and ensure the reliability of our operations.</p><p>Bloom filters continue to be an invaluable tool in computer science, simplifying complex tasks and enhancing performance in various applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f3aa1f50afa" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>