<?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 Noel Jaymon on Medium]]></title>
        <description><![CDATA[Stories by Noel Jaymon on Medium]]></description>
        <link>https://medium.com/@noeljaymon23?source=rss-4323de5a3454------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*QT21GB2AyewbAOAhF0t_Zg.jpeg</url>
            <title>Stories by Noel Jaymon on Medium</title>
            <link>https://medium.com/@noeljaymon23?source=rss-4323de5a3454------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 23:02:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@noeljaymon23/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[Choosing the Right Amazon Cognito Authentication Flow: SRP vs.]]></title>
            <link>https://towardsdev.com/choosing-the-right-amazon-cognito-authentication-flow-srp-vs-2e6cee1aeae6?source=rss-4323de5a3454------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e6cee1aeae6</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[two-factor-authentication]]></category>
            <category><![CDATA[aws-cognito]]></category>
            <category><![CDATA[mfa]]></category>
            <dc:creator><![CDATA[Noel Jaymon]]></dc:creator>
            <pubDate>Sun, 06 Sep 2026 20:36:01 GMT</pubDate>
            <atom:updated>2026-09-06T20:36:01.005Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Choosing the Right Amazon Cognito Authentication Flow: SRP vs. Custom Auth vs. Admin Flow (A Real-World CJIS Journey)</strong></h3><p>Amazon Cognito gives you several ways to authenticate users, and the documentation lists them all as if they’re interchangeable options on a menu. They’re not. Each flow makes different assumptions about <strong><em>where</em> </strong>authentication logic runs, <strong><em>what</em> </strong>you’re allowed to control, and <strong><em>how</em> </strong>you can layer on your own security requirements.</p><p>We learned this the hard way while building authentication for a law-enforcement case-management platform that had to comply with the FBI’s CJIS Security Policy. We started with the “<strong>obvious</strong>” flow, hit a wall, moved to a more powerful one, hit a subtler wall, and finally landed on the approach that actually fit our constraints. Along the way we accumulated a fairly complete mental model of Cognito’s auth flows which is what this article is.</p><figure><img alt="Choosing the Right Auth Flow in AWS Cognito" src="https://cdn-images-1.medium.com/max/1024/1*ZQbyu1I1LFqS_NZu0hormA.png" /><figcaption>Choosing the Right Auth Flow in AWS Cognito</figcaption></figure><p>If you’re integrating Cognito with a frontend and wondering which auth flow to pick, this is the guide I wish we’d had.</p><p><strong>— -</strong></p><p><strong>The three flows at a glance</strong></p><p>Cognito’s user pool authentication broadly comes in three shapes:</p><p>1. <strong>SRP (Secure Remote Password)</strong> — `USER_SRP_AUTH`. The password never leaves the client in a recoverable form; the client and Cognito do a cryptographic handshake. This is what Amplify uses by default.</p><p>2. <strong>Custom authentication</strong> — `CUSTOM_AUTH`. You define the challenge/response logic yourself using three Lambda triggers. Maximum flexibility, maximum responsibility.</p><p>3. <strong>Admin / server-side password auth</strong> — `ADMIN_USER_PASSWORD_AUTH` (and its browser-callable sibling `USER_PASSWORD_AUTH`). Your backend sends the username and password to Cognito directly and gets back tokens or a challenge.</p><p>There’s also `REFRESH_TOKEN_AUTH`, which every flow relies on for silent session renewal, but that’s orthogonal to the initial sign-in decision.</p><p>Let’s walk through each, how it actually works, and — most importantly — where it breaks down.</p><figure><img alt="The three Cognito authentication flows compared" src="https://cdn-images-1.medium.com/max/1024/1*OkQusa8rZNJgF7_ezFJQJQ.png" /><figcaption>The three Cognito authentication flows compared</figcaption></figure><p><strong>— -</strong></p><p><strong>1. SRP (`USER_SRP_AUTH`): the secure default</strong></p><p><strong>How it works</strong></p><p>SRP is a password-authenticated key agreement protocol. The short version: the client proves it knows the password without ever transmitting the password (or a simple hash of it) over the wire. Amplify implements the whole handshake for you, so from the frontend it’s a single call:</p><pre>import { Auth } from &quot;aws-amplify&quot;; // Amplify v5 style<br>await Auth.signIn(username, password);</pre><p>Amplify performs the multi-step SRP exchange with Cognito under the hood, handles any MFA challenge that comes back, stores the resulting tokens, and manages refresh. For a standard app, this is genuinely close to plug-and-play, and it’s the most secure of the browser-driven options because the password is never sent directly.</p><p><strong>When to use it</strong></p><p>- You want the least code and the strongest client-side password handling.</p><p>- You’re happy to let Cognito own the entire authentication lifecycle.</p><p>- You don’t need to insert custom logic (like a bespoke lockout policy) <strong><em>into</em> </strong>the authentication decision.</p><p><strong>The limitation that pushed us off it</strong></p><p>SRP authenticates the user, but it gives you <strong>no hook to run your own logic during the attempt</strong>. In particular, Cognito has no built-in, configurable “lock the account after N failed attempts for M minutes” control that you can point to and audit.</p><p>CJIS requires exactly that: a hard account lockout after a defined number of failed attempts. Cognito’s native throttling exists, but it’s undocumented, adaptive, and critically for compliance not something you can produce clean audit evidence for (“user X was locked after N attempts at time T”). With Amplify calling SRP directly from the browser, there was simply nowhere for us to insert and record that policy.</p><p>That was the first wall.</p><p><strong>— -</strong></p><p><strong>2. Custom Authentication (`CUSTOM_AUTH`): maximum control, maximum rope</strong></p><p><strong>How it works</strong></p><p>Custom auth lets you define the authentication conversation yourself using three Lambda triggers:</p><p>- <strong>Define Auth Challenge</strong> — the state machine. It decides, at each step, what challenge to issue next (or whether to pass/fail the whole thing).</p><p>- <strong>Create Auth Challenge</strong> — generates a challenge (e.g., an OTP, a security question).</p><p>- <strong>Verify Auth Challenge Response</strong>— checks the user’s answer and reports correct/incorrect.</p><p>From the frontend (Amplify), it looks like this:</p><pre>let user = await Auth.signIn(username); // starts CUSTOM_AUTH, no password yet<br>user = await Auth.sendCustomChallengeAnswer(user, password); // your challenge answer</pre><p>The appeal for us was obvious: because <em>*we*</em> controlled `Define Auth Challenge`, we could check a DynamoDB-backed attempt counter at the start of every sign-in and refuse to proceed if the account was locked — a fully custom, fully auditable lockout policy. We could also chain MFA in afterward.</p><p><strong>Where it got subtle</strong></p><p>Here’s the catch that isn’t obvious until you’re deep in it: <strong>`CUSTOM_AUTH` does not verify the password for you.</strong>When the user submits their password as a custom challenge answer, Cognito just hands that string to your `Verify Auth Challenge` Lambda and asks, “is this correct?” It has no idea it’s a password. It does nothing to check it.</p><p>So how do you verify the password inside a custom flow? You have to ask Cognito yourself by making a <strong><em>separate</em></strong> authentication call from inside your Lambda:</p><pre>cognito.admin_initiate_auth(<br>AuthFlow=&quot;ADMIN_USER_PASSWORD_AUTH&quot;,<br>AuthParameters={&quot;USERNAME&quot;: username, &quot;PASSWORD&quot;: supplied_password},<br>...<br>)</pre><p>If it doesn’t throw, the password was right. This works… until the user has MFA enabled.</p><p><strong>The limitation that pushed us off it</strong></p><p>This one took real debugging (and a CloudTrail investigation) to pin down, so it’s worth stating precisely, because it’s a trap:</p><p><strong>A password-verification call for an MFA-enabled user does not return “success” — it returns an MFA challenge.</strong>From Cognito’s perspective, you just started a real authentication, and now it wants the second factor.</p><p>That means our password-check-inside-a-Lambda was silently opening a <strong><em>second, parallel</em></strong> MFA challenge session for the same user — one nobody ever answered — while the <strong><em>outer</em></strong> custom-auth flow had its own MFA challenge that the user actually interacted with. Two concurrent software-token MFA challenges for one user. When the user submitted their (correct) TOTP code, it collided with this dual-challenge state, and Cognito rejected it as `CodeMismatchException`.</p><p>The symptom was maddening: the same user, same authenticator app, same code would authenticate fine under SRP but fail under custom auth. CloudTrail made it visible every custom-auth login produced <strong>two</strong> `InitiateAuth` calls where a working login had one.</p><figure><img alt="Why the custom auth password check collided with MFA" src="https://cdn-images-1.medium.com/max/1024/1*Byyk8YS9WRRWLCdqaEqC-A.png" /><figcaption>Why the custom auth password check collided with MFA</figcaption></figure><p>The root cause, in one sentence: <strong>because `CUSTOM_AUTH` can’t verify passwords itself, we were forced to verify them out-of-band, and that out-of-band call is a second auth session that conflicts with MFA.</strong> The split between “password step” and “MFA step” that custom auth encourages is exactly what created the collision.</p><p><strong>When custom auth <em>is</em> the right tool</strong></p><p>Don’t let our experience scare you off it — custom auth is excellent for what it’s designed for:</p><p>- Passwordless flows (email/SMS magic links, OTP-only sign-in).</p><p>- CAPTCHA or security-question challenges.</p><p>- Adaptive, multi-factor challenge sequences you fully control.</p><p>The mistake was using it to bolt custom logic <strong><em>around a standard password + MFA login</em></strong>. If your challenge <strong><em>is </em></strong>the authentication (OTP, magic link), custom auth shines. If you’re using it to wrap an ordinary password login with extra logic, you’re fighting the grain.</p><p><strong>— -</strong></p><p><strong>3. Admin / Server-Side Flow (`ADMIN_USER_PASSWORD_AUTH`): one session, full control</strong></p><p><strong>How it works</strong></p><p>In this flow, your backend receives the username and password and calls Cognito directly:</p><pre>resp = cognito.admin_initiate_auth(<br>UserPoolId=USER_POOL_ID,<br>ClientId=CLIENT_ID,<br>AuthFlow=&quot;ADMIN_USER_PASSWORD_AUTH&quot;,<br>AuthParameters={&quot;USERNAME&quot;: username, &quot;PASSWORD&quot;: password},<br>)<br></pre><p>For an MFA-enabled user, one correct-password call returns a single `SOFTWARE_TOKEN_MFA` challenge and a session. You then answer that challenge in the <strong><em>same session</em></strong>:</p><pre>cognito.admin_respond_to_auth_challenge(<br>ChallengeName=&quot;SOFTWARE_TOKEN_MFA&quot;,<br>Session=resp[&quot;Session&quot;],<br>ChallengeResponses={&quot;USERNAME&quot;: username, &quot;SOFTWARE_TOKEN_MFA_CODE&quot;: code},<br>…<br>)</pre><p>Password and MFA are one continuous, native session. There is no second, parallel challenge — which is precisely the collision that broke us under custom auth. One `InitiateAuth`, one `RespondToAuthChallenge`, tokens out.</p><p>`USER_PASSWORD_AUTH` is the browser-callable equivalent (Amplify can drive it directly); `ADMIN_USER_PASSWORD_AUTH` requires IAM credentials and runs server-side.</p><p><strong>Why this finally fit CJIS</strong></p><p>The realization that unlocked everything: <strong>we never actually needed to “verify the password in isolation.”</strong> That need was manufactured entirely by custom auth’s design. The native flow verifies the password <strong><em>as step one of a flow that continues into MFA on the same session </em></strong>so the awkward out-of-band password check, and the collision it caused, simply disappear.</p><p>And our lockout requirement? We wrapped it <strong><em>around</em></strong> the native call in our backend:</p><p>- Before calling Cognito, check the DynamoDB attempt/lock counters reject immediately if locked.</p><p>- On a wrong password (Cognito throws), increment the counter and lock at the threshold.</p><p>- On a wrong MFA code (Cognito returns `CodeMismatchException`), increment the MFA counter and lock at its threshold.</p><p>- On success, clear the counters.</p><p>We kept the exact CJIS-auditable lockout we needed, and we got a login flow that actually works with MFA by moving the lockout logic <strong><em>outside</em></strong> the auth flow (wrapping it) instead of <strong><em>inside</em></strong> it (splitting it).</p><figure><img alt="The admin flow with lockout wrapped around a single native session" src="https://cdn-images-1.medium.com/max/1024/1*VrEj5XZymKOAary7yKtRMg.png" /><figcaption>The admin flow with lockout wrapped around a single native session</figcaption></figure><p><strong>The trade-offs (there are real ones)</strong></p><p>This flow isn’t free:</p><p>- <strong>Tokens flow through your backend.</strong> With SRP, Cognito issues tokens to the browser and Amplify manages them transparently. With the admin flow, your backend receives the tokens and hands them to the frontend, which then has to inject them into Amplify’s session so the rest of the app (`currentSession()`, auto-refresh) keeps working. This “token adoption” step is extra work and, on Amplify v6, touches implementation details you should test carefully across upgrades.</p><p>- <strong>The password transits your backend.</strong> It’s over TLS and your backend is trusted, but for a compliance review it’s worth documenting that the password passes through your Lambda rather than going browser-to-Cognito directly.</p><p>- <strong>You own more of the flow.</strong> More correctness responsibility, more audit-logging opportunity (which, for CJIS, is arguably a feature).</p><p><strong>When to use it</strong></p><p>- You need to wrap authentication with your own server-side logic (lockout, audit logging, custom risk checks) <strong>and</strong> you’re using standard password + MFA.</p><p>- You already have a trusted backend in the request path.</p><p>- You want password and MFA handled as one coherent native flow rather than split across custom challenges.</p><p><strong>— -</strong></p><p><strong>A decision guide</strong></p><figure><img alt="Decision Guide Table" src="https://cdn-images-1.medium.com/max/1024/1*kLc99WfrrhrJpXJ4zUKLHA.png" /><figcaption>Decision Guide Table</figcaption></figure><p>The single most useful heuristic we took away:</p><p><strong>If your challenge <em>is</em> the authentication, use Custom Auth. If you need to wrap a standard password+MFA login with extra logic, use the admin flow and put your logic <em>around</em> it never split the password and MFA into separate steps you stitch together yourself.<br> —-</strong></p><h4><strong>Closing Thought</strong></h4><p>Cognito’s flows aren’t a menu of interchangeable options they’re different tools with different assumptions baked in. SRP assumes Cognito owns the lifecycle. Custom auth assumes <strong><em>you</em></strong> define the challenge. The admin flow assumes you have a trusted backend and want to wrap standard auth with your own logic.</p><p>We arrived at the admin flow not because it’s “best” in the abstract, but because our constraint auditable, hard account lockout on a standard password+MFA login for CJIS is exactly the shape it fits. Your constraints may point elsewhere. The goal of this article isn’t to sell you one flow; it’s to help you recognize, earlier than we did, which wall you’re about to hit so you can pick the flow that doesn’t have that wall in the first place.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e6cee1aeae6" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/choosing-the-right-amazon-cognito-authentication-flow-srp-vs-2e6cee1aeae6">Choosing the Right Amazon Cognito Authentication Flow: SRP vs.</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How AWS Lambda Works Behind the Scenes: Containers, Concurrency, and Scaling Explained]]></title>
            <link>https://towardsdev.com/how-aws-lambda-works-behind-the-scenes-containers-concurrency-and-scaling-explained-b6fe7499b0c3?source=rss-4323de5a3454------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6fe7499b0c3</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[cloud-architecture]]></category>
            <dc:creator><![CDATA[Noel Jaymon]]></dc:creator>
            <pubDate>Wed, 17 Dec 2025 12:18:41 GMT</pubDate>
            <atom:updated>2025-12-18T08:09:33.306Z</atom:updated>
            <content:encoded><![CDATA[<h3>A backend engineer’s guide to understanding Lambda’s execution model, cold starts, caching, and real-world scaling behavior</h3><p>AWS Lambda is marketed as <em>serverless</em>, but if you’re building production systems, you need to understand <strong>what actually runs your code</strong> and <strong>how it scales under load</strong>.</p><p>This article breaks down <strong>Lambda’s internal execution model</strong> containers, concurrency, cold starts, and caching without abstractions or marketing noise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_O1UE6aayRuBhqiaLomtCA.png" /><figcaption>aws lambda</figcaption></figure><h3>1. Lambda Is Container-Based (Not Thread-Based)</h3><p>At runtime, every Lambda invocation runs inside an <strong>isolated execution environment</strong> (commonly called a container).</p><blockquote><strong><em>AWS Lambda scales by creating containers, not threads.</em></strong></blockquote><h3>Key rules</h3><ul><li><strong>1 container = 1 request at a time</strong></li><li>Containers do <strong>not share memory</strong></li><li>Scaling happens by <strong>adding more containers</strong></li></ul><h3>Diagram: Request → Container mapping</h3><pre>Incoming Requests<br>       │<br>       ├──▶ Container A → handler()<br>       ├──▶ Container B → handler()<br>       └──▶ Container C → handler()</pre><p>No container ever processes two requests concurrently.</p><h3>2. Containers vs Threads (Why AWS Chose This Model)</h3><p>Lambda deliberately avoids multi-request threading.</p><pre>| Threads                     | Containers       |<br>| --------------------------- | ---------------- |<br>| Shared memory               | Isolated memory  |<br>| Fast, lightweight           | Slightly heavier |<br>| Race conditions possible    | Strong isolation |<br>| One crash can affect others | Fault-safe       |</pre><p>This design ensures:</p><ul><li>Predictable scaling</li><li>Security isolation</li><li>No cross-request state leaks</li></ul><p>That’s why Lambda treats <strong>concurrency as container count</strong>, not thread count.</p><h3>3. Cold Starts vs Warm Starts</h3><h3>Cold Start</h3><p>Occurs when AWS:</p><ul><li>Creates a new container</li><li>Initializes the runtime</li><li>Loads your code and global variables</li></ul><h3>Warm Start</h3><p>Occurs when:</p><ul><li>An existing container is reused</li><li>Global state is already in memory</li></ul><h3>Diagram: Cold vs Warm execution</h3><pre>Cold Start<br>  └─ Create container<br>  └─ Init runtime<br>  └─ Import modules<br>  └─ Load globals<br>  └─ Invoke handler()</pre><pre>Warm Start<br>  └─ Invoke handler() directly</pre><p>AWS keeps containers warm <strong>opportunistically</strong> — this is not guaranteed.</p><h3>4. Why Static Caching Works in Lambda</h3><p>Anything defined <strong>outside the handler function</strong> is executed <strong>once per container</strong>.</p><h3>Example (Python)</h3><pre>STATIC_MAPPING = load_mapping()  # runs once per container</pre><pre>def handler(event, context): # executes on every execution<br>    return STATIC_MAPPING[event[&quot;key&quot;]]</pre><h3>What this gives you</h3><ul><li>Zero repeated I/O</li><li>No S3 or DB calls per request</li><li>Extremely low latency</li></ul><h3>What it doesn’t give you</h3><ul><li>No sharing across containers</li><li>No persistence guarantees</li></ul><blockquote><em>Lambda caching is an </em><strong><em>optimization</em></strong><em>, not a contract.</em></blockquote><h3>5. How Lambda Actually Scales</h3><p>Lambda scaling is driven by <strong>concurrency</strong>, not request volume.</p><h3>The formula</h3><pre>Concurrency = Requests per second × Execution time (seconds)</pre><h3>Example</h3><p>If:</p><ul><li>Avg execution time = 1s</li><li>Traffic = 3 requests/sec</li></ul><p>Then:</p><pre>Concurrency ≈ 3 containers</pre><h3>Diagram: Traffic-driven scaling</h3><pre>Low traffic        Medium traffic        Traffic spike<br>    │                   │                     │<br>1 container       3 containers         20+ containers</pre><p>AWS automatically creates and removes containers as traffic changes.</p><h3>6. Account-Level Concurrency Limits</h3><p>By default, AWS enforces:</p><pre>1,000 concurrent executions per region (per account)</pre><p>This limit is <strong>shared across all Lambda functions</strong>.(can be increased to 5k or 10k upon special request with aws team)</p><h3>Critical CloudWatch metrics</h3><ul><li>ConcurrentExecutions</li><li>UnreservedConcurrentExecutions</li><li>Throttles</li></ul><p>If concurrency exceeds the limit, Lambda <strong>throttles immediately</strong>.</p><h3>7. Reserved vs Provisioned Concurrency</h3><h3>Reserved Concurrency</h3><ul><li>Caps max containers per function</li><li>Guarantees capacity</li><li>Prevents noisy neighbors</li></ul><h3>Provisioned Concurrency</h3><ul><li>Keeps containers pre-warmed</li><li>Eliminates cold starts</li><li>Preloads static mappings</li></ul><p>Use provisioned concurrency when:</p><ul><li>Latency is critical</li><li>You load large in-memory data(&gt; 100 MB)</li></ul><h3>8. Threads Inside Lambda (When They Make Sense)</h3><p>Threads can be useful <strong>inside a single invocation</strong> for:</p><ul><li>Parallel API calls</li><li>I/O-bound workloads</li></ul><p>They <strong>do not</strong>:</p><ul><li>Increase Lambda concurrency</li><li>Allow multiple requests per container</li></ul><p>In Python, threads help with I/O — not CPU (GIL still applies).</p><h3>9. What Backend Engineers Should Remember</h3><ul><li>Lambda scales using <strong>containers</strong></li><li>One request per container</li><li>Concurrency equals container count</li><li>Global variables persist <strong>per container</strong></li><li>Containers are ephemeral</li><li>CloudWatch metrics are non-negotiable</li></ul><h3>References</h3><ul><li>AWS Lambda Developer Guide<br> <a href="https://docs.aws.amazon.com/lambda/latest/dg/welcome.html">https://docs.aws.amazon.com/lambda/latest/dg/welcome.html</a></li><li>Lambda Concurrency<br> <a href="https://docs.aws.amazon.com/lambda/latest/dg/lambda-concurrency.html">https://docs.aws.amazon.com/lambda/latest/dg/lambda-concurrency.html</a></li><li>Execution Environment<br> <a href="https://docs.aws.amazon.com/lambda/latest/dg/runtimes-context.html">https://docs.aws.amazon.com/lambda/latest/dg/runtimes-context.html</a></li></ul><h3>Final Thought</h3><p>If you think of Lambda as <strong>stateless containers that scale automatically</strong>, everything — from caching to throttling — becomes predictable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6fe7499b0c3" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/how-aws-lambda-works-behind-the-scenes-containers-concurrency-and-scaling-explained-b6fe7499b0c3">How AWS Lambda Works Behind the Scenes: Containers, Concurrency, and Scaling Explained</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[FakeBuster- Get your facts right!]]></title>
            <link>https://medium.com/@noeljaymon23/fakebuster-get-your-facts-right-e6d7a7acc37e?source=rss-4323de5a3454------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6d7a7acc37e</guid>
            <category><![CDATA[rag-architecture]]></category>
            <category><![CDATA[ai-evaluation]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[kaggle-competition]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Noel Jaymon]]></dc:creator>
            <pubDate>Sun, 20 Apr 2025 17:31:55 GMT</pubDate>
            <atom:updated>2025-05-04T10:29:56.913Z</atom:updated>
            <content:encoded><![CDATA[<h4>Leveraging LLMs, Vector Search, and Web Search to Detect and Correct Geopolitical Misinformation.</h4><p>In an age where misinformation spreads faster than facts especially in sensitive areas like geopolitics the need for automated fact-checking has never been more urgent. <strong>FakeBuster</strong> is an AI-powered system designed to verify geopolitical news and social media claims in real time. Built using <strong>Google’s Gemini</strong>, <strong>vector-based retrieval (RAG)</strong>, and <strong>live web search</strong>, it combines large language model reasoning with fresh, trustworthy context from the web.</p><p>This project was developed as part of a Kaggle competition focused on building GenAI tools for disaster response and decision-making. In this post, I’ll walk you through the architecture, reasoning process, and how FakeBuster handles noisy claims like tweets about trade bans or interest rate cuts by returning not only <strong>true/false verdicts</strong> but also <strong>reliable sources and corrections</strong>.</p><p>Let’s break down how it works, and why it matters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*TYI4hlsWVgVoUfTmrHZFWg.png" /><figcaption>Figure 1 : Fake Buster Architecture Workflow</figcaption></figure><p><strong>What This Blog Covers:</strong></p><ul><li>The Tech Stack used</li><li>The architecture and design of FakeBuster</li><li>How it evaluates AI answers using LLM based QA assessment</li><li>Application in news, government, and social platforms</li><li>Future upgrades and enhancements</li></ul><p>But wait how exactly does FakeBuster <em>know</em> what’s real?</p><p>It’s not just magic (though it might feel like it). Behind the scenes, there’s a powerful AI framework at work one that doesn’t guess, but checks. It’s called <strong>Retrieval-Augmented Generation</strong>, or RAG for short.</p><p>Let’s peel back the curtain and see how this technique helps FakeBuster ground every response in real, verifiable information <em>and why that changes everything.</em></p><h3>🤖 How FakeBuster Uses RAG:</h3><p>At the heart of FakeBuster lies <strong>Retrieval-Augmented Generation (RAG)</strong> a powerful AI technique that combines the best of both worlds: factual retrieval and natural language generation.</p><p>Instead of relying solely on a model’s internal memory, RAG augments its responses by actively<em> searching through a curated knowledge</em> base of <strong>verified, trusted sources</strong>. When a user poses a query or inputs suspicious content, FakeBuster:</p><ol><li><strong>Retrieves</strong> the most relevant documents from a vectorized database.</li><li><strong>Augments</strong> the user input with these documents as contextual evidence.</li><li><strong>Generates</strong> a response that is grounded, explainable, and fact-checked.</li></ol><blockquote><em>FakeBuster uses Retrieval-Augmented Generation (RAG) to detect and verify information. It starts with document chunking and embedding, followed by intelligent retrieval of the most relevant sources, and ends with an LLM generating grounded, fact-checked responses based on real documents.</em></blockquote><p>Now that we’ve seen how RAG powers FakeBuster’s factual responses, let’s zoom in on what actually makes the engine run.</p><p>From document chunking to real-time search and answer evaluation here’s a look under the hood at the tech stack and architecture that make FakeBuster tick.</p><p><strong>Tech Stack</strong></p><p>FakeBuster uses:</p><ul><li><a href="https://www.langchain.com/"><strong>LangChain</strong></a> for orchestration</li><li><a href="https://deepmind.google/technologies/gemini/"><strong>Gemini 1.5 Pro</strong></a> for controlled LLM responses</li><li><a href="https://www.trychroma.com/"><strong>ChromaDB</strong></a> for vector storage</li><li><a href="https://programmablesearchengine.google.com/about/"><strong>Google Custom Search API</strong></a> for real time fact checking</li><li><strong>Google Generative AI Embeddings</strong> for similarity retrieval</li><li><a href="https://huggingface.co/mistralai/Mixtral-8x7B-Instruct-v0.1"><strong>Mistral 8x7B Instruct</strong></a> via HuggingFace for evaluation</li><li><a href="https://cloud.google.com/use-cases/retrieval-augmented-generation?hl=en"><strong>RAG</strong></a><strong> + </strong><a href="https://www.promptingguide.ai/techniques/fewshot"><strong>Few Shot Prompting</strong></a> for factual answering</li></ul><h3>Architecture Layer: How FakeBuster Works End to End</h3><p>FakeBuster’s architecture is modular, explainable, and efficient. The system processes input text, retrieves relevant evidence from a vector database, and then uses a <strong>large language model (LLM)</strong> to determine whether the text is real or fabricated, while citing the sources that back its verdict. Here’s how it works, layer by layer:</p><p><strong><em>Data Collection + Embedding</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*V02J8gQbDY0fOOnlaJKJ6Q.png" /><figcaption>Figure 2: Document Chunking Pipeline</figcaption></figure><p>The system starts by ingesting geopolitical news events as structured JSON. These are turned into Document objects using <em>LangChain</em>, chunked using <strong><em>RecursiveCharacterTextSplitter</em></strong>, and embedded with <strong><em>GoogleGenerativeAIEmbeddings</em></strong>. The result is stored in <em>Chroma</em>, a <strong>Vector DB</strong>, enabling fast similarity based document retrieval.</p><blockquote><em>Raw JSON documents are converted into LangChain document objects, then split using a Recursive Text Splitter while preserving source metadata — preparing them for embedding and retrieval.</em></blockquote><p>Below is a snippet of the structured JSON dataset that powers the FakeBuster system. Each entry represents a geopolitical news event with metadata such as date, region, source, and summary — later chunked and embedded for semantic retrieval.</p><pre>data = [<br>  {<br>    &quot;id&quot;: &quot;1&quot;,<br>    &quot;event&quot;: &quot;US Imposes 104% Tariff on Chinese Imports&quot;,<br>    &quot;date&quot;: &quot;2025-04-09&quot;,<br>    &quot;region&quot;: &quot;USA&quot;,<br>    &quot;summary&quot;: &quot;US Imposes 104% Tariff on Chinese Imports. President Trump&#39;s administration has implemented a 104% tariff...&quot;,<br>    &quot;source&quot;: &quot;https://www.businessinsider.com/trump-tariffs-are-here-2025-4&quot;,<br>    &quot;category&quot;: &quot;trade policy&quot;<br>  },<br>  {<br>    &quot;id&quot;: &quot;2&quot;,<br>    &quot;event&quot;: &quot;China Retaliates with 84% Tariff on US Goods&quot;,<br>    &quot;date&quot;: &quot;2025-04-09&quot;,<br>    &quot;region&quot;: &quot;China&quot;,<br>    &quot;summary&quot;: &quot;China Retaliates with 84% Tariff on US Goods. In response to US tariffs, China has announced an 84% tariff...&quot;,<br>    &quot;source&quot;: &quot;https://www.aljazeera.com/news/liveblog/2025/4/9/trump-tariffs-stock-dive-as-world-braces...&quot;,<br>    &quot;category&quot;: &quot;trade policy&quot;<br>  },<br>  ...<br>]</pre><p>This dataset structure ensures traceability of sources and context preservation, which are critical for grounding factual answers in RAG pipelines.</p><p><strong><em>Retrieval + Grounded Answer Generation (RAG)</em></strong></p><p>Once the documents are neatly chunked and embedded into a vector database, it’s time to put them to use. Enter the <strong>AI Agent</strong> — the intelligent engine behind FakeBuster’s fact-checking prowess. From interpreting user queries to retrieving relevant chunks and producing grounded, explainable responses, the AI Agent orchestrates it all. Here’s how this powerhouse operates under the hood:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*Ibv17Q1XzYmugcwxBBB4HA.png" /><figcaption>Figure 3 : Anatomy of FakeBuster’s AI Agent</figcaption></figure><p><strong><em>System Prompt Configuration</em></strong></p><p>To ensure precise behavior from the LLM, FakeBuster defines a custom system_message instructing the model to act as a geopolitical analyst. This message establishes tool usage constraints and encourages source transparency-critical for ensuring the accuracy and trustworthiness of answers.</p><pre>llm = ChatGoogleGenerativeAI(<br> model=&quot;gemini-1.5-pro&quot;,<br> temperature=0,<br> convert_system_message_to_human=True,<br> google_api_key=os.environ[&quot;GOOGLE_API_KEY_GENAI&quot;],<br> system_message=(<br> &quot;You are a geopolitical analyst. You may only call each tool once per question. &quot;<br> &quot;If you&#39;ve already received information from a tool, do not call it again. &quot;<br> &quot;Always include source URLs from tool observations in your final answer.&quot;<br> )<br>)</pre><p><strong><em>Tool Based Decision Routing</em></strong></p><p>Using <strong>LangChain Agents</strong>, FakeBuster decides whether to check historical or current information. If the query is about past events, it uses the in house vector DB (GeoNewsDB); if it’s a current event, it calls Google Search.</p><p>The decision logic is implemented using LangChain&#39;s tool routing, where each tool is registered with a specific use-case description. Based on the timestamp in the query, the agent selects the appropriate tool-GeoNewsDB for past events or Google Search for current updates:</p><pre>geo_tool = Tool(<br>    name=&quot;GeoNewsDB&quot;,<br>    func=tool_wrapper(&quot;GeoNewsDB&quot;, geonewsdb_tool_fn),<br>    description=&quot;Use for known, documented events before April 20, 2025.&quot;<br>)<br><br>google_tool = Tool(<br>    name=&quot;GoogleSearch&quot;,<br>    func=tool_wrapper(&quot;GoogleSearch&quot;, search.run),<br>    description=&quot;Use for real-time updates on or after April 20, 2025.&quot;<br>)<br><br>tools = [geo_tool, google_tool]</pre><p><strong><em>Smart Question Understanding with Few Shot Prompting</em></strong></p><p>To guide Gemini in reasoning through the tools, a <strong>few shot ReAct prompt</strong> is used. It provides examples of tool usage, encouraging the LLM to reflect (“Thought”) and act (“Action”) as a reasoning agent</p><pre>few_shot_prompt = PromptTemplate.from_template(&quot;&quot;&quot;<br>You are a smart assistant that answers questions about tariffs and geopolitics. You have access to two tools:<br><br>- Use **GeoNewsDB** only once per question, for known or historical events before the present date.<br>- Use **GoogleSearch** only once per question, and only for real-time developments on/after present date.<br># - If a question may require both tools, use each **only once**, and combine their results.<br><br>When providing your final answer:&quot;&lt;clear, neutral summary of the facts&gt;&quot;<br><br>Guidelines:<br>- Do not hallucinate — if uncertain, say so in the &quot;answer&quot;.<br>- Extract all relevant info from the first tool call. Do not repeat tool calls.<br>- If a tool was already called, do not use it again.<br>- Always use the observation to form your final answer.<br>- Be concise, accurate, and trustworthy.<br><br>---<br><br>Examples:<br><br>Question: Did India cut repo rates in 2020?  <br>Thought: This is historical. I will use GeoNewsDB.  <br>Action: GeoNewsDB  <br>Action Input: India repo rate 2020  <br>Observation: India reduced its repo rate by 75 basis points in March 2020.  <br>Final Answer:&quot;Yes, India reduced its repo rate by 75 basis points in March 2020.&quot;<br><br>---<br><br>Question: Has the US recently increased tariffs on Chinese EVs?  <br>Thought: This is recent. I will use GoogleSearch.  <br>Action: GoogleSearch  <br>Action Input: US tariff Chinese EVs 2025  <br>Observation: On April 8, 2025, the US imposed a 104% tariff on Chinese electric vehicles.  <br>Final Answer:&quot;Yes, the US imposed a 104% tariff on Chinese electric vehicles in April 2025.&quot;<br><br>---<br><br>Question: Did the US warn about new Chinese steel tariffs in March 2025?  <br>Thought: This is a historical event from March. I will use GeoNewsDB.  <br>Action: GeoNewsDB  <br>Action Input: US Chinese steel tariff warning March 2025  <br>Observation: In March 2025, the US warned of potential new tariffs on Chinese steel amid ongoing trade imbalances.  <br>Final Answer:&quot;Yes, in March 2025, the US warned of potential new tariffs on Chinese steel.&quot;<br>---<br><br>Now answer this new question:  <br>Question: {input}  <br>{agent_scratchpad}<br><br>&quot;&quot;&quot;)</pre><p>To tie together the workings of FakeBuster’s internal components and give you a bird’s-eye view of how everything fits together, let’s walk through a high-level architectural flow. This next diagram condenses the complete RAG-driven process from receiving a user query to producing a fact-checked, source-backed response into a simplified pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VHCWnVjOVPszevQ4aYRp5w.png" /><figcaption>Figure 4 : Summary View of FakeBuster’s RAG-Based Agent Architecture</figcaption></figure><p>Each of these components works in harmony to detect deep fakes, verify facts, and return source-grounded answers in real time.</p><h3>AI Evaluation: How FakeBuster Audits Itself</h3><p>One of the standout aspects of FakeBuster is that it doesn’t just generate answers, it also checks how good those answers are. The project incorporates a multi stage QA evaluation pipeline using Hugging Face tools and the <strong>Mistral 8x7B Instruct</strong> model to critique LLM generated answers across three key metrics: <strong>groundedness</strong>, <strong>relevance</strong>, and <strong>standalone clarity</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HhJD5o81VNYitUEXLbDByg.png" /><figcaption>Figure 5 : AI Evaluation Pipeline</figcaption></figure><p><strong><em>Phase 1: QA Pair Generation (Code Section 5)</em></strong></p><p>The process begins by sampling embedded document chunks and prompting <strong>Mistral 8x7B Instruct</strong> to generate <strong>factoid style questions</strong> along with concise reference answers. These resemble the types of questions real users might ask about geopolitics, e.g., <em>“Did China reduce tariffs in early 2025?”</em></p><pre>QA_generation_prompt = &quot;&quot;&quot;<br>Your task is to write a factoid question and an answer given a context.<br>Your factoid question should be answerable with a specific, concise piece of factual information from the context.<br>Your factoid question should be formulated in the same style as questions users could ask in a search engine.<br>This means that your factoid question MUST NOT mention something like &quot;according to the passage&quot; or &quot;context&quot;.<br><br>Provide your answer as follows:<br><br>Output:::<br>Factoid question: (your factoid question)<br>Answer: (your answer to the factoid question)<br><br>Now here is the context.<br><br>Context: {context}\n<br>Output:::&quot;&quot;&quot;</pre><p><strong><em>Phase 2: Quality Filtering Metrics for QA Pairs</em></strong></p><p>Each generated question is scored on:</p><ul><li><strong>Groundedness</strong> : Can the answer be clearly derived from the provided context? This is critical in verifying that the answer isn’t hallucinated or loosely connected to the source.</li><li><strong>Relevance</strong> : Is the question useful to someone building an NLP system? i.e., whether the question is meaningful or useful in the context of building NLP datasets or search-like systems. This ensures the QA pairs align with real-world user intent.</li><li><strong>Standalone clarity</strong> : Does the question make complete sense on its own?It is to ensure question can be understood on its own without relying on external references. This is crucial for training generalizable QA models.</li></ul><p>Here’s the prompt for each metric:</p><pre>question_groundedness_critique_prompt = &quot;&quot;&quot;<br>You will be given a context and a question.<br>Your task is to provide a &#39;total rating&#39; scoring how well one can answer the given question unambiguously with the given context.<br>Give your answer on a scale of 1 to 5, where 1 means that the question is not answerable at all given the context, and 5 means that the question is clearly and unambiguously answerable with the context.<br><br>Provide your answer as follows:<br><br>Answer:::<br>Evaluation: (your rationale for the rating, as a text)<br>Total rating: (your rating, as a number between 1 and 5)<br><br>You MUST provide values for &#39;Evaluation:&#39; and &#39;Total rating:&#39; in your answer.<br><br>Now here are the question and context.<br><br>Question: {question}\n<br>Context: {context}\n<br>Answer::: &quot;&quot;&quot;<br><br>question_relevance_critique_prompt = &quot;&quot;&quot;<br>You will be given a question.<br>Your task is to provide a &#39;total rating&#39; representing how useful this question can be to machine learning developers building NLP applications with the Hugging Face ecosystem.<br>Give your answer on a scale of 1 to 5, where 1 means that the question is not useful at all, and 5 means that the question is extremely useful.<br><br>Provide your answer as follows:<br><br>Answer:::<br>Evaluation: (your rationale for the rating, as a text)<br>Total rating: (your rating, as a number between 1 and 5)<br><br>You MUST provide values for &#39;Evaluation:&#39; and &#39;Total rating:&#39; in your answer.<br><br>Now here is the question.<br><br>Question: {question}\n<br>Answer::: &quot;&quot;&quot;<br><br>question_standalone_critique_prompt = &quot;&quot;&quot;<br>You will be given a question.<br>Your task is to provide a &#39;total rating&#39; representing how context-independent this question is.<br>Give your answer on a scale of 1 to 5, where 1 means that the question depends on additional information to be understood, and 5 means that the question makes sense by itself.<br>For instance, if the question refers to a particular setting, like &#39;in the context&#39; or &#39;in the document&#39;, the rating must be 1.<br>The questions can contain obscure technical nouns or acronyms like Gradio, Hub, Hugging Face or Space and still be a 5: it must simply be clear to an operator with access to documentation what the question is about.<br><br>For instance, &quot;What is the name of the checkpoint from which the ViT model is imported?&quot; should receive a 1, since there is an implicit mention of a context, thus the question is not independent from the context.<br><br>Provide your answer as follows:<br><br>Answer:::<br>Evaluation: (your rationale for the rating, as a text)<br>Total rating: (your rating, as a number between 1 and 5)<br><br>You MUST provide values for &#39;Evaluation:&#39; and &#39;Total rating:&#39; in your answer.<br><br>Now here is the question.<br><br>Question: {question}\n<br>Answer::: &quot;&quot;&quot;</pre><p>These scores are generated using a prompt driven critique method where <strong><em>Mistral</em></strong> plays the evaluator. QA pairs scoring poorly on any criterion are filtered out, leaving only high quality evaluation data.</p><p><strong><em>Phase 3: FakeBuster Gets Tested</em></strong></p><p>Each validated question is passed through the <strong>FakeBuster agent</strong>, which uses Gemini to generate a grounded answer via its RAG pipeline and controlled tool usage. This answer is then evaluated against the reference answer using <strong>LangChain’s evaluation suite</strong>, guided by:</p><ul><li><strong>Correctness</strong> : Is the answer factually aligned with the reference?</li><li><strong>Relevance</strong> : Does it actually address the question?</li><li><strong>Conciseness</strong> : Is it clean and direct?</li></ul><p>Gemini evaluates the system’s outputs with structured prompts, and the results are stored back in a structured data frame.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZMAH2hdOjUypZidIzc4QHA.png" /><figcaption>Figure 6 : LLM as Judge Evaluation</figcaption></figure><h3>Real World Application: Where FakeBuster Fits</h3><ul><li><strong>Newsrooms &amp; Media Verification<br></strong> Journalists and editors can validate breaking news claims using FakeBuster’s grounded outputs, reducing reliance on gut checks and rushed fact finding.</li><li><strong>Policy Research &amp; Government Analysis<br></strong> FakeBuster can support analysts tracking geopolitical shifts, especially when layered with time specific tool calls and vetted source citations.</li><li><strong>Social Platforms &amp; Moderation Tools<br></strong> Platforms can deploy FakeBuster in their backend pipelines to flag potential misinformation before it spreads.</li><li><strong>AI Safety &amp; LLM Monitoring<br></strong> Used as a safeguard, FakeBuster can review outputs from other generative systems to verify claims or sources before publication.</li></ul><h3>Future Enhancements: Scaling FakeBuster with GenAI Ecosystem</h3><p><strong>1. Integrating Google’s Gemini API Ecosystem</strong></p><p>Beyond Gemini 1.5 Pro, FakeBuster could be upgraded to leverage <strong>multi modal capabilities</strong> of upcoming Gemini models, allowing it to verify not just text but also related images, graphs, or documents in real time.</p><p><strong>2. Expanding Grounding Through Google Knowledge Graph</strong></p><p>Rather than relying solely on retrievable documents or live search, the system could tap into <strong>Google’s Knowledge Graph</strong> to enrich grounding with structured facts and semantic links.</p><p><strong>3. Scalable Hosting with Vertex AI or LangChain Server</strong></p><p>To productionize the system, deploying it via <strong>Vertex AI</strong> or using <strong>LangChain’s hosted runtime</strong> would allow real time querying with autoscaling, logging, and monitoring, crucial for enterprise deployment.</p><p><strong>4. Auto Prompt Refinement &amp; Active Learning</strong></p><p>Using feedback from evaluation cycles, FakeBuster can <strong>auto tune its prompts</strong> and grounding strategies over time.</p><p><strong>Toward Truth Aware LLMs</strong></p><p>FakeBuster is more than just a text classifier, it’s a <strong>truth first agent system</strong>. By combining retrieval, tool based reasoning, LLM generated analysis, and post hoc evaluation, it addresses a real world crisis: AI generated misinformation.</p><p>What sets it apart is <strong>accountability</strong>. Every output is backed by sources, every decision follows logic, and every answer gets judged. In an age of synthetic information, that’s the kind of AI we need.</p><p>- — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — -</p><p>Curious to dive into the implementation details or run FakeBuster yourself?</p><p>📂 You can access the complete code on the Kaggle Notebook below<br> 👉 <a href="https://www.kaggle.com/code/noeljaymon/fake-buster-get-your-facts-right">https://www.kaggle.com/code/noeljaymon/fake-buster-get-your-facts-right</a></p><p>You can also watch the you tube video — <a href="https://youtu.be/nW-yteTZqAY">https://youtu.be/nW-yteTZqAY</a></p><p>This includes:</p><ul><li>Modular pipeline code for data ingestion, embedding, and retrieval</li><li>RAG integration and LangChain agent orchestration</li><li>Prompt templates and evaluation logic</li><li>Sample datasets and usage examples to get you started</li></ul><p>Whether you’re building your own misinformation detection tool or just exploring GenAI applications — you’ll find everything you need in the repo.</p><p>🤝 Acknowledgment</p><p>This project wouldn’t have been possible without the collaboration and insights of my teammates <a href="https://medium.com/u/41f58effcde4">Adamyaofficial</a> and <a href="https://medium.com/u/c2b9a0f9824f">Himanshi Sharma</a>. Grateful for your support in building and refining <em>FakeBuster</em> into an effective AI-driven defense against misinformation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6d7a7acc37e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Refactoring If..Else Statement In JS]]></title>
            <link>https://towardsdev.com/refactoring-nested-loops-in-js-e6d8a9db2db3?source=rss-4323de5a3454------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6d8a9db2db3</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[nested-if-else]]></category>
            <category><![CDATA[conversational-ai]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[refactoring]]></category>
            <dc:creator><![CDATA[Noel Jaymon]]></dc:creator>
            <pubDate>Wed, 08 Dec 2021 05:12:01 GMT</pubDate>
            <atom:updated>2021-12-13T06:38:50.487Z</atom:updated>
            <content:encoded><![CDATA[<p>Most of the time the first solution that pops up in our mind is not the best solution. It is only through experience and improving one’s logical thinking and problem-solving skills that one can come up with an optimized approach for a given problem. It is a common observation that most of the code in JS gets nested because of the various conditions one has to handle for the solution.</p><p>Hopefully, you get to learn something new today and become a better developer by writing clean, readable, and optimized code.</p><ol><li><a href="https://www.programiz.com/javascript/ternary-operator">Ternary operator</a></li><li><a href="https://www.w3schools.com/js/js_switch.asp">Switch Case</a></li><li><a href="https://www.geeksforgeeks.org/javascript-short-circuiting/">Short Circuit</a> (Using Logical Operators)</li><li><a href="https://learningactors.com/javascript-guard-clauses-how-you-can-refactor-conditional-logic/">Guard clauses</a></li><li>Function delegation</li></ol><p>Let&#39;s check out each of these methods in detail now.</p><ol><li><strong>Ternary Operator<br></strong>This is the best and most common way to replace your “if…else” statements. In the field of conversational AI, one will encounter a situation where you have to check the platform from where the bot is triggered and give a response accordingly. This is the best example to use a ternary operator rather than using an if statement to check the condition.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*_4kr2ZB-Ab89Ie1i_Vmekg.png" /><figcaption>Ternary operator</figcaption></figure><p><strong>2. Switch Case<br></strong>The switch case statement is not the best possible way to replace nested “if-else” statements but these can be used to reduce duplicate code which is another common mistake ignored by developers in the field of conversational AI.<br>Many times we expect the virtual agent to give a static or simple response for different User Intents. When we implement the fulfillment logic for this we tend to unknowingly produce duplicate code.<br>These situations can be eliminated by using switch case statements as a common logic can be executed for multiple cases and other simple responses can be covered under separate cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*FSpfHQ12ItbNUs_pzsSLTg.png" /><figcaption>Switch Case</figcaption></figure><p><strong>3. Short-Circuiting<br></strong>In this approach, we will use logical operators like “ &amp;&amp; ” (AND) and “||” (OR). The Working of these operators is complementary to each other.<br>For example, The right side of the “ AND ” operator is executed only if the left side is true while the right side of the “ OR ” operator is executed only if the left side is false. We can use this logic to easily remove the nesting in our code.<br>This can be useful for setting a custom exit message at the end of a conversation.<br>Also, remember that there are few expressions that are always falsy(converted to false)<br><em>eg: null, undefined, NaN, an empty string(“”)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*LFIE5kIny_zgCWrfP_4lxA.png" /><figcaption>Short Circuit Method</figcaption></figure><p>4. <strong>Guard Clauses<br></strong>These are used as an early exit strategy. We define our conditions in such a way that the loop is exited for every check. This strategy makes the code more readable and optimized.<br>This can be used in situations where we check if the user is authenticated and perform some actions accordingly(eg: Triggering an event for user intent)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*OtjxQWnFhfXpUa7SuMFUng.png" /><figcaption>Guard Clauses</figcaption></figure><p>5. <strong>Function Delegation<br></strong>This strategy is very useful to understand the concept of closures in JS. Dividing the use-case into sub-cases and creating a function for each will help to eliminate the levels of nesting. We can combine all the above-discussed strategies and combine them to achieve the best possible code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/1*lOgPtzMygwwgBLo-4SHuEA.png" /><figcaption>Without Function Delegation</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*JWtDYszsKUp_n-UhukexBg.png" /><figcaption>With Function Delegation</figcaption></figure><p>You can clearly see the concept of closures implemented as the parameters of the outer function are accessible to the inner functions</p><p>Hope this was helpful for everyone and especially to the folks from the conversational AI domain.</p><p>For folks not from conversational AI backgrounds, I would recommend you to go through the hyperlinked texts for each of the approaches above as they will help you understand the concepts better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RA5ql5MnwhdJ-jxf.jpg" /><figcaption>End</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6d8a9db2db3" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/refactoring-nested-loops-in-js-e6d8a9db2db3">Refactoring If..Else Statement In JS</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>