<?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 Varun on Medium]]></title>
        <description><![CDATA[Stories by Varun on Medium]]></description>
        <link>https://medium.com/@vbansal0803?source=rss-96942185b8cf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*k6I19I4Y2yEYPIUX</url>
            <title>Stories by Varun on Medium</title>
            <link>https://medium.com/@vbansal0803?source=rss-96942185b8cf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 03:01:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vbansal0803/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[The Transactional Outbox Pattern: The Secret Behind Reliable Event Publishing in Distributed…]]></title>
            <link>https://medium.com/@vbansal0803/the-transactional-outbox-pattern-the-secret-behind-reliable-event-publishing-in-distributed-59c271c5166a?source=rss-96942185b8cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/59c271c5166a</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[kafka]]></category>
            <dc:creator><![CDATA[Varun]]></dc:creator>
            <pubDate>Tue, 07 Jul 2026 05:41:34 GMT</pubDate>
            <atom:updated>2026-07-07T05:41:34.310Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Transactional Outbox Pattern: The Secret Behind Reliable Event Publishing in Distributed Systems</h3><h4>Learn how modern systems ensure database writes and event publishing never fall out of sync — without using distributed transactions.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A3YzAaJU23xReuOTUD873g.png" /></figure><blockquote><strong><em>“We saved the order, but the payment event was never sent.”</em></strong></blockquote><p>This is one of the most frustrating bugs you’ll encounter when building distributed systems.</p><p>Everything works perfectly during testing.</p><p>Then one day, production decides otherwise.</p><p>A customer places an order.<br>The database commits successfully.<br>Your application crashes milliseconds before publishing the event.</p><p>Now your database says the order exists.<br>But every downstream service thinks it doesn’t.</p><p>Welcome to the world of distributed systems.</p><h3>The Problem Nobody Talks About</h3><p>Imagine you’re building an e-commerce platform.</p><p>When a customer places an order, your service needs to do two things:</p><ol><li>Save the order in the database.</li><li>Publish an OrderCreated event to Kafka, RabbitMQ, or another message broker.</li></ol><p>The code looks innocent enough:</p><pre>saveOrder(order); <br><br>eventBus.publish(new OrderCreated(order.getId()));</pre><p>Looks fine, right?</p><p>Not quite.</p><p>What happens if the database transaction succeeds…</p><p>…but the event broker is temporarily unavailable?</p><p>Now your database contains the order, but no other service knows about it.</p><p>Inventory isn’t updated.<br>Notifications aren’t sent.<br>Analytics miss the order.</p><p>You’ve created inconsistent state.</p><h3>“Easy. Publish First.”</h3><p>Some developers try this instead:</p><pre>eventBus.publish(event);<br><br>saveOrder(order);</pre><p>Now imagine the event is published successfully…</p><p>…and then the database transaction fails.</p><p>Other services receive an event for an order that doesn’t exist.</p><p>Even worse.</p><h3>The Distributed Transaction Trap</h3><p>Your first instinct might be:</p><blockquote><strong><em>“Let’s wrap both operations in one transaction.”</em></strong></blockquote><p>Unfortunately, your database and your message broker are two different systems.</p><p>Keeping them in a single distributed transaction (2PC) is:</p><ul><li>Slow</li><li>Complex</li><li>Difficult to scale</li><li>Unsupported by many modern cloud systems</li></ul><p>Most high-scale companies avoid distributed transactions whenever possible.</p><p>So how do they guarantee reliability?</p><p>This is where the <strong>Transactional Outbox Pattern</strong> comes in.</p><h3>The Transactional Outbox Pattern</h3><p>Instead of writing to <strong>two different systems</strong>, write to <strong>one</strong>.</p><p>Inside the same database transaction:</p><ul><li>Save your business data.</li><li>Save the event into an <strong>Outbox</strong> table.</li></ul><p>That’s it.</p><pre>BEGIN TRANSACTION<br>Insert Order<br>Insert Outbox Event<br>COMMIT</pre><p>Since both writes happen in the same transaction:</p><ul><li>Either both succeed</li><li>Or both fail</li></ul><p>No inconsistent state.</p><h3>What Does the Outbox Look Like?</h3><p>A simple table works well:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*GeLYt3FN5TZTeN-ug7CIDg.png" /></figure><p>Notice something interesting.</p><p>We’re not talking to Kafka.</p><p>We’re simply storing events alongside our business data.</p><h3>But How Does Kafka Get the Event?</h3><p>That’s the clever part.</p><p>A separate process continuously scans the Outbox table.</p><pre>while(true){    <br>  events = fetchPendingEvents();<br>  publish(events);<br>      markAsPublished();<br>}</pre><p>The relay is responsible for:</p><ul><li>Reading pending events</li><li>Publishing them</li><li>Marking them as completed</li></ul><p>Your business transaction stays simple.</p><h3>Visualising the Flow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*qnhr675ZL18XLW68CMuz4Q.png" /></figure><p>Everything important happens after the database commit.</p><h3>What If Publishing Fails?</h3><p>Suppose Kafka is down.</p><p>The relay tries publishing.</p><p>It fails.</p><p>Nothing is lost because the event is still sitting safely in the Outbox table.</p><p>The relay simply retries later.</p><p>Eventually Kafka comes back online.</p><p>The event gets delivered.</p><p>This makes the system resilient to temporary failures.</p><h3>What About Duplicate Events?</h3><p>Here’s another challenge.</p><p>Imagine this sequence:</p><ol><li>Relay publishes the event.</li><li>Kafka receives it.</li><li>Relay crashes before updating the Outbox row.</li></ol><p>When the relay restarts…</p><p>It publishes the same event again.</p><p>Duplicates happen.</p><p>That’s expected.</p><p>The Outbox Pattern guarantees <strong>at-least-once delivery</strong>, not exactly-once delivery.</p><p>Consumers should therefore be <strong>idempotent</strong>.</p><p>For example:</p><ul><li>Ignore duplicate event IDs.</li><li>Track processed message IDs.</li><li>Make updates repeatable without changing the final outcome.</li></ul><p>Exactly-once delivery is far more expensive than most systems actually need.</p><h3>Why This Pattern Scales</h3><p>The beauty of the Outbox Pattern is that your application only depends on one system during the request life-cycle.</p><p>The database.</p><p>Message brokers become asynchronous.</p><p>If Kafka experiences a temporary outage:</p><ul><li>Orders continue getting saved.</li><li>Events accumulate in the Outbox.</li><li>Publishing resumes automatically when Kafka recovers.</li></ul><p>Your users never notice.</p><h3>Real-World Usage</h3><p>This pattern is widely used in event-driven architectures because it provides reliable messaging without distributed transactions.</p><p>It’s commonly paired with technologies such as:</p><ul><li>Kafka</li><li>RabbitMQ</li><li>Amazon SQS</li><li>Google Pub/Sub</li><li>Azure Service Bus</li></ul><p>Many engineering teams implement the relay themselves, while others rely on tools like <strong>Debezium</strong>, which reads database changes using Change Data Capture (CDC) and streams Outbox events directly into Kafka.</p><h3>Advantages</h3><ul><li>No distributed transactions</li><li>Reliable event publishing</li><li>Automatic retries</li><li>Better fault tolerance</li><li>Simpler application code</li><li>Works with almost any message broker</li></ul><h3>Trade-offs</h3><p>Like every engineering pattern, it isn’t free.</p><p>You’ll need to think about:</p><ul><li>Cleaning old Outbox records</li><li>Building or operating the relay service</li><li>Handling duplicate messages</li><li>Monitoring retry failures</li><li>Back pressure if the broker stays unavailable for a long time</li></ul><p>The complexity shifts from your business logic to your infrastructure — but in return, you gain much stronger reliability.</p><h3>When Should You Use It?</h3><p>The Transactional Outbox Pattern is a great fit when:</p><ul><li>You use microservices.</li><li>You publish domain events.</li><li>You rely on asynchronous communication.</li><li>Data consistency matters.</li><li>Lost events are unacceptable.</li></ul><p>For a simple CRUD application that never emits events, it’s usually unnecessary.</p><h3>Final Thoughts</h3><p>Distributed systems don’t usually fail because of complex algorithms.</p><p>They fail in the tiny gap between two successful operations.</p><p>Saving data and publishing an event may take only a few milliseconds, but that’s exactly where bugs, crashes, and network failures love to hide.</p><p>The Transactional Outbox Pattern closes that gap.</p><p>Instead of hoping two systems succeed together, it leverages the one thing databases already do exceptionally well: <strong>atomic transactions</strong>.</p><p>That’s why many large-scale systems — from e-commerce platforms to fintech applications and ride-sharing services — use this pattern to build reliable, event-driven architectures.</p><p>The next time you’re tempted to write:</p><pre>save();<br><br>publish();</pre><p>Ask yourself:</p><p><strong>What happens if the application crashes between those two lines?</strong></p><p>If the answer makes you uncomfortable, it might be time to introduce an Outbox.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59c271c5166a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Headless, API-First, and Decoupled Architectures: A Professional Guide]]></title>
            <link>https://medium.com/@vbansal0803/headless-api-first-and-decoupled-architectures-a-professional-guide-f2775e450279?source=rss-96942185b8cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2775e450279</guid>
            <category><![CDATA[decoupled-architecture]]></category>
            <category><![CDATA[headless-cms-explained]]></category>
            <category><![CDATA[headless-architecture]]></category>
            <category><![CDATA[modern-web-architecture]]></category>
            <category><![CDATA[api-first-architecture]]></category>
            <dc:creator><![CDATA[Varun]]></dc:creator>
            <pubDate>Wed, 21 Jan 2026 04:59:22 GMT</pubDate>
            <atom:updated>2026-01-21T04:59:22.906Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Modern web applications are no longer limited to a single website. Today’s products often span web apps, mobile apps, smart devices, and third-party integrations. Traditional monolithic architectures struggle to meet these demands due to tight coupling, limited scalability, and slow development cycles.</p><p>This is where <strong>Headless</strong>, <strong>API-First</strong>, and <strong>Decoupled architectures</strong> come in. Together, they form the foundation of modern, scalable, and future-ready web systems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t78rEvsfg6Rrj9-fTo6MNA.jpeg" /></figure><h3>1. Traditional Monolithic Architecture (Quick Recap)</h3><p>In a monolithic system, frontend, backend, and content management live in a single codebase.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/261/1*YpSYDPAxx8Pfep02DoB3_Q.png" /></figure><h3>Limitations</h3><ul><li>Tight coupling between UI and business logic</li><li>Difficult to scale individual components</li><li>Content cannot be easily reused across platforms</li></ul><h3>2. Decoupled Architecture</h3><p><strong>Decoupled architecture</strong> is a design approach where the frontend (presentation layer) and backend (data + business logic) are built, deployed, and maintained as completely separate systems. Their only point of interaction is through well-defined APIs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/297/1*NgGxJusEkC-iuJLvn6kNQw.png" /></figure><h3>Theoretical Perspective</h3><p>From a software engineering standpoint, decoupling is rooted in the principle of <strong>separation of concerns</strong>. Each layer has a single responsibility:</p><ul><li><strong>Frontend</strong>: User experience and presentation</li><li><strong>Backend</strong>: Business rules, data processing, and security</li></ul><p>Loose coupling reduces system fragility. Changes in one layer do not cascade into failures in another, which dramatically improves maintainability.</p><h3>Key Characteristics</h3><ul><li>Independent deployments and release cycles</li><li>Easier refactoring and technology upgrades</li><li>Clear API contracts act as system boundaries</li></ul><h3>3. Headless Architecture</h3><p>A <strong>headless architecture</strong> takes decoupling one step further by completely removing the frontend layer from the backend system. The backend exposes content and functionality exclusively via APIs, without any built-in rendering or templating.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/305/1*Erllus2iMblWIAWKRnoVMQ.png" /></figure><h3>Conceptual Explanation</h3><p>The term <em>headless</em> comes from the idea that the system has no predefined “head” (<strong>UI</strong>). Instead, developers are free to build multiple heads that consume the same backend.</p><p>In theory, this enables <strong>content atomization</strong>, where content is stored in small, structured pieces rather than fixed pages. These pieces can be recombined dynamically depending on platform, screen size, or user context.</p><h3>Headless CMS Examples</h3><ul><li>Strapi</li><li>Contentful</li><li>Sanity</li></ul><h3>Why Headless Matters</h3><ul><li>Eliminates frontend constraints imposed by traditional CMSs</li><li>Improves content governance and reuse</li><li>Aligns well with omnichannel and microservices strategies</li></ul><h3>4. API-First Architecture</h3><p>In an <strong>API-First architecture</strong>, APIs are not an afterthought — they are the primary product of the backend system. The entire application ecosystem is designed around API consumption.</p><h3>Theoretical Foundation</h3><p>API-First design follows <strong>contract-driven development</strong>, where the API schema (<strong>OpenAPI</strong>, <strong>GraphQL</strong> schema) is defined before implementation. This creates a shared understanding between frontend, backend, and third-party consumers.</p><h3>Core Principles</h3><ul><li>APIs are versioned and backward-compatible</li><li>Documentation is generated from the API contract</li><li>APIs are reusable, testable, and platform-agnostic</li></ul><h3>REST vs GraphQL (High-Level)</h3><ul><li><strong>REST</strong>: Resource-oriented, stateless, predictable</li><li><strong>GraphQL</strong>: Query-based, flexible data fetching, reduced over-fetching</li></ul><p>API-First systems are inherently future-proof because new clients can be added without modifying backend logic.</p><h3>5. How These Architectures Work Together</h3><p>In modern systems, headless, API-first, and decoupled principles are often combined:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*CgYR6RNu63peNFpTSal_Xg.png" /></figure><p>This setup enables true multi-platform delivery with minimal duplication.</p><h3>6. Code Example: API-First Backend (Node.js)</h3><p>Below is a simple REST API built using Express:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2DnixeJJy8_q7tio0ogd1w.png" /></figure><p>This API can be consumed by any frontend or client.</p><h3>7. Code Example: Decoupled Frontend (Next.js)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bTt22ta5p7Vycdl8cf_nhg.png" /></figure><p>The frontend knows nothing about how the backend is implemented — only the API contract matters.</p><h3>8. Benefits of Headless, API-First, and Decoupled Architectures</h3><h3>Architectural Benefits</h3><ul><li><strong>Scalability</strong>: Each layer can scale independently based on load</li><li><strong>Resilience</strong>: Failures are isolated, reducing blast radius</li><li><strong>Performance</strong>: Frontends can leverage CDN caching, SSG, and edge rendering</li></ul><h3>Organizational Benefits</h3><ul><li>Parallel development across teams</li><li>Clear ownership boundaries</li><li>Faster on-boarding for new developers</li></ul><h3>Business Benefits</h3><ul><li>Faster time-to-market</li><li>Easier experimentation with new platforms</li><li>Long-term cost efficiency despite higher initial investment</li></ul><h3>9. Challenges and Trade-Offs</h3><p>Despite their advantages, these architectures introduce real-world trade-offs that must be acknowledged.</p><h3>Technical Challenges</h3><ul><li>Increased system complexity</li><li>More infrastructure components to manage</li><li>Need for strong API governance and monitoring</li></ul><h3>Operational Challenges</h3><ul><li>Requires mature DevOps practices</li><li>Debugging across distributed systems can be harder</li><li>Authentication and authorization must be centralized</li></ul><h3>Strategic Considerations</h3><p>These architectures are most effective when long-term scalability and multi-platform support outweigh the simplicity of monolithic systems.</p><h3>10. Popular Technology Stack</h3><ul><li><strong>Frontend</strong>: React, Next.js, Vue, Svelte</li><li><strong>Backend</strong>: Node.js, NestJS, Django, Spring Boot</li><li><strong>CMS</strong>: Strapi, Contentful, Sanity</li><li><strong>APIs</strong>: REST, GraphQL</li></ul><h3>11. When Should You Use This Architecture?</h3><h3>Recommended For</h3><ul><li>SaaS platforms</li><li>E-commerce applications</li><li>Products targeting multiple platforms</li></ul><h3>Not Ideal For</h3><ul><li>Very small websites</li><li>Simple blogs with no expansion plans</li></ul><h3>Conclusion</h3><p>Headless, API-first, and decoupled architectures are not trends — they are responses to real scalability and flexibility challenges in modern web development. When applied correctly, they enable teams to build fast, maintainable, and future-ready systems.</p><p>Understanding these concepts is essential for developers working on modern web platforms.</p><p><strong>Happy coding! 😊</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2775e450279" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Over-Abstraction Can Kill Your Code-base]]></title>
            <link>https://medium.com/@vbansal0803/why-over-abstraction-can-kill-your-code-base-1e6911771a56?source=rss-96942185b8cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e6911771a56</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[reuseable]]></category>
            <category><![CDATA[abstraction]]></category>
            <category><![CDATA[generalization]]></category>
            <category><![CDATA[problem-solving]]></category>
            <dc:creator><![CDATA[Varun]]></dc:creator>
            <pubDate>Thu, 03 Jul 2025 04:24:47 GMT</pubDate>
            <atom:updated>2025-07-03T04:24:47.352Z</atom:updated>
            <content:encoded><![CDATA[<h4>How premature generalisation creates more problems than it solves.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ExUgp4KEMmySi8qgnAYq1A.png" /><figcaption>Photos from https://frontendatscale.com/</figcaption></figure><blockquote><strong>“We should make it reusable.”<br>“Let’s abstract it for future use.”</strong><br><strong>“We might need this later.”</strong></blockquote><p>You’ve heard these phrases before. They often come from well-intentioned developers trying to write “clean” or “scalable” code. But more often than not, this mindset leads to <strong>over-abstraction</strong> — a dangerous path that can quietly erode your codebase.</p><p>In this post, I want to explore why going too generic, too early, is a trap — especially for new tasks or developers — and how you can avoid it.</p><h3>🚧 What Is Over-Abstraction?</h3><p>Over-abstraction is the act of <strong>creating overly generic solutions before there’s a clear, repeated need</strong>. It usually shows up as:</p><ul><li>Utility functions with 6+ config flags.</li><li>Abstract base classes with 2 levels of inheritance.</li><li>Generic components that handle every use case but are hard to understand.</li><li>Indirect logic that’s spread across “helper,” “lib,” and “core” files.</li></ul><p>On paper, it looks smart — you’re “thinking ahead.” But in practice, it often becomes a <strong>maze</strong> for anyone trying to build, debug, or maintain the system.</p><h3>🧠 The Good Intentions Behind It</h3><p>The goal of abstraction is valid: reduce repetition, increase reuse, and make the codebase more scalable. But here’s the catch:</p><blockquote><strong><em>Abstraction is a byproduct of understanding, not a shortcut around it.</em></strong></blockquote><p>When you abstract too soon, you’re not basing it on <em>real</em> patterns — just on assumptions. And assumptions make for fragile foundations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M5DskE3UubIurHBGe4N6jA.png" /><figcaption>Photos from https://frontendatscale.com/</figcaption></figure><h3>⚠️ Why Over-Abstraction Is Dangerous</h3><h3>1. Kills Clarity</h3><p>New developers can’t follow what’s going on because nothing is concrete. The real logic is buried under layers of indirection. Instead of understanding <em>how</em> the system works, they have to reverse-engineer a generic engine.</p><h3>2. Hurts Debugging</h3><p>Every bug now requires diving through layers of reusable logic. Good luck tracing a small issue in a deeply abstracted handler that dynamically builds logic based on five flags and a strategy map.</p><h3>3. Slows Down New Features</h3><p>Want to add a new behavior? Better pray it fits into the existing abstraction. If not, you’re stuck either:</p><ul><li>Hacking around it with exceptions and flags, or</li><li>Rewriting the whole layer.</li></ul><p>Both are expensive.</p><h3>4. Discourages Learning</h3><p>Over-generic systems intimidate new developers. They feel they must understand <em>everything</em> before touching <em>anything</em> — leading to hesitation and fear of breaking things.</p><h3>5. The YAGNI Principle</h3><blockquote><strong><em>You Aren’t Gonna Need It.</em></strong><em><br> Most of the time, that “reusable” code you wrote? It’s never reused. You’ve wasted hours generalizing a one-off solution, introducing complexity that wasn’t needed in the first place.</em></blockquote><h3>🧪 A Quick Example</h3><p>Let’s say you need to format user names. You write:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*079BedwYqWrDE9vWGoWeSQ.png" /></figure><p>Seems fine, right?</p><p>Now imagine the next dev wants to handle middle names, suffixes, different locales, fallbacks, and nickname preferences. Soon, you’re juggling 10 flags, and no one knows what the function <em>really</em> does anymore.</p><p>Compare that to just writing a few separate, clearly named functions like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G4q7CU1euGEo2OLXvxgrdg.png" /></figure><p>Yes, it’s repetition. But it’s <strong>readable, predictable, and safe</strong>.</p><h3>✅ When Should You Abstract?</h3><p>Here’s a good rule:</p><blockquote><strong><em>Concrete first. Abstract after.</em></strong></blockquote><p>Only abstract when:</p><ul><li>You’ve seen the same pattern <strong>2–3 times</strong>.</li><li>The abstraction is <strong>clear and limited</strong> in scope.</li><li>It <strong>simplifies</strong> rather than complicates your system.</li></ul><p>Until then: <strong>write it plainly.</strong> Keep it specific. Focus on clarity and confidence, not cleverness.</p><h3>🧭 Better Principles to Follow</h3><p>Instead of “make it reusable,” think:</p><ul><li><strong>KISS</strong> — Keep it simple, stupid.</li><li><strong>YAGNI</strong> — You aren’t gonna need it.</li><li><strong>Do the simplest thing that works.</strong></li><li><strong>Build for today. Refactor for tomorrow.</strong></li></ul><p>These aren’t excuses to write bad code — they’re reminders to <strong>prioritize learning, understanding, and correctness</strong> over abstraction for abstraction’s sake.</p><h3>💬 Final Thoughts</h3><p>The best code isn’t the most abstract. It’s the most <strong>understandable</strong>. Especially in early stages or on small teams, <strong>concrete, specific, working code beats overly generic systems every time</strong>.</p><p>So the next time you’re tempted to write a reusable helper, ask yourself:</p><blockquote>“Do I really need this to be generic? Or am I just trying to be clever?”</blockquote><p>Clarity scales. Premature abstraction doesn’t.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e6911771a56" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Understanding Proxies: Forward Proxy vs Reverse Proxy]]></title>
            <link>https://medium.com/@vbansal0803/understanding-proxies-forward-proxy-vs-reverse-proxy-964e9c9da23d?source=rss-96942185b8cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/964e9c9da23d</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[proxy]]></category>
            <category><![CDATA[reverse-proxy]]></category>
            <category><![CDATA[servers]]></category>
            <category><![CDATA[proxy-server]]></category>
            <dc:creator><![CDATA[Varun]]></dc:creator>
            <pubDate>Wed, 28 May 2025 04:23:32 GMT</pubDate>
            <atom:updated>2025-05-28T04:25:23.512Z</atom:updated>
            <content:encoded><![CDATA[<p>In the digital world, where data constantly moves across networks, <strong>proxies</strong> act as crucial intermediaries — improving performance, enhancing privacy, and boosting security. But not all proxies are the same. Two of the most important types — <strong>Forward Proxy</strong> and <strong>Reverse Proxy</strong> — often get confused.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_wVTxoaR0F0S7gGC.jpg" /></figure><p>In this post, we’ll break down:</p><ul><li>What a proxy is</li><li>The difference between <strong>forward</strong> and <strong>reverse</strong> proxies</li><li>Real-world use cases and examples</li><li>How to decide which one to use</li></ul><h3>🔍 What Is a Proxy?</h3><p>At its core, a <strong>proxy</strong> is a server that acts as a gateway between a client (like your computer) and the internet. Instead of the client talking directly to a web server, the proxy handles communication on its behalf.</p><p>Proxies help with:</p><ul><li>Anonymizing client requests</li><li>Filtering or blocking content</li><li>Caching data for performance</li><li>Load balancing and security enhancement</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QBJcDJ3ZcDunMSIIu7SCBg.png" /></figure><h3>🧭 Forward Proxy — The Client’s Middleman</h3><p>A <strong>forward proxy</strong> is positioned in front of the <strong>client</strong>. It acts on the client’s behalf to fetch data from the internet.</p><h4>🔁 How It Works:</h4><ol><li>The client sends a request to the proxy.</li><li>The proxy forwards that request to the target server.</li><li>The server responds to the proxy.</li><li>The proxy sends the response back to the client.</li></ol><h4>✅ Common Use Cases:</h4><ul><li>Bypassing geo-blocked content (e.g., streaming sites)</li><li>Enforcing content filtering in schools or workplaces</li><li>Hiding client IP addresses</li><li>Caching repeated requests to speed up browsing</li></ul><blockquote><strong><em>Example tools:</em></strong><em> Squid, CCProxy, Tor</em></blockquote><h3>🛡️ Reverse Proxy — The Server’s Bodyguard</h3><p>A <strong>reverse proxy</strong> is placed in front of the <strong>server</strong>. It receives requests from clients and forwards them to the appropriate internal server.</p><h4>🔁 How It Works:</h4><ol><li>The client sends a request to the reverse proxy.</li><li>The proxy forwards the request to one of many backend servers.</li><li>The selected server processes the request and replies.</li><li>The proxy sends the response back to the client.</li></ol><h4>✅ Common Use Cases:</h4><ul><li>Load balancing across multiple backend servers</li><li>Protecting internal servers by hiding their IPs</li><li>SSL termination (handling HTTPS encryption)</li><li>Caching static content to reduce load</li></ul><blockquote><strong><em>Example tools:</em></strong><em> NGINX, HAProxy, Apache (mod_proxy)</em></blockquote><h3>🆚 Key Differences at a Glance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*gq7oRjDJAvFnrxdr3y9vfg.png" /></figure><h3>🔄 Real-World Analogy</h3><ul><li>A <strong>Forward Proxy</strong> is like a <strong>VPN service</strong>: you use it to go online anonymously or bypass restrictions.</li><li>A <strong>Reverse Proxy</strong> is like a <strong>receptionist</strong> in a company: visitors (clients) talk to the receptionist (proxy), who forwards them to the right employee (server).</li></ul><h3>🎯 When to Use Which?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*b9rrq76uoqCqfMEHy4w2IQ.png" /></figure><h3>🧠 Final Thoughts</h3><p>Both <strong>forward proxies</strong> and <strong>reverse proxies</strong> serve as intermediaries — but they solve very different problems.</p><ul><li><strong>Forward proxies</strong> help clients access external resources securely or anonymously.</li><li><strong>Reverse proxies</strong> help servers handle incoming traffic efficiently, securely, and at scale.</li></ul><p>Whether you’re designing a secure infrastructure, optimizing for performance, or controlling access — understanding the type of proxy you need is critical.</p><p>If you found this helpful, feel free to share or leave a comment! Want more posts like this on web architecture or backend strategies? Let me know 🙌</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=964e9c9da23d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Monolithic vs  Microservices Architecture: What’s the Difference?]]></title>
            <link>https://medium.com/@vbansal0803/monolithic-vs-microservices-architecture-whats-the-difference-6a616cd33465?source=rss-96942185b8cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a616cd33465</guid>
            <category><![CDATA[devops-architecture]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[microservice-architecture]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[monolithic-architecture]]></category>
            <dc:creator><![CDATA[Varun]]></dc:creator>
            <pubDate>Tue, 08 Apr 2025 06:04:23 GMT</pubDate>
            <atom:updated>2025-04-08T06:04:23.425Z</atom:updated>
            <content:encoded><![CDATA[<p>When you’re starting a new software project or scaling an existing one, one of the most crucial decisions you’ll make is choosing the right <strong>architecture</strong>. Two popular approaches dominate the landscape today: <strong>Monolithic</strong> and <strong>Microservices</strong> architectures. But what do they mean, and how do they affect the way your application works?</p><p>Let’s break it down in simple terms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oKseoGIIdVdEem2MUk5TZQ.png" /></figure><h3>🔍 What is Monolithic Architecture?</h3><p>A <strong>monolithic application</strong> is built as a single, unified unit. All the components like authentication, product management, order processing, etc., are combined in one big codebase and are tightly coupled.</p><h3>🚪 Imagine This:</h3><p>Think of it as a <strong>single-room apartment</strong> where your bedroom, kitchen, and living room are all in one place. Easy to build and manage in the beginning, but as things get crowded, it becomes hard to separate and upgrade individual parts.</p><h3>✅ Pros:</h3><ul><li>Easy to develop at the beginning</li><li>Simpler to test and deploy</li><li>Fewer moving parts</li></ul><h3>❌ Cons:</h3><ul><li>Hard to scale specific components</li><li>Slower development as the codebase grows</li><li>A single bug can impact the whole app</li><li>Difficult to adopt new technologies</li></ul><h3>🧩 What is Microservices Architecture?</h3><p><strong>Microservices architecture</strong> breaks the application into smaller, independent services. Each service handles a specific business functionality — like user authentication, payment processing, or inventory tracking — and can be developed, deployed, and scaled independently.</p><h3>🏘 Think of it Like:</h3><p>A <strong>neighbourhood</strong> of small houses (services), each with its own entrance, plumbing, and electricity. If one house has an issue, the rest remain unaffected.</p><h3>✅ Pros:</h3><ul><li>Easier to scale and maintain</li><li>Faster development with independent teams</li><li>Fault isolation — one failure doesn’t bring down the whole system</li><li>Flexibility in using different technologies for different services</li></ul><h3>❌ Cons:</h3><ul><li>More complex infrastructure</li><li>Communication between services can fail</li><li>Requires strong DevOps and monitoring setup</li><li>Higher initial learning curve</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G1btVqqUdqSOr8VqUUODGQ.png" /></figure><h3>⚖️ Monolithic vs Microservices: A Quick Comparison</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*Wn7wr-Lnos_PBirPx4wIfw.png" /></figure><h3>🧠 When to Use What?</h3><h3>Use Monolithic When:</h3><ul><li>You’re building a small, simple app</li><li>You want to get to MVP quickly</li><li>Your team is small</li></ul><h3>Use Microservices When:</h3><ul><li>Your app is growing and has many features</li><li>You have a larger dev team</li><li>You need to scale parts independently</li><li>You’re ready to invest in DevOps and monitoring</li></ul><h3>🚀 Final Thoughts</h3><p>Both monolithic and microservices architectures have their place. While monoliths offer simplicity and speed for small applications, microservices provide flexibility and scalability for larger, complex systems.</p><p>Understanding the <strong>trade-offs</strong> between them helps you choose the right path for your project’s success.</p><p>Want to see a real-world example of setting up microservices with Node.js? Drop a comment and stay tuned for my next blog! 😉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a616cd33465" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Ultimate Guide for Beginners to Learn WebSockets with Node.js]]></title>
            <link>https://medium.com/@vbansal0803/the-ultimate-guide-for-beginners-to-learn-websockets-with-node-js-1801613876d9?source=rss-96942185b8cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/1801613876d9</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[websocket-server]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Varun]]></dc:creator>
            <pubDate>Thu, 23 Jan 2025 04:30:19 GMT</pubDate>
            <atom:updated>2025-01-23T04:30:19.600Z</atom:updated>
            <content:encoded><![CDATA[<p>In the modern world of real-time applications, WebSockets have become a vital tool for developers looking to build interactive, live, and seamless user experiences. From chat applications to stock market tickers, WebSockets enable persistent, bidirectional communication between the server and the client. If you’re new to WebSockets and Node.js, this guide will walk you through everything you need to know to get started.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*U8kOTD1ZcFB_X-ii" /></figure><h3>What are WebSockets?</h3><p>WebSockets are a protocol that allows for full-duplex communication over a single TCP connection. Unlike HTTP, which is stateless and requires a new connection for each request, WebSockets maintain a constant connection, making them ideal for applications that require low latency and real-time data updates.</p><h3>Key Features of WebSockets:</h3><ul><li><strong>Persistent Connection</strong>: Once established, the connection remains open, eliminating the overhead of repeated handshakes.</li><li><strong>Bidirectional Communication</strong>: Both the client and server can send data at any time.</li><li><strong>Low Latency</strong>: Ideal for real-time applications like gaming, chat, or live notifications.</li><li><strong>Event-Driven</strong>: Communicates via events, allowing for efficient handling of messages.</li></ul><h3>Why Use Node.js for WebSockets?</h3><p>Node.js is a perfect match for WebSockets because of its event-driven, non-blocking architecture. With libraries like ws and Socket.IO, implementing WebSockets in Node.js is straightforward and efficient.</p><h3>Advantages of Using Node.js:</h3><ol><li><strong>Asynchronous Nature</strong>: Handles multiple WebSocket connections efficiently.</li><li><strong>Vast Ecosystem</strong>: Popular libraries like ws and Socket.IO simplify WebSocket implementation.</li><li><strong>JavaScript Everywhere</strong>: Use the same language for both frontend and backend.</li></ol><h3>Setting Up WebSockets in Node.js</h3><h4>Step 1: Setting Up a Basic Node.js Project</h4><ul><li><strong>Install Node.js</strong>: Ensure you have Node.js installed. Download it from <a href="https://nodejs.org/">Node.js Official Site</a>.</li><li><strong>Create a Project Directory</strong>:</li></ul><pre>mkdir websocket-demo <br>cd websocket-demo <br>npm init -y</pre><ul><li><strong>Install Dependencies</strong>: We’ll use the ws library, a lightweight WebSocket implementation for Node.js.</li></ul><pre>npm install ws</pre><h4>Step 2: Writing Your First WebSocket Server</h4><p>Create a file called server.js and add the following code:</p><pre>const WebSocket = require(&#39;ws&#39;);<br><br>// Create a WebSocket server<br>const server = new WebSocket.Server({ port: 8080 });<br>console.log(&#39;WebSocket server is running on ws://localhost:8080&#39;);<br>// Handle connection events<br>server.on(&#39;connection&#39;, (socket) =&gt; {<br>  console.log(&#39;Client connected&#39;);<br>  // Handle incoming messages<br>  socket.on(&#39;message&#39;, (message) =&gt; {<br>    console.log(`Received: ${message}`);<br>    // Echo the message back to the client<br>    socket.send(`You said: ${message}`);<br>  });<br>  // Handle connection closure<br>  socket.on(&#39;close&#39;, () =&gt; {<br>    console.log(&#39;Client disconnected&#39;);<br>  });<br>});</pre><p>Run the server using:</p><pre>node server.js</pre><p>Your WebSocket server is now running on ws://localhost:8080.</p><h3>Step 3: Creating a Simple WebSocket Client</h3><p>Create an index.html file to act as the client:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>  &lt;meta charset=&quot;UTF-8&quot;&gt;<br>  &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>  &lt;title&gt;WebSocket Client&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>  &lt;h1&gt;WebSocket Client&lt;/h1&gt;<br>  &lt;input id=&quot;message&quot; type=&quot;text&quot; placeholder=&quot;Type a message...&quot;&gt;<br>  &lt;button onclick=&quot;sendMessage()&quot;&gt;Send&lt;/button&gt;<br>  &lt;div id=&quot;response&quot;&gt;&lt;/div&gt;<br>&lt;script&gt;<br>    const socket = new WebSocket(&#39;ws://localhost:8080&#39;);<br>    // Listen for messages from the server<br>    socket.onmessage = (event) =&gt; {<br>      document.getElementById(&#39;response&#39;).innerText = event.data;<br>    };<br>    // Send a message to the server<br>    function sendMessage() {<br>      const message = document.getElementById(&#39;message&#39;).value;<br>      socket.send(message);<br>    }<br>  &lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>Open index.html in your browser, type a message, and see the server respond in real time.</p><h3>Advanced WebSocket Features with Node.js</h3><p>Once you’re comfortable with the basics, you can explore more advanced features:</p><h4>1. Broadcasting Messages</h4><p>Allow the server to send messages to all connected clients:</p><pre>server.on(&#39;connection&#39;, (socket) =&gt; {<br>  socket.on(&#39;message&#39;, (message) =&gt; {<br>    server.clients.forEach((client) =&gt; {<br>      if (client.readyState === WebSocket.OPEN) {<br>        client.send(message);<br>      }<br>    });<br>  });<br>});</pre><h4>2. Authentication</h4><p>Secure your WebSocket connection by implementing token-based authentication. For example, use JWT to validate clients before establishing a connection.</p><h4>3. Handling Errors</h4><p>Add error handling to ensure your application remains stable:</p><pre>socket.on(&#39;error&#39;, (error) =&gt; {<br>  console.error(&#39;WebSocket error:&#39;, error);<br>});</pre><h4>4. Scaling WebSocket Servers</h4><p>Use libraries like Cluster or tools like Redis for pub/sub to manage WebSocket connections across multiple servers.</p><h3>Best Practices for WebSocket Development</h3><ol><li><strong>Use Secure WebSockets (wss://)</strong>: Always encrypt your WebSocket connections in production.</li><li><strong>Set Connection Limits</strong>: Avoid overloading your server by limiting the number of concurrent connections.</li><li><strong>Monitor Connection Health</strong>: Implement heartbeats to detect and close inactive connections.</li><li><strong>Optimize Data</strong>: Minimize the size of messages to reduce bandwidth usage.</li><li><strong>Graceful Shutdowns</strong>: Ensure all connections are closed properly during server shutdown.</li></ol><h3>Conclusion</h3><p>WebSockets, combined with Node.js, are a powerful combination for building real-time applications. Whether you’re working on a live chat, collaborative tool, or real-time notifications, the flexibility and efficiency of WebSockets make them an essential tool in your development toolkit. By following this guide, you have all the foundational knowledge to start building WebSocket-based applications with Node.js.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1801613876d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Install MongoDB and MongoDB Compass as a Service on Ubuntu]]></title>
            <link>https://medium.com/@vbansal0803/how-to-install-mongodb-and-mongodb-compass-as-a-service-on-ubuntu-637c4b471f3d?source=rss-96942185b8cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/637c4b471f3d</guid>
            <dc:creator><![CDATA[Varun]]></dc:creator>
            <pubDate>Sat, 04 Jan 2025 04:39:52 GMT</pubDate>
            <atom:updated>2025-01-04T04:39:52.587Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1-4pGiZBsqNAci5aqD8uXg.png" /></figure><p>MongoDB is a popular NoSQL database known for its scalability and flexibility. MongoDB Compass, on the other hand, is a GUI tool that simplifies database management and querying. This guide will walk you through the process of installing MongoDB and MongoDB Compass on an Ubuntu system, and setting up MongoDB as a service.</p><h3>Step 1: Install MongoDB on Ubuntu</h3><h4>1. Import the Public Key for MongoDB</h4><p>First, add the MongoDB public key to your system:</p><pre>wget -qO - https://www.mongodb.org/static/pgp/server-6.0.asc | sudo apt-key add -</pre><h4>2. Create a List File for MongoDB</h4><p>Add the MongoDB repository to your system’s package manager:</p><pre>echo &quot;deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu $(lsb_release -cs)/mongodb-org/6.0 multiverse&quot; | sudo tee /etc/apt/sources.list.d/mongodb-org-6.0.list</pre><h4>3. Update the Package List</h4><p>Update your package list to include the MongoDB repository:</p><pre>sudo apt update</pre><h4>4. Install MongoDB</h4><p>Install the MongoDB package:</p><pre>sudo apt install -y mongodb-org</pre><h4>5. Start and Enable MongoDB as a Service</h4><p>Ensure that MongoDB starts automatically on boot:</p><pre>sudo systemctl start mongod<br>sudo systemctl enable mongod</pre><h4>6. Check MongoDB Service Status</h4><p>Verify that MongoDB is running:</p><pre>sudo systemctl status mongod</pre><p>If everything is set up correctly, you should see a message indicating that MongoDB is active and running.</p><h3>Step 2: Install MongoDB Compass</h3><h4>1. Download MongoDB Compass</h4><p>Download the latest version of MongoDB Compass from the <a href="https://www.mongodb.com/try/download/compass">official website</a>. Alternatively, you can use the terminal:</p><pre>wget https://downloads.mongodb.com/compass/mongodb-compass_&lt;version&gt;_amd64.deb</pre><p>Replace &lt;version&gt; with the version number of the downloaded package.</p><h4>2. Install the Downloaded .deb File</h4><p>Use the following command to install MongoDB Compass:</p><pre>sudo dpkg -i mongodb-compass_&lt;version&gt;_amd64.deb</pre><h4>3. Fix Dependencies (if needed)</h4><p>If the installation reports any missing dependencies, run:</p><pre>sudo apt --fix-broken install</pre><h4>4. Launch MongoDB Compass</h4><p>Start MongoDB Compass using the terminal:</p><pre>mongodb-compass</pre><p>Alternatively, you can search for “MongoDB Compass” in your system’s application menu.</p><h3>Step 3: Verify the Installation</h3><h4>Verify MongoDB Installation</h4><ul><li>Open the MongoDB shell:</li></ul><pre>mongosh</pre><ul><li>Run a test query to check the databases:</li></ul><pre>show dbs;</pre><p>If MongoDB is running correctly, you will see a list of databases.</p><h4>Verify MongoDB Compass Installation</h4><ul><li>Open MongoDB Compass and connect to your MongoDB instance using the default connection string:</li></ul><pre>localhost:27017</pre><ul><li>Once connected, you can manage your databases through the intuitive GUI.</li></ul><h3>Additional Notes</h3><h4>Uninstall MongoDB</h4><p>If you need to uninstall MongoDB, run:</p><pre>sudo apt remove mongodb-org<br>sudo rm -r /var/log/mongodb /var/lib/mongodb</pre><h4>Uninstall MongoDB Compass</h4><p>To remove MongoDB Compass, run:</p><pre>sudo apt remove mongodb-compass</pre><p>By following these steps, you’ve successfully installed MongoDB and MongoDB Compass on Ubuntu. You can now manage your databases efficiently using the MongoDB service and Compass GUI.</p><h4><strong>Happy coding!</strong></h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=637c4b471f3d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Ultimate Guide to Joi Validation for Beginners]]></title>
            <link>https://medium.com/@vbansal0803/the-ultimate-guide-to-joi-validation-for-beginners-08d5a1d27432?source=rss-96942185b8cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/08d5a1d27432</guid>
            <category><![CDATA[joi-validation]]></category>
            <category><![CDATA[validation]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Varun]]></dc:creator>
            <pubDate>Fri, 03 Jan 2025 05:57:35 GMT</pubDate>
            <atom:updated>2025-01-03T05:57:35.022Z</atom:updated>
            <content:encoded><![CDATA[<p>When working with JavaScript, validating data is essential to ensure that your application behaves as expected. <strong>Joi</strong> is a powerful library that allows you to define validation rules easily. In this guide, we’ll cover everything you need to know about <strong>Joi</strong>, including conditional validations, to get started.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V_FLwB6kRWTeOdN7GUimmw.png" /></figure><h3>What is Joi?</h3><p><strong>Joi</strong> is a popular JavaScript library for data validation. It helps validate objects, arrays, strings, and other types of data. Instead of manually checking your data, you define rules in a schema, and Joi takes care of the rest.</p><h3>Setting Up Joi</h3><ul><li>Install Joi in your project:</li></ul><figure><img alt="npm install joi" src="https://cdn-images-1.medium.com/max/1024/1*yUZxW94bVJ4LRE-gkeaCoQ.png" /></figure><ul><li>Import Joi in your file:</li></ul><figure><img alt="const Joi = require(‘joi’);" src="https://cdn-images-1.medium.com/max/1024/1*ocj1M_vkbYGPPVXciOtw6g.png" /></figure><h3>How Joi Validation Works</h3><p>Joi works by creating a <strong>schema</strong> to define rules for your data. Then, you validate your data against the schema.</p><h3>Basic Example:</h3><figure><img alt="const schema = Joi.object({ name: Joi.string().required(), age: Joi.number().integer().min(18).max(60).required(), }); const data = { name: ‘John’, age: 25 }; const result = schema.validate(data); console.log(result);" src="https://cdn-images-1.medium.com/max/1024/1*QcAsJK3YL2HvMIp8sgV5YQ.png" /></figure><h3>Core Features</h3><h4>1. String Validation</h4><ul><li>.min(n): Minimum length</li><li>.max(n): Maximum length</li><li>.email(): Valid email format</li><li>.pattern(regex): Match a regex pattern</li><li>.required(): Field is required</li></ul><p>Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5PZ-jIYxiqdtWqpngwrntw.png" /></figure><h4>2. Number Validation</h4><ul><li>.integer(): Must be an integer</li><li>.positive(): Must be positive</li><li>.min(n), .max(n): Set range</li><li>.precision(n): Decimal places</li></ul><p>Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wE7To3pEx-_R6MSo589rwA.png" /></figure><h4>3. Array Validation</h4><ul><li>.items(schema): Validate items in the array</li><li>.min(n), .max(n): Set item count</li></ul><p>Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3QpqpDXLzonD-DlfXtZiPQ.png" /></figure><h4>4. Object Validation</h4><ul><li>Validate nested objects with .keys().</li></ul><p>Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CoPsLzbyDHO1WdMU42VVbg.png" /></figure><h3>Conditional Validations</h3><p>Joi makes conditional validations easy. Here are some common scenarios:</p><h4>1. Condition Based on Other Fields</h4><p>Use .when() to apply rules conditionally.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CdU5DFPU8_Y_jGjcH4bKSA.png" /></figure><ul><li>is: Field value to check</li><li>then: Rule if condition matches</li><li>otherwise: Rule if condition doesn’t match</li></ul><h3>2. Conditional Arrays</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sTEqCCoNET_uDZUo4v9RGQ.png" /></figure><h3>3. Required Based on Value</h3><p>Make a field required based on another field’s value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o2PMKXDxZQq74siJeAD1YA.png" /></figure><h3>Chaining Multiple Validations</h3><p>Joi allows you to chain multiple validations together.</p><p>Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7hJ7e_ahTBPxZSsa9bdW2Q.png" /></figure><h3>Validation Options</h3><p>Joi provides options to customise validation behaviour.</p><h3>Common Options:</h3><ol><li><strong>abortEarly</strong>: Stop validation after the first error (default: true).</li><li><strong>allowUnknown</strong>: Allow properties not in the schema (default: false).</li><li><strong>stripUnknown</strong>: Remove unknown properties (default: false).</li></ol><p>Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c_RhwyNuu2Pn9YMVhseZtg.png" /></figure><h3>Error Handling</h3><p>Joi provides detailed error messages when validation fails.</p><p>Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tj9PWcN0C1t5vZfRYi2glg.png" /></figure><h3>Advanced Features</h3><h3>1. Custom Validation</h3><p>Define custom validation rules with .custom().</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DgOvZ4Y1uVMb9Ld9AVS8MA.png" /></figure><h3>2. Validate Nested Objects</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l1k5Mbod3_CYkxoQdCEzIg.png" /></figure><h3>Complete Example</h3><p>Here’s a complete example of Joi validation in action:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*or-a4hrGpdtzGfpqOywnSw.png" /></figure><h3>Quick Reference</h3><p><strong>String</strong> : .min(), .max(), .email(), .pattern(), .required()</p><p><strong>Number :</strong> .integer(), .positive(), .min(), .max()</p><p><strong>Array :</strong>.items(), .min(), .max()</p><p><strong>Object:</strong> .keys(), .requiredKeys()</p><p><strong>Conditional</strong> : .when()</p><p><strong>Custom Rules:</strong> .custom()</p><h3>Conclusion</h3><p>With Joi, you can streamline data validation in your applications. From basic validations to complex conditional rules, Joi covers all your needs. Start small, experiment with the examples, and you’ll soon master this powerful library.</p><p>Let me know if you have questions or need help with a specific scenario!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=08d5a1d27432" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bridging the Gap: A Hybrid Approach to User Authentication]]></title>
            <link>https://medium.com/@vbansal0803/bridging-the-gap-a-hybrid-approach-to-user-authentication-c952a3b7368c?source=rss-96942185b8cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/c952a3b7368c</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[hybrid-authentication]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Varun]]></dc:creator>
            <pubDate>Thu, 19 Dec 2024 08:10:57 GMT</pubDate>
            <atom:updated>2024-12-19T08:15:10.145Z</atom:updated>
            <content:encoded><![CDATA[<p>In the ever-evolving landscape of web and mobile applications, user authentication is a cornerstone of security and user experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XsvXUryevCqNP6ocBNxRNA.jpeg" /></figure><p>Traditionally, we’ve relied on either stateless token-based authentication (e.g., JWT) or stateful session-based authentication. Both methods have their strengths and limitations, but what if we could combine the best of both worlds? This blog explores a novel hybrid approach that merges the reliability of session-based authentication with the scalability of JWT.</p><h3>The Current Landscape</h3><p><strong>1. Stateless Token-Based Authentication (JWT):</strong> JWT (JSON Web Tokens) have become a popular choice for modern applications due to their stateless nature. Here, the server encodes user information and sends it to the client, which uses the token for subsequent requests. Token validation is efficient as it doesn’t require a database lookup. However, token revocation and blacklisting remain challenging.</p><p><strong>Advantages:</strong></p><ul><li>High scalability (no database lookup).</li><li>Easy to implement.</li><li>Works well for distributed systems.</li></ul><p><strong>Limitations:</strong></p><ul><li>Revocation is difficult once the token is issued.</li><li>Token size can grow with additional claims.</li></ul><p><strong>2. Stateful Session-Based Authentication:</strong> This method involves storing session data on the server, often in a database or memory store like Redis. Tokens act as keys to access session information. Revocation is straightforward — just delete the session data from the store.</p><p><strong>Advantages:</strong></p><ul><li>Simple token revocation.</li><li>Smaller token size.</li></ul><p><strong>Limitations:</strong></p><ul><li>Requires database queries for every request.</li><li>Less scalable due to session storage.</li></ul><h3>The Hybrid Approach</h3><p>The proposed method aims to integrate the advantages of both systems.</p><p><strong>How It Works:</strong></p><p><strong>— Session ID in JWT:</strong></p><ul><li>A unique session_id is generated for each user session and stored in the database (e.g., MongoDB).</li><li>This session_id is embedded in the JWT as a claim.</li></ul><p><strong>— Token Validation Process:</strong></p><ul><li>When a request is received, the server validates the JWT as usual.</li><li>After validation, the session_id from the token is matched against the list of active session IDs in the database.</li></ul><p><strong>— Session Revocation:</strong></p><ul><li>To revoke a session, simply remove or invalidate the session_id in the database. This ensures that tokens associated with that session ID are no longer valid.</li></ul><h4>Implementation Details</h4><p><strong>Database Design:</strong> Each user record contains an array of session_ids:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cQpQ4bZWGGBzTQPDDIPnhw.png" /></figure><p><strong>JWT Payload Structure:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2_jZZhojR5Cmnemt-3YseQ.png" /></figure><p><strong>Verification Logic:</strong></p><ol><li>Decode the JWT to extract user_id and session_id.</li><li>Query the database to fetch the user’s active session_ids.</li><li>Check if the session_id exists in the retrieved array.</li></ol><p><strong>Revocation Example:</strong></p><ol><li>Deleting or blacklisting a session_id ensures the associated token becomes invalid.</li></ol><h4>Practical Implementation</h4><p>Here’s a step-by-step implementation using Node.js and MongoDB:</p><p><strong>1. Generating a JWT with Session ID:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JZqjI0xNo9dgA6D-9wsAKw.png" /></figure><p><strong>2. Validating the Token:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VDs1LDlExoOGkiity3wHdg.png" /></figure><p><strong>3. Revoking a Session:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gsAtIXUPNWBz-ReTQSqJZA.png" /></figure><p><strong>4. Middleware to Protect Routes:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Iex1Jn5d9QbyT4xRYqn0pw.png" /></figure><h4>Benefits of the Hybrid Approach</h4><p><strong>1. Overcoming Drawbacks of Other Methods:</strong></p><p><strong>— Stateless JWT:</strong></p><ul><li>Addresses the lack of token revocation by leveraging the session_id stored in the database.</li><li>Avoids embedding excessive claims, keeping tokens compact.</li></ul><p><strong>— Stateful Session:</strong></p><ul><li>Reduces the database load compared to storing full session data for every request.</li><li>Maintains scalability by relying on token validation first, and only querying the database for session verification.</li></ul><p><strong>2. Balancing Scalability and Security:</strong></p><ul><li>Combines the stateless efficiency of JWT with the revocation control of session-based methods.</li><li>Suitable for applications requiring distributed architecture without sacrificing token control.</li></ul><p><strong>3. Compact and Efficient Tokens:</strong></p><ul><li>Embedding only the session_id keeps tokens lightweight, unlike JWTs with numerous claims.</li></ul><p><strong>4. Improved Revocation:</strong></p><ul><li>Easily revoke specific sessions by removing or invalidating their session_id in the database.</li><li>Supports granular control, allowing multiple active sessions for the same user.</li></ul><h4>Limitations of the Hybrid Approach</h4><p><strong>1. Database Dependency:</strong></p><ul><li>Requires database access for session validation, which introduces a slight delay compared to purely stateless JWTs.</li><li>Needs efficient indexing for session lookups to avoid performance bottlenecks.</li></ul><p><strong>2. Concurrency Challenges:</strong></p><ul><li>Requires atomic operations when adding or removing session_ids to prevent race conditions.</li></ul><p><strong>3. Implementation Complexity:</strong></p><ul><li>More complex than either pure stateless or stateful methods.</li><li>Requires additional database management and JWT integration logic.</li></ul><p><strong>4. Scalability Limits:</strong></p><ul><li>While more scalable than stateful methods, it may not match the sheer scalability of fully stateless JWTs in extremely high-traffic systems.</li></ul><h4>Performance Insights</h4><p><strong>Benchmarks:</strong> A simulated environment was used to compare this hybrid method against traditional stateless JWT and session-based approaches. The metrics include:</p><p><strong>— Authentication Latency:</strong></p><ul><li>Hybrid: Slightly higher than stateless JWT but lower than session-based.</li><li>Stateless: Fastest.</li><li>Stateful: Slowest due to full session fetch.</li></ul><p><strong>— Database Load:</strong></p><ul><li>Hybrid: Minimal (only fetching session_ids).</li><li>Stateless: None.</li><li>Stateful: High.</li></ul><p><strong>— Scalability:</strong></p><ul><li>Hybrid: Balances well between stateless and stateful methods.</li><li>Stateless: Highly scalable.</li><li>Stateful: Limited by database/memory constraints.</li></ul><h3>Conclusion</h3><p>The hybrid approach offers a middle ground between the scalability of stateless JWT and the control of session-based authentication. By integrating session_id management, it ensures easy token revocation while maintaining a high level of scalability and performance. This makes it a compelling choice for modern applications requiring robust authentication mechanisms.</p><p>Have you tried implementing this method? Share your thoughts or experiences in the comments below…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c952a3b7368c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>