<?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 Mohd Gufran on Medium]]></title>
        <description><![CDATA[Stories by Mohd Gufran on Medium]]></description>
        <link>https://medium.com/@mohd.gufran?source=rss-ab25a514734e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*B9r7ATFYxKRDOXZp</url>
            <title>Stories by Mohd Gufran on Medium</title>
            <link>https://medium.com/@mohd.gufran?source=rss-ab25a514734e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 10:39:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mohd.gufran/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[Jev: The Rise of AI Decision Models]]></title>
            <link>https://medium.com/@mohd.gufran/jev-the-rise-of-ai-decision-models-09598ca7e4d1?source=rss-ab25a514734e------2</link>
            <guid isPermaLink="false">https://medium.com/p/09598ca7e4d1</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[system-one-model]]></category>
            <category><![CDATA[jevs]]></category>
            <dc:creator><![CDATA[Mohd Gufran]]></dc:creator>
            <pubDate>Wed, 23 Sep 2026 08:14:58 GMT</pubDate>
            <atom:updated>2026-09-23T08:14:58.466Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>LLMs generate. Decision models decide. Code executes.</strong></p><p>For the last few years, the default architecture for adding AI to software has looked something like this:</p><pre>User<br>  ↓<br>Prompt<br>  ↓<br>LLM<br>  ↓<br>Generated text<br>  ↓<br>Parse / Validate<br>  ↓<br>Application</pre><p>This works incredibly well for chat, coding, summarization, reasoning, and content generation.</p><p>But consider these questions:</p><ul><li>Should this API request be retried?</li><li>Which team should handle this incident?</li><li>Should this transaction be flagged?</li><li>Should an AI agent ask a human for approval?</li><li>Which model should handle this request?</li><li>Is this document relevant?</li><li>How urgent is this ticket?</li></ul><p>The application doesn’t need a paragraph.</p><p><strong><em>It needs a decision.</em></strong></p><p>This is where <strong>Jev</strong> comes in.</p><p>Jev is TypeSafe AI’s first public <strong>System One</strong> model, designed for fast, structured decisions that software can consume directly. A key part of its approach is <strong>RLCD (Reinforcement Learning for Calibrated Decisions)</strong>, which focuses not only on making the right decision, but also on producing meaningful confidence around that decision.</p><h3>1. LLMs Are Great at Generation</h3><p>An LLM essentially gives us:</p><pre>Input<br>  ↓<br>LLM<br>  ↓<br>Tokens<br>  ↓<br>Text</pre><p>For example:</p><pre>User:<br>&quot;My Kubernetes pod keeps restarting. What should I check?&quot;</pre><pre>LLM:<br>&quot;Start by checking the pod logs using kubectl logs...&quot;</pre><p>The output space is almost unlimited.</p><p>That’s exactly what makes LLMs powerful.</p><p>But imagine asking:</p><pre>Should I retry this request?</pre><p>and forcing the LLM to generate:</p><pre>{<br>  &quot;decision&quot;: &quot;RETRY&quot;<br>}</pre><p>The application then has to:</p><pre>LLM<br> ↓<br>Generated string<br> ↓<br>Parse JSON<br> ↓<br>Validate schema<br> ↓<br>Check allowed values<br> ↓<br>Execute</pre><p>We’re using a <strong>generative interface for a decision problem</strong>.</p><h3>2. What Is Jev?</h3><p>Jev changes the abstraction.</p><p>Instead of:</p><pre>Prompt → Generate text</pre><p>the model is designed around:</p><pre>State + Question → Decision</pre><p>For example:</p><pre>State:<br>&quot;Backup job failed three times because<br>of a storage timeout.&quot;</pre><pre>Question:<br>&quot;Which team should handle this?&quot;</pre><pre>Choices:<br>- storage<br>- networking<br>- billing<br>- security</pre><p>The model returns a structured decision rather than a paragraph.</p><p>Conceptually:</p><pre>{<br>  &quot;choice&quot;: &quot;storage&quot;,<br>  &quot;probabilities&quot;: {<br>    &quot;storage&quot;: 0.91,<br>    &quot;networking&quot;: 0.05,<br>    &quot;billing&quot;: 0.01,<br>    &quot;security&quot;: 0.03<br>  }<br>}</pre><p>TypeSafe describes this as:</p><blockquote><strong><em>“unstructured state in, typed probabilistic decisions out.”</em></strong></blockquote><p>That’s the key idea.</p><h3>3. LLM vs Jev</h3><p><strong>LLM → Generate</strong><br>Takes a prompt and context, then generates text, code, explanations, or plans.</p><p><strong>Jev / System One → Decide</strong><br>Takes a state and a question, then produces a structured decision, often with a probability or confidence signal.</p><pre>LLM<br>Prompt + Context → Generated Output</pre><pre>Jev<br>State + Question → Decision + Probability</pre><p>An LLM can also classify, route, or score — but Jev is designed specifically around these <strong>bounded decision problems</strong>.</p><p>So the simplest mental model is:</p><blockquote><strong><em>LLMs generate. Jev decides. Code executes.</em></strong></blockquote><p>The interesting part is that they can work together: an LLM can reason and generate a plan, while Jev can make the critical decisions that determine what happens next.</p><p>The important point is:</p><blockquote><strong><em>Jev isn’t necessarily a replacement for an LLM. It is a different primitive.</em></strong></blockquote><h3>4. Three Decision Primitives</h3><p>TypeSafe’s current API exposes three major question types.</p><h3>Choice</h3><p>Choose one option:</p><pre>Which team owns this issue?</pre><pre>storage<br>networking<br>billing<br>security</pre><h3>Score</h3><p>Evaluate something on a scale:</p><pre>How severe is this incident?</pre><pre>1 ───────── 10</pre><h3>Noul</h3><p>A yes/no proposition represented probabilistically:</p><pre>Does this request require human review?</pre><p>These primitives are deliberately simple.</p><p>The complexity lives in the <strong>state and reasoning</strong>, not in the output format.</p><h3>5. Why Probability Matters</h3><p>Consider:</p><pre>RETRY</pre><p>versus:</p><pre>RETRY<br>Probability = 0.97</pre><p>The second result allows your application to define a policy:</p><pre>Probability<br>                  │<br>       ┌──────────┼──────────┐<br>       ↓          ↓          ↓<br>     &gt;95%      70–95%      &lt;70%<br>       ↓          ↓          ↓<br>    Automate   Review      Reject</pre><p>This is where decision models become particularly interesting.</p><p>The model provides the <strong>signal</strong>.</p><p>Your application defines the <strong>policy</strong>.</p><h3>6. Calibration: Can We Trust the Probability?</h3><p>A probability is useful only when it reflects reality.</p><p>If a model predicts <strong>80% confidence</strong> for 100 cases, a well-calibrated model should be correct in roughly <strong>80 of them</strong>.</p><pre>Accuracy:<br>&quot;Was the prediction correct?&quot;</pre><pre>Calibration:<br>&quot;Does my confidence match how often I&#39;m correct?&quot;</pre><p>A model can have high accuracy but still be <strong>overconfident</strong>.</p><p>For automated systems, that difference matters because confidence helps determine <strong>when to act automatically and when to ask for human review</strong>.</p><p>This is one of the key ideas behind System One models.</p><h3>7. RLCD: Reinforcement Learning for Calibrated Decisions</h3><p>TypeSafe says Jev is trained using:</p><p><strong>RLCD — Reinforcement Learning for Calibrated Decisions.</strong></p><p>Traditional LLMs mainly focus on producing the right or useful answer.</p><p>Decision models have an additional goal: <strong>knowing how confident they should be in that decision</strong>.</p><pre>Traditional model<br>→ Get the answer right</pre><pre>Decision model<br>→ Get the decision right<br>→ Know how confident to be</pre><p>For example, imagine a model makes 100 predictions and says <strong>“90% confident”</strong> each time.</p><p>If it is correct only 60 times, something is wrong with its confidence.</p><p>A well-calibrated model should be correct roughly <strong>90 times</strong>.</p><p>This is where calibration becomes important:<br><strong>the confidence should match reality.</strong></p><p>One way to measure this is with the <strong>Brier score</strong>:</p><pre>Brier Score = (Prediction − Actual)²</pre><p>If the actual outcome is 1:</p><pre>Prediction = 0.9 → Loss = 0.01<br>Prediction = 0.1 → Loss = 0.81</pre><p>The second prediction is much worse because the model was <strong>very confident in the wrong direction</strong>.</p><blockquote><strong><em>Note:</em></strong><em> The Brier score is used here only to explain the idea of calibration. It is not a claim that Jev uses Brier loss internally. TypeSafe has described its RLCD objective, but has not published a complete reproducible training recipe.</em></blockquote><h3>8. Why Not Just Use Structured Outputs From an LLM?</h3><p>This is an important question.</p><p>Modern LLMs can already produce:</p><pre>{<br>  &quot;decision&quot;: &quot;RETRY&quot;<br>}</pre><p>So what’s different?</p><p>The distinction isn’t simply:</p><blockquote><em>“Can the model produce JSON?”</em></blockquote><p>It can.</p><p>The deeper distinction is:</p><p>LLM:</p><pre>Generate tokens<br>     ↓<br>Constrain them into a schema<br>     ↓<br>Get structured output</pre><p>versus the System One idea:</p><p>Decision modeils:</p><pre>Question defines valid output<br>     ↓<br>Model evaluates question<br>     ↓<br>Typed decision + probability</pre><p>TypeSafe also describes Jev’s sampling as parallel rather than autoregressive token-by-token generation. Its claim is that removing general string generation allows a different efficiency/latency tradeoff.</p><p>So the difference is not merely <strong>JSON mode vs no JSON mode</strong>.</p><p>It is a difference in:</p><ul><li>model interface</li><li>output space</li><li>sampling</li><li>training objective</li><li>optimization target</li></ul><h3>9. The Architecture Gets Interesting When We Combine Them</h3><p>The most interesting question isn’t:</p><pre>Jev vs LLM</pre><p>It’s:</p><pre>Jev + LLM + Code</pre><p>Consider an AI agent.</p><h3>Traditional agent</h3><pre>User<br> ↓<br>LLM<br> ↓<br>Reason<br> ↓<br>Generate tool call<br> ↓<br>Execute<br> ↓<br>LLM<br> ↓<br>...</pre><h3>Decision-aware agent</h3><pre>User<br>                      │<br>                      ↓<br>                    LLM<br>               Understand / Plan<br>                      │<br>                      ↓<br>                    Jev<br>              Decide / Classify<br>                      │<br>          ┌───────────┼───────────┐<br>          ↓           ↓           ↓<br>        Tool        Retry       Human<br>          │           │           │<br>          └───────────┼───────────┘<br>                      ↓<br>                   Execute</pre><p>The LLM handles open-ended reasoning.</p><p>Jev handles bounded decisions.</p><p>Code handles execution.</p><h3>10. Example: Intelligent Model Routing</h3><p>Suppose your application has:</p><pre>Small LLM<br>Medium LLM<br>Frontier LLM</pre><p>You don’t necessarily want every request to use the most expensive model.</p><p>Ask a decision model:</p><pre>How complex is this request?</pre><pre>1 = Simple<br>2 = Moderate<br>3 = Complex</pre><p>Then:</p><pre>if (complexity === &quot;simple&quot;) {<br>    useSmallModel();<br>} else if (complexity === &quot;moderate&quot;) {<br>    useMediumModel();<br>} else {<br>    useFrontierModel();<br>}</pre><p>The decision model becomes an <strong>AI router</strong>.</p><h3>11. Example: AI Guardrails</h3><p>Imagine an agent proposes:</p><pre>DELETE BACKUP INSTANCE</pre><p>Don’t let the same model automatically authorize its own action.</p><p>Instead:</p><p>The LLM generates the action.</p><p>The decision model evaluates it.</p><p>Your application controls execution.</p><p>This gives us an important engineering principle:</p><blockquote><strong><em>Generation and authorization don’t have to be performed by the same model.</em></strong></blockquote><h3>12. Build a Small LLM + Jev Application</h3><p>Let’s imagine we’re building an incident assistant.</p><p>A user sends:</p><pre>&quot;My backup failed three times with a storage timeout.&quot;</pre><h3>Step 1 — LLM</h3><p>The LLM extracts the broader context:</p><pre>Product: Backup<br>Problem: Failed operation<br>Potential cause: Storage timeout</pre><h3>Step 2 — Jev</h3><p>Ask:</p><pre>Is this a storage-related incident?<br>Should this be escalated?<br>How severe is the incident?</pre><h3>Step 3 — Application code</h3><pre>if storage_related:<br>    team = &quot;storage&quot;<br>if escalation_probability &gt; 0.9:<br>    create_incident()<br>if severity &gt;= 8:<br>    page_on_call()</pre><h3>Step 4 — LLM</h3><p>Finally:</p><pre>&quot;The backup failure appears to be related<br>to storage. I&#39;ve routed the issue to the<br>storage team and created an incident.&quot;</pre><p>The complete architecture becomes:</p><pre>User<br> ↓<br>LLM → Understand<br> ↓<br>Jev → Decide<br> ↓<br>Code → Execute<br> ↓<br>LLM → Explain</pre><p>This is a much more modular AI system than asking one model to do everything.</p><h3>13. The Bigger Idea: AI as a Software Primitive</h3><p>We’ve traditionally thought about AI like this:</p><pre>Prompt → Model → Text</pre><p>System One suggests another abstraction:</p><pre>State → Question → Decision → Action</pre><p>That is a very different way to build AI software.</p><p>Instead of one enormous model doing everything:</p><pre>AI Application<br>                       │<br>        ┌──────────────┼──────────────┐<br>        ↓              ↓              ↓<br>       LLM            Jev            Code<br>        │              │              │<br>    Generate         Decide        Execute<br>        │              │              │<br>        └──────────────┼──────────────┘<br>                       ↓<br>                     Human</pre><p>Each component has a clear responsibility.</p><p>That’s something software engineers already understand:</p><blockquote><strong><em>Separation of concerns.</em></strong></blockquote><h3>14. Final Takeaway</h3><p>The interesting shift isn’t:</p><blockquote><strong><em>“Jev will replace LLMs.”</em></strong></blockquote><p>It is:</p><blockquote><strong><em>“Maybe we shouldn’t use a generative model for every AI problem.”</em></strong></blockquote><p>LLMs are extremely good at:</p><pre>Understanding<br>Reasoning<br>Generating<br>Explaining</pre><p>Decision models are designed for:</p><pre>Classifying<br>Routing<br>Scoring<br>Evaluating<br>Selecting<br>Estimating uncertainty</pre><p>Traditional software remains responsible for:</p><pre>Rules<br>Permissions<br>Transactions<br>Execution<br>Security</pre><p>And humans remain important when:</p><pre>Consequences are high<br>+<br>Uncertainty is significant<br>+<br>Judgment is required</pre><p>So the mental model I would keep is:</p><pre>AI Application</pre><pre>LLM          → Think / Generate<br>Decision AI  → Decide<br>Code         → Execute<br>Human        → Govern</pre><p>The future of AI may therefore be less about finding <strong>one model that does everything</strong> and more about building <strong>systems where specialized models work together</strong>.</p><p>And that’s what makes Jev and System One models interesting.</p><blockquote><strong><em>LLMs generate. Decision models decide. Code executes. Humans govern.</em></strong></blockquote><p>That is a much more useful way to think about the next generation of AI-powered software.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=09598ca7e4d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Really Happens When You Open an App?]]></title>
            <link>https://medium.com/@mohd.gufran/what-really-happens-when-you-open-an-app-694f47a45141?source=rss-ab25a514734e------2</link>
            <guid isPermaLink="false">https://medium.com/p/694f47a45141</guid>
            <category><![CDATA[stack]]></category>
            <category><![CDATA[heap-vs-stack]]></category>
            <category><![CDATA[rams]]></category>
            <category><![CDATA[heap-memory]]></category>
            <dc:creator><![CDATA[Mohd Gufran]]></dc:creator>
            <pubDate>Mon, 11 May 2026 02:57:40 GMT</pubDate>
            <atom:updated>2026-05-11T02:57:40.876Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding RAM, Stack, Heap Memory — In the Simplest Way Possible</h3><p>Most people think that when we open an app, the entire application directly gets loaded into RAM and starts running.</p><p>But that is not how computers actually work.</p><p>Behind every app opening , whether it is Instagram, Chrome, PUBG, VS Code, or even a Calculator, there is an entire memory management system working silently.</p><p>And two of the most important parts of that system are:</p><h3>Stack Memory and Heap Memory</h3><p>If you have ever heard developers saying:</p><ul><li>“This is stored in stack”</li><li>“Objects go to heap”</li><li>“Stack overflow”</li><li>“Heap allocation is expensive”</li></ul><p>then this blog will finally make all of it crystal clear.</p><p>Not just for programmers.</p><p>But for anyone curious about how apps actually work internally.</p><h3>Step 1 — What Happens When You Open an App?</h3><p>Suppose you click on Chrome.</p><p>Your operating system:</p><ul><li>Windows</li><li>Linux</li><li>macOS</li><li>Android</li></ul><p>creates something called a: <strong>Process</strong></p><p>A process is basically: <em>A running instance of a program.</em></p><p>Now the OS allocates some space in: <strong>RAM</strong> (Main Memory) for that process.</p><h3>RAM is the Real Physical Memory</h3><p>RAM is the actual hardware memory inside your computer or phone.</p><p>Everything an app actively needs while running goes into RAM.</p><p>But RAM is not used randomly.</p><p>The OS divides the app memory into sections.</p><p>Something like this:</p><pre>+------------------------------------------------+<br>| CODE SECTION                                   |<br>| Application instructions                       |<br>+------------------------------------------------+<br>| GLOBAL VARIABLES                               |<br>+------------------------------------------------+<br>|                                                |<br>|                   HEAP                         |<br>|      Dynamic Objects, Arrays, App Data         |<br>|                                                |<br>+------------------------------------------------+<br>|                   STACK                        |<br>|     Function Calls, Local Variables            |<br>+------------------------------------------------+</pre><p>Now let’s understand the two most important regions.</p><h3>Stack Memory — The Fast Working Area</h3><p>Stack memory is used for:</p><ul><li>function calls</li><li>local variables</li><li>temporary calculations</li><li>execution flow</li></ul><p>Think of stack like:</p><h3>A student’s desk during an exam</h3><p>Only current work is kept there.</p><p>As soon as work finishes, the space becomes free again.</p><h3>Why Is It Called Stack?</h3><p>Because it behaves exactly like a stack of books.</p><pre>Top<br>+---------+<br>| Book 3  |<br>+---------+<br>| Book 2  |<br>+---------+<br>| Book 1  |<br>+---------+<br>Bottom</pre><p>The last book placed is the first removed.</p><p>This is called: <strong>LIFO </strong>(Last In First Out)</p><h3>Example of Stack in Code</h3><pre>function add() {<br>   let a = 10;<br>   let b = 20;<br>   let sum = a + b;<br>}</pre><p>When this function runs:</p><pre>STACK<br>----------------<br>sum = 30<br>b = 20<br>a = 10<br>----------------</pre><p>When the function ends:</p><pre>STACK CLEARED</pre><p>Everything gets removed automatically.</p><p>No cleanup required.</p><p>That is why stack is:</p><ul><li>extremely fast</li><li>lightweight</li><li>efficient</li></ul><h3>Why Stack is So Fast</h3><p>Stack allocation is incredibly simple.</p><p>The CPU only moves a pointer.</p><pre>Stack Pointer ↓</pre><pre>+-----------+<br>| New Data  |<br>+-----------+<br>| Old Data  |<br>+-----------+</pre><p>No searching.</p><p>No tracking.</p><p>No fragmentation handling.</p><p>Just push and pop.</p><p>That is why stack operations are very fast.</p><h3>But If Stack is So Fast… Why Not Store Everything There?</h3><p>This is where most beginners get confused.</p><p>The answer is:</p><h3>Stack is intentionally small.</h3><p>Even though stack is inside RAM, the OS only reserves a limited portion for it.</p><p>Usually:</p><ul><li>1 MB</li><li>2 MB</li><li>8 MB</li></ul><p>per thread.</p><p>Why?</p><p>Because every thread gets its own stack.</p><p>Imagine:</p><pre>1000 threads</pre><p>If each stack was huge:</p><pre>1 GB each</pre><p>your RAM would finish instantly.</p><p>So stack is optimized for:</p><ul><li>speed</li><li>predictability</li><li>temporary work</li></ul><p>not for huge storage.</p><h3>Heap Memory — The Flexible Storage Area</h3><p>Heap memory is used for:</p><ul><li>objects</li><li>arrays</li><li>dynamic data</li><li>large structures</li><li>app state</li><li>data that survives longer</li></ul><p>Think of heap like:</p><h3>A warehouse</h3><p>Items can be stored anywhere.</p><p>Large things can be kept there.</p><p>Data can grow and shrink dynamically.</p><h3>Example of Heap</h3><pre>let user = {<br>   name: &quot;Ali&quot;,<br>   age: 20<br>};</pre><p>Memory internally looks like:</p><pre>STACK<br>----------------<br>user -&gt; address 100<br>----------------<br></pre><pre>HEAP<br>----------------<br>Address 100:<br>{<br>  name: &quot;Ali&quot;,<br>  age: 20<br>}<br>----------------</pre><p>The actual object lives in heap.</p><p>Stack only stores the reference.</p><h3>Why Objects Usually Go to Heap</h3><p>Because objects are dynamic.</p><p>Example:</p><pre>user.city = &quot;Delhi&quot;;</pre><p>Now the object size increased.</p><p>Heap can handle this flexibility.</p><p>Stack cannot efficiently manage such dynamic growth.</p><h3>Real Difference Between Stack and Heap</h3><pre>| Feature    | Stack          | Heap           |<br>| ---------- | -------------- | -------------- |<br>| Speed      | Very Fast      | Slower         |<br>| Size       | Small          | Large          |<br>| Structure  | Sequential     | Flexible       |<br>| Allocation | Automatic      | Dynamic        |<br>| Cleanup    | Automatic      | Manual / GC    |<br>| Best For   | Temporary Data | Long-Term Data |</pre><h3>What About App Size vs RAM?</h3><p>Suppose:</p><pre>App Size = 20 MB<br>Available RAM = 10 MB</pre><p>Can the app run?</p><p>Possibly yes.</p><p>Because:</p><h3>App size and RAM usage are completely different things.</h3><p>App size means:</p><pre>Storage size on disk</pre><p>RAM usage means:</p><pre>Runtime memory requirement</pre><p>An app does NOT load entirely into RAM.</p><p>Modern operating systems use:</p><h3>Demand Paging</h3><p>meaning: <em>Only necessary parts are loaded into RAM when needed.</em></p><p>That is why:</p><ul><li>a 100 GB game can run on 16 GB RAM</li><li>Chrome installer may be 100 MB but use 2 GB RAM</li></ul><h3>What Happens If RAM Is Less?</h3><p>The OS may use: <strong>Virtual Memory</strong></p><p>which means:</p><ul><li>part RAM</li><li>part disk storage</li></ul><p>Disk acts like temporary memory.</p><p>But disks are much slower than RAM.</p><p>So performance drops heavily.</p><h3>What is Stack Overflow?</h3><p>Suppose a function keeps calling itself.</p><pre>function test() {<br>   test();<br>}</pre><p>Every call creates a new stack frame.</p><pre>+-------------+<br>| test()      |<br>+-------------+<br>| test()      |<br>+-------------+<br>| test()      |<br>+-------------+</pre><p>Eventually stack memory becomes full.</p><p>This causes: <strong>Stack Overflow</strong></p><h3>Why Heap is Slower</h3><p>Heap allocation is more complex.</p><p>The system must:</p><ul><li>find free space</li><li>track used blocks</li><li>manage fragmentation</li><li>handle garbage collection</li></ul><p>Example:</p><pre>[Used][Free][Used][Free]</pre><p>Finding suitable space takes time.</p><p>That is why heap is slower.</p><h3>Can We Write Faster Code Using More Stack?</h3><p>Yes — but carefully.</p><p>Good developers try to:</p><ul><li>reduce unnecessary heap allocations</li><li>keep temporary data on stack</li><li>reuse memory</li><li>reduce object creation</li></ul><p>But you cannot force everything into stack.</p><p>Because stack is small and temporary.</p><h3>Stack Optimization Techniques</h3><h3>1. Avoid Huge Local Variables</h3><p>Bad:</p><pre>void process() {<br>   int hugeArray[1000000];<br>}</pre><p>May crash due to stack overflow.</p><h3>2. Reduce Deep Recursion</h3><p>Bad recursion consumes stack repeatedly.</p><p>Better:</p><pre>for(int i=0;i&lt;n;i++) {<br>   // iterative approach<br>}</pre><h3>3. Pass Large Objects by Reference</h3><p>Bad:</p><pre>void process(BigObject obj)</pre><p>Copies huge data into stack.</p><p>Better:</p><pre>void process(const BigObject&amp; obj)</pre><p>Only reference passed.</p><h3>4. Reuse Memory</h3><p>High-performance apps reuse buffers and objects instead of repeatedly creating new ones.</p><p>Especially:</p><ul><li>game engines</li><li>browsers</li><li>operating systems</li></ul><h3>Real-World Examples</h3><h3>Instagram</h3><h3>Stack handles:</h3><ul><li>button click functions</li><li>temporary execution</li><li>calculations</li></ul><h3>Heap handles:</h3><ul><li>feed data</li><li>stories</li><li>comments</li><li>reels</li><li>cache</li></ul><h3>PUBG / GTA</h3><h3>Stack:</h3><ul><li>physics calculations</li><li>temporary computations</li><li>execution flow</li></ul><h3>Heap:</h3><ul><li>map data</li><li>textures</li><li>players</li><li>inventory</li><li>vehicles</li></ul><h3>Simple Analogy That Explains Everything</h3><p>Imagine building construction.</p><h3>Stack = Engineer’s Work Desk</h3><ul><li>quick notes</li><li>temporary calculations</li><li>fast access</li><li>limited space</li></ul><h3>Heap = Material Warehouse</h3><ul><li>large storage</li><li>flexible</li><li>dynamic</li><li>long-term items</li></ul><p>A real project needs BOTH.</p><p>Only desk?</p><p>Impossible.</p><p>Only warehouse?</p><p>Slow and messy.</p><h3>Final Understanding</h3><p>When an app opens:</p><ol><li>OS creates a process</li><li>RAM is allocated</li><li>Memory gets divided into sections</li><li>Stack manages execution</li><li>Heap manages dynamic data</li></ol><p>And that is how modern applications actually run internally.</p><h3>One-Line Summary</h3><blockquote><em>Stack memory is a small, super-fast temporary workspace for execution, while heap memory is a large flexible storage area used for dynamic application data.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=694f47a45141" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kafka Explained Like You’re Just Living Your Life]]></title>
            <link>https://medium.com/@mohd.gufran/kafka-explained-like-youre-just-living-your-life-ddd35eb73837?source=rss-ab25a514734e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ddd35eb73837</guid>
            <category><![CDATA[apache-kafka]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[computer-engineering]]></category>
            <category><![CDATA[kafka]]></category>
            <dc:creator><![CDATA[Mohd Gufran]]></dc:creator>
            <pubDate>Wed, 06 May 2026 14:31:01 GMT</pubDate>
            <atom:updated>2026-05-06T14:31:01.397Z</atom:updated>
            <content:encoded><![CDATA[<p>We often hear big tech words like <em>event streaming</em>, <em>distributed systems</em>, or <em>real-time pipelines</em>. And then there’s <strong>Apache Kafka</strong>, which somehow sounds even more intimidating.</p><p>But honestly, Kafka is not that complicated.</p><p>Let’s understand it the way we understand… life.</p><h3>It Starts With Something Very Normal</h3><p>Imagine you’re sitting with your friends.</p><p>You say:<br><em>“Let’s go on a trip.”</em></p><p>Now look what happens:</p><ul><li>One friend starts checking hotels</li><li>Another looks for transport</li><li>Someone creates a WhatsApp group</li><li>Someone else checks budgets</li></ul><p>You said <strong>one thing</strong>, but <strong>multiple things started happening at the same time</strong>.</p><p>You didn’t coordinate everything manually.<br>People just <em>picked up the information and acted on it</em>.</p><p>That’s exactly what Kafka does in software systems.</p><h3>So What is Kafka, Really?</h3><p>Kafka is like a <strong>middle layer that carries information from one place to many places</strong>.</p><ul><li>One system sends data → <em>“Hey, something happened!”</em></li><li>Kafka stores it</li><li>Multiple systems read it and react</li></ul><p>No direct connections. No chaos. Just smooth flow.</p><h3>Real-Life Example: Food Delivery</h3><p>Let’s take something we all relate to — ordering food.</p><p>You place an order on an app.</p><p>Behind the scenes:</p><ul><li>Order service says: <em>“New order placed”</em> → sends to Kafka</li><li>Restaurant system reads it → starts cooking</li><li>Delivery system reads it → assigns a rider</li><li>Notification system reads it → sends you updates</li></ul><p>All of this happens <strong>independently</strong>, but based on the same event.</p><p>You didn’t place 4 different requests.<br>You placed <strong>one</strong>, and Kafka made sure everyone who needed it got it.</p><h3>Another Example: Traffic Signals</h3><p>Think of Kafka like a <strong>traffic signal system for data</strong>.</p><ul><li>Cars = data</li><li>Roads = topics</li><li>Signals = Kafka controlling flow</li></ul><p>Without signals → chaos<br>With signals → smooth movement</p><p>Kafka ensures data moves in an <strong>organized and predictable way</strong>.</p><h3>A Few Terms (Without Making It Boring)</h3><p>You don’t need to memorize these, just <em>get the feel</em>:</p><ul><li><strong>Producer</strong> → the one who sends data<br>(like you placing an order)</li><li><strong>Consumer</strong> → the one who reads data<br>(restaurant, delivery, notifications)</li><li><strong>Topic</strong> → a category of messages<br>(like “orders”, “payments”, “notifications”)</li><li><strong>Broker</strong> → Kafka server managing everything</li></ul><h3>Why Companies Love Kafka</h3><p>Because real systems are messy.</p><p>Without Kafka:</p><ul><li>Everything is tightly connected</li><li>One failure can break everything</li><li>Scaling becomes painful</li></ul><p>With Kafka:</p><ul><li>Systems are loosely connected</li><li>They don’t depend directly on each other</li><li>You can scale easily</li><li>You can process <strong>millions of events in real time</strong></li></ul><p>That’s why companies like Uber, Netflix, and banks rely heavily on it.</p><h3>A Simple Way to Remember</h3><p>Think of Kafka as:</p><p>A <strong>group chat</strong>, where one message is sent<br>And everyone who cares about it reacts in their own way</p><h3>Final Thought</h3><p>Kafka is not just a tool.<br>It’s a way of designing systems where:</p><ul><li>One action</li><li>Triggers multiple reactions</li><li>Without everything being tightly glued together</li></ul><p>And once you start seeing systems like this…<br>you’ll notice Kafka-like patterns everywhere — even in real life.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ddd35eb73837" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Ride Apps Use a 4-Digit PIN]]></title>
            <link>https://medium.com/@mohd.gufran/why-ride-apps-use-a-4-digit-pin-fa4574477dd1?source=rss-ab25a514734e------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa4574477dd1</guid>
            <category><![CDATA[ola]]></category>
            <category><![CDATA[uber]]></category>
            <category><![CDATA[abc]]></category>
            <category><![CDATA[rapido]]></category>
            <dc:creator><![CDATA[Mohd Gufran]]></dc:creator>
            <pubDate>Tue, 21 Apr 2026 14:31:01 GMT</pubDate>
            <atom:updated>2026-04-21T14:31:01.738Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve ever used apps like Rapido, Uber, or Ola, you’ve probably noticed something curious:</p><p>Before your ride starts, the driver asks for a <strong>4-digit PIN</strong>.</p><p>At first glance, this feels… unnecessary.</p><p>After all, the system already knows:</p><ul><li>Who the customer is</li><li>Who the driver is</li><li>Which ride is booked</li></ul><p>So why add another step?</p><p>And more importantly — how does a <strong>4-digit PIN (just 10,000 combinations)</strong> work for <strong>millions of users</strong>?</p><p>Let’s break it down.</p><h3>The Common Misconception: “4 Digits = Only 10,000 Users”</h3><p>A 4-digit PIN ranges from 0000 to 9999.</p><p>That gives us <strong>10,000 combinations</strong>.</p><p>So it’s natural to think:<br><em>“Does that mean only 10,000 rides can exist at once?”</em></p><p>Not at all.</p><p>Because the PIN is <strong>not globally unique</strong>.</p><h3>The Key Idea: The PIN Is Contextual, Not Universal</h3><p>Internally, every ride has a unique identity:</p><ul><li>ride_id (unique)</li><li>driver_id</li><li>customer_id</li><li>pin (4-digit, temporary)</li></ul><p>So instead of checking:</p><pre>Is PIN = 4821 valid?</pre><p>The system checks:<br>It validates the PIN <strong>along with the ride ID, customer ID, and driver ID</strong> to ensure it matches the exact ride.</p><pre>Does (PIN = 4821 AND ride_id AND customer_id AND driver_id) match a valid ride record?</pre><p>That means:</p><ul><li>Multiple users can have the same PIN at the same time</li><li>No conflicts happen because each PIN is tied to a <strong>specific ride context</strong></li></ul><h3>So Why Use a PIN at All?</h3><p>This is where things get interesting.</p><p>The PIN is not for the backend.</p><p>It’s for the <strong>real world</strong>.</p><h3>Problem 1: Identifying the Right Human</h3><p>Imagine a crowded pickup spot:</p><ul><li>5 people standing nearby</li><li>Everyone looking at their phone</li><li>Driver calls out a name</li></ul><p>Chances are:</p><ul><li>Someone responds incorrectly</li><li>Or confusion slows everything down</li></ul><p>The system knows who you are.</p><p>But the <strong>driver doesn’t</strong>.</p><p>The PIN acts as a <strong>shared secret</strong> between driver and rider.</p><h3>Problem 2: Preventing Wrong Pickups</h3><p>Without a PIN:</p><ul><li>Someone could mistakenly (or intentionally) take your ride</li><li>Driver might start the trip with the wrong person</li></ul><p>With a PIN:</p><ul><li>Only the actual rider can provide it</li><li>It confirms: <em>“Yes, this is the correct passenger”</em></li></ul><h3>Problem 3: Security and Fraud Prevention</h3><p>The PIN helps prevent:</p><ul><li>Unauthorized ride starts</li><li>Fake passengers</li><li>Accidental ride mismatches</li></ul><p>It’s a simple but effective <strong>authentication layer</strong>.</p><h3>Problem 4: Works in Low Connectivity</h3><p>In many areas, network connectivity isn’t reliable.</p><p>Even if:</p><ul><li>The app lags</li><li>Data doesn’t sync instantly</li></ul><p>The driver can still ask:<br><em>“What’s your PIN?”</em></p><p>And verify instantly.</p><h3>Why Not Use Customer ID Instead?</h3><p>Good question.</p><p>Because:</p><ul><li>IDs are long and not human-friendly</li><li>Hard to communicate verbally</li><li>Potentially sensitive</li></ul><p>A PIN is:</p><ul><li>Short</li><li>Temporary</li><li>Easy to say and verify</li></ul><h3>System Design Perspective</h3><p>Internally:</p><ul><li>ride_id → uniquely identifies the ride</li><li>driver_id → identifies driver</li><li>customer_id → identifies user</li></ul><p>Externally:</p><ul><li>PIN → verifies the <strong>correct human in the physical world</strong></li></ul><p>This separation is intentional.</p><h3>A Simple Analogy</h3><p>Think about food delivery.</p><p>The delivery agent already has:</p><ul><li>Your order details</li><li>Your address</li></ul><p>Still, they ask:<br><em>“What’s your OTP?”</em></p><p>Same idea.</p><h3>Final Takeaway</h3><p>The 4-digit PIN isn’t about scaling users.</p><p>It’s about solving a <strong>real-world problem</strong>:<br><em>How do you ensure the driver picks the </em>right person<em> in a chaotic, physical<br>environment?</em></p><p>So even though:</p><ul><li>The backend doesn’t need it</li><li>The system already knows everything</li></ul><p>The PIN exists because:</p><ul><li>Humans make mistakes</li><li>Environments are unpredictable</li><li>Simplicity beats complexity</li></ul><p>And sometimes, <strong>4 digits are all you need</strong>.</p><p>If you enjoyed this breakdown, you’ll start noticing similar patterns in delivery apps, banking OTPs, and beyond — where simple UX hides smart system design.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa4574477dd1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Calling Deployable Architecture from UI]]></title>
            <link>https://medium.com/@mohd.gufran/calling-deployable-architecture-from-ui-34b9976ec6c9?source=rss-ab25a514734e------2</link>
            <guid isPermaLink="false">https://medium.com/p/34b9976ec6c9</guid>
            <category><![CDATA[deployable-architecture]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[terraform-modules]]></category>
            <category><![CDATA[apicart]]></category>
            <category><![CDATA[schematics-workspace]]></category>
            <dc:creator><![CDATA[Mohd Gufran]]></dc:creator>
            <pubDate>Tue, 07 Apr 2026 14:01:02 GMT</pubDate>
            <atom:updated>2026-04-07T14:01:02.418Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deployable Architecture</h3><p><strong>Deployable Architecture (DA)</strong> is a reusable, pre-packaged infrastructure template in IBM Cloud that allows developers to deploy multiple cloud resources using a single configuration.</p><p>Instead of manually:</p><ul><li>Creating services</li><li>Configuring connections</li><li>Setting permissions</li><li>Writing Terraform scripts</li></ul><p>Deployable Architecture lets you define everything once and reuse it across environments.</p><p><strong>In simple terms:</strong><br> Deployable Architecture = <strong>Infrastructure blueprint</strong><br> Input values = <strong>Configuration</strong><br> Output = <strong>Provisioned cloud resources</strong></p><p>For example, a DA can:</p><ul><li>Create a Backup instance</li><li>Create a connection</li><li>Configure access policies</li></ul><p>All in <strong>one deployment</strong>.</p><h3>Cart API</h3><p><strong>Cart API</strong> is the entry point used to trigger Deployable Architecture deployments.</p><p>It:</p><ul><li>Accepts deployment payload</li><li>Validates configuration</li><li>Creates deployment request</li><li>Triggers Schematics workspace</li></ul><p>Think of it like:<br><em>Add infrastructure to cart → checkout → deployment starts</em></p><h3>Schematics Workspace</h3><p>A <strong>Schematics workspace</strong> is automatically created when Cart API is called.</p><p>It:</p><ul><li>Stores deployment configuration</li><li>Pulls Deployable Architecture</li><li>Runs Terraform</li><li>Tracks deployment status</li></ul><p>This is where actual provisioning happens.</p><h3>Terraform Modules</h3><p>Inside Deployable Architecture are <strong>Terraform modules</strong>.</p><p>They:</p><ul><li>Define cloud resources</li><li>Configure dependencies</li><li>Handle provisioning logic</li></ul><p>Example Terraform actions:</p><ul><li>Create Backup instance</li><li>Create connection</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Vbyd1MZxtabrd3QuWa2iQ.png" /></figure><h3>How UI Calls Deployable Architecture</h3><p>Here is the <strong>simplified step-by-step flow</strong>:</p><h3>Step 1 — User fills form in UI</h3><p>User enters:</p><ul><li>Instance Name</li><li>Connection Name</li></ul><pre>Instance Name: my-backup-instance<br>Connection Name: my-backup-connection</pre><h3>Step 2 — User clicks Save</h3><p>React handler collects data:</p><pre>const handleSave = async () =&gt; {<br>  const payload = {<br>    instanceName,<br>    connectionName<br>  };<br>  await callIntegrationAPI(payload);<br>};</pre><h3>Step 3 — Backend builds DA payload</h3><pre>const buildCartPayload = (data) =&gt; {<br>  return {<br>    name: &quot;backup-da&quot;,<br>    description: &quot;Provision instance and connection&quot;,<br>    service_name: &quot;backup-service&quot;,<br>    cart_items: [{<br>          name: &quot;backup-da&quot;,<br>          catalog_id: &quot;catalog-id&quot;,<br>          offering_id: &quot;offering-id&quot;,<br>          offering_version: &quot;1.0.0&quot;,<br>          inputs: [<br>            {<br>              name: &quot;instance_name&quot;,<br>              value: data.instanceName,<br>              metadata: { type: &quot;string&quot; }<br>            },<br>            {<br>              name: &quot;connection_name&quot;,<br>              value: data.connectionName,<br>              metadata: { type: &quot;string&quot; }<br>            }<br>          ]<br>        }]<br>    };<br>};</pre><h3>Step 4 — Call Cart API</h3><pre>POST /v2/cart</pre><p>Payload:</p><pre>{<br>  &quot;name&quot;: &quot;backup-da&quot;,<br>  &quot;cart_items&quot;: [<br>    {<br>      &quot;catalog_id&quot;: &quot;catalog-id&quot;,<br>      &quot;offering_id&quot;: &quot;offering-id&quot;,<br>      &quot;offering_version&quot;: &quot;1.0.0&quot;,<br>      &quot;inputs&quot;: [<br>        {<br>          &quot;name&quot;: &quot;instance_name&quot;,<br>          &quot;value&quot;: &quot;my-backup-instance&quot;<br>        },<br>        {<br>          &quot;name&quot;: &quot;connection_name&quot;,<br>          &quot;value&quot;: &quot;my-backup-connection&quot;<br>        }<br>      ]<br>    }<br>  ]<br>}</pre><h3>Step 5 — Schematics Workspace Created</h3><p>Cart API automatically:</p><ul><li>Creates workspace</li><li>Downloads DA</li><li>Runs Terraform</li></ul><h3>Step 6 — Terraform Modules Execute</h3><p>Terraform provisions:</p><pre>Resource 1 → Backup Instance<br>Resource 2 → Backup Connection</pre><h3>Step 7 — Deployment Complete</h3><p>Result:</p><pre>✔ Instance created<br>✔ Connection created</pre><h3>Conclusion</h3><p>Deployable Architecture provides a structured and scalable way to automate infrastructure provisioning directly from applications. By using predefined templates, teams can standardize deployments, reduce manual configuration, and ensure consistency across environments.</p><p>When integrated into a UI workflow, the process becomes straightforward: user inputs are collected, passed to backend services, and then executed through automated deployment mechanisms. Behind the scenes, deployment services create execution environments and run infrastructure code to provision the required resources.</p><p>This approach offers several advantages:</p><ul><li>Faster and automated deployments</li><li>Consistent and repeatable infrastructure setup</li><li>Built-in best practices and governance</li><li>Reusable deployment templates</li><li>Simplified user experience for complex operations</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34b9976ec6c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Rapido, Uber, and Ola Power Real-Time Ride Assignments: A Developer’s Deep Dive]]></title>
            <link>https://medium.com/@mohd.gufran/how-rapido-uber-and-ola-power-real-time-ride-assignments-a-developers-deep-dive-fc89f164dba4?source=rss-ab25a514734e------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc89f164dba4</guid>
            <dc:creator><![CDATA[Mohd Gufran]]></dc:creator>
            <pubDate>Thu, 06 Nov 2025 13:28:05 GMT</pubDate>
            <atom:updated>2025-11-06T13:28:05.030Z</atom:updated>
            <content:encoded><![CDATA[<p>Ever wondered how apps like Rapido, Uber, or Ola manage to find a driver near you in just a few seconds? You tap “Book Ride” and suddenly a driver is on the way. Behind that simple button is a surprisingly complex system: smart map databases that know where every driver is, real-time communication that pushes ride requests instantly, and safety mechanisms to make sure only one driver gets confirmed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*J9TC-nDjJPbVU960.png" /></figure><h3>The Real-Time Ride Assignment Workflow</h3><p>Let’s break down the end-to-end flow in five core steps, focusing on how location data, geospatial search, and atomic operations come together to ensure the right driver gets the ride.</p><h3>1. User Requests a Ride</h3><p>When a rider enters their pickup and drop locations and hits “Book Ride,” the client app POSTs a new ride request to the backend API:</p><pre>POST /ride/request<br>{<br>  &quot;userId&quot;: &quot;U123&quot;,<br>  &quot;pickup&quot;: { &quot;lat&quot;: 12.9716, &quot;lng&quot;: 77.5946 },<br>  &quot;drop&quot;:   { &quot;lat&quot;: 12.9260, &quot;lng&quot;: 77.6762 }<br>}</pre><p>This request is saved to the database (for example, MongoDB) with a status of pending.</p><h3>2. Backend Finds Nearby Drivers (Geo-Indexed DB)</h3><p>How does the system instantly find drivers in the vicinity?</p><ul><li><strong>Driver Apps Push Location Regularly:</strong> The driver app uploads current GPS coordinates every few seconds to the backend:</li></ul><pre>{<br>  &quot;driverId&quot;: &quot;DRIVER_01&quot;,<br>  &quot;lat&quot;: 12.9721,<br>  &quot;lng&quot;: 77.5976<br>}</pre><ul><li><strong>Geo-Indexing:</strong> In MongoDB, each driver’s location is stored in GeoJSON format. A special geospatial index is created:</li></ul><pre>db.drivers.createIndex({ location: &quot;2dsphere&quot; });</pre><ul><li>This enables fast radius and proximity search, essential for real time pickup matching, as it stores real world coordinates.</li><li><strong>Proximity Query Example:</strong></li></ul><pre>db.drivers.find({<br>  status: &quot;available&quot;,<br>  location: {<br>    $near: {<br>      $geometry: { type: &quot;Point&quot;, coordinates: [77.5946, 12.9716] },<br>      $maxDistance: 2000 // meters (2 km radius)<br>    }<br>  }<br>})</pre><ul><li>Only drivers within 2 km are returned, sorted by distance.</li></ul><h3>How The Geo-Index Works Internally</h3><p>Think of the Earth (or a city map) being <strong>divided into a grid, </strong>just like how Google Maps loads tiles when you zoom in.</p><p>Each grid cell stores drivers currently inside that region.</p><pre>+---------+---------+---------+<br>|   A1    |   A2    |   A3    |<br>| (3 drv) | (0 drv) | (5 drv) |<br>+---------+---------+---------+<br>|   B1    |   B2    |   B3    |<br>| (1 drv) | (7 drv) | (2 drv) |<br>+---------+---------+---------+<br>|   C1    |   C2    |   C3    |<br>| (0 drv) | (4 drv) | (1 drv) |<br>+---------+---------+---------+</pre><p>Each block contains the <strong>drivers currently located</strong> in that block.</p><p>If the driver moves from block A3 → A2:</p><ul><li>They are <strong>removed from A3</strong></li><li>They are <strong>added to A2</strong></li></ul><p>When the customer requests a ride:</p><ol><li>The backend checks which grid cell the customer falls inside (say <strong>B2</strong>).</li><li>It retrieves drivers from <strong>B2 and nearby cells (A2, B1, B3, C2)</strong>.</li><li>It returns them instantly, <strong>without scanning all drivers in the database</strong>.</li></ol><h3>3. Backend Sends Ride Requests to Nearby Drivers</h3><p>Now the orchestration begins:</p><ul><li><strong>Active Drivers (App Open):</strong><br> Via WebSocket or MQTT(Message Queuing Telemetry Transport), the backend emits a &quot;rideRequest&quot; event with ride details directly to each target driver’s socket connection.</li></ul><pre>io.to(driver.socketId).emit(&quot;rideRequest&quot;, { rideId: &quot;...&quot;, ...});</pre><ul><li><strong>Inactive Drivers (App Minimized/Locked):</strong><br> Fallback to push notifications using Firebase Cloud Messaging (FCM).</li></ul><pre>sendPushNotification(driver.fcmToken, {<br>  title: &quot;New Ride Request!&quot;,<br>  data: { rideId: &quot;...&quot;}<br>});</pre><h3>4. Driver Accepts the Ride</h3><p>Multiple drivers could accept almost simultaneously. When a driver taps “Accept,” the app sends a reply:</p><pre>socket.emit(&quot;acceptRide&quot;, { rideId: &quot;RIDE001&quot;, driverId: &quot;DRIVER_01&quot; })</pre><p>The backend tries to assign the ride:</p><pre>db.rides.updateOne(<br>  { _id: &quot;RIDE001&quot;, status: &quot;pending&quot; }, // ensure ride is still open<br>  { $set: { status: &quot;assigned&quot;, driverId: &quot;DRIVER_01&quot; }}<br>)</pre><h3>5. Resolving Race Conditions: Who Really Gets the Ride?</h3><p>If five drivers all try to accept, only one can win. <strong>Atomic DB update operations</strong> ensure fairness:</p><ul><li>The first driver whose request reaches the database and matches the pending status is assigned the ride.</li><li>Others get a “Ride Already Taken” rejection via WebSocket or push notification.</li></ul><h3>Example Code Logic:</h3><pre>if (modifiedCount === 1) {<br>  // This driver won the race!<br>  sendSuccess();<br>} else {<br>  // Ride already assigned to someone else<br>  sendReject();<br>}</pre><h3>Continuous Location Updates</h3><ul><li>Every few seconds, each driver updates their coordinates:</li></ul><pre>POST /driver/updateLocation<br>{<br>  &quot;driverId&quot;: &quot;DRIVER_01&quot;,<br>  &quot;location&quot;: { &quot;lat&quot;: 12.9721, &quot;lng&quot;: 77.5976 }<br>}</pre><ul><li>The backend updates the appropriate document and updates the driver’s grid position, so geo-searches always use fresh data.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc89f164dba4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Containerizing a Simple Node.js App with Podman]]></title>
            <link>https://medium.com/@mohd.gufran/containerizing-a-simple-node-js-app-with-podman-0b07e7388fb2?source=rss-ab25a514734e------2</link>
            <guid isPermaLink="false">https://medium.com/p/0b07e7388fb2</guid>
            <category><![CDATA[podman]]></category>
            <category><![CDATA[image]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Mohd Gufran]]></dc:creator>
            <pubDate>Sun, 31 Aug 2025 17:53:24 GMT</pubDate>
            <atom:updated>2025-08-31T17:53:24.812Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Containerization is an essential skill for modern developers. Containers enable packaging an application with its dependencies into a lightweight, portable unit that can run consistently across different environments. While Docker is popular, we will be using <strong>Podman </strong>which is<strong> </strong>a daemonless, rootless, and secure alternative.</p><p>In this guide, we will learn how to create a simple Node.js app, containerize it using Podman, and run it locally.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*65zpyYv-ngphmuaxKKYLAQ.png" /><figcaption>AI-generated image of a basic containerized app architecture</figcaption></figure><h3>Key Definitions</h3><p><strong>Container: </strong>A container is an image under execution. It is a running environment that has everything needed for an application such as code, runtime, libraries, and settings. Containers are isolated from each other so that one application does not affect another, but they all share the same operating system kernel. Containers are created from images and can be started, stopped, moved, or deleted.</p><p><strong>Image: </strong>An image is like a recipe. It is a read only template that describes what the container should look like and what it needs to run. An image contains the application code and all the dependencies packaged together. You cannot run an image directly because it is only a blueprint. When you run an image, it becomes a container.</p><h3>Containerization Tools Overview</h3><p>Several tools help create and manage containers:</p><p><strong>Docker</strong>: The most popular container engine, using a client-server architecture with a central daemon.</p><p><strong>Podman</strong>: A daemonless, rootless container engine compatible with Docker commands but designed for enhanced security and simpler architecture.</p><p><strong>Buildah</strong>: Focused on building OCI container images.</p><p><strong>Kubernetes</strong>: Orchestrates large-scale container deployments.</p><p>In this tutorial, we use Podman for containerization because of its simplicity.</p><h3>Step 1: Create a Simple Node.js Application</h3><ol><li>Create a project folder and initialize Node.js:</li></ol><pre># Create a new directory named simpleApp<br>mkdir simpleApp  <br><br># Move into the newly created directory<br>cd simpleApp  <br><br># Initialize a new Node.js project with default settings<br># This will create a package.json file<br>npm init -y</pre><p>2. Create index.js with a basic HTTP server:</p><pre>// Import the built-in &#39;http&#39; module in Node.js<br>const http = require(&#39;http&#39;);<br><br>// Create an HTTP server<br>http.createServer((req, res) =&gt; {<br>  // Set the HTTP response header with status 200 (OK) and content type as HTML<br>  res.writeHead(200, { &#39;Content-Type&#39;: &#39;text/html&#39; });<br><br>  // Send the response body &quot;Hello World!&quot; and end the response<br>  res.end(&#39;Hello World!&#39;);<br>  <br>// The server will listen for requests on port 3000<br>}).listen(3000);</pre><p>3. Your package.json is ready from initialization.</p><h3>Step 2: Write a Containerfile</h3><p>The Containerfile (Podman’s equivalent of Dockerfile) defines how your container image is built:</p><pre># Use the official Node.js version 14 image as the base<br>FROM node:14  <br><br># Set the working directory inside the container to /app<br>WORKDIR /app  <br><br># Copy package.json and package-lock.json into the container<br>COPY package*.json ./  <br><br># Install the project dependencies inside the container<br>RUN npm install  <br><br># Copy the rest of the application files into the container<br>COPY . .  <br><br># Expose port 3000 so the app can be accessed from outside the container<br>EXPOSE 3000  <br><br># Define the command to run the application<br>CMD [&quot;node&quot;, &quot;index.js&quot;]</pre><h3>Step 3: Install and Set Up Podman</h3><ul><li>Install Podman Desktop.</li><li>In Podman Desktop go to Settings &gt; Resources, click Setup next to Podman, and follow prompts to initialize the Podman machine (a Linux VM) because containers require Linux.</li><li>Alternatively, install via Homebrew:</li></ul><pre># Install Podman using Homebrew on macOS<br>brew install podman  <br><br># Initialize a new Podman virtual machine (needed on macOS since Podman runs inside a VM)<br>podman machine init  <br><br># Start the Podman virtual machine<br>podman machine start</pre><h3>Step 4: Build Your Podman Container Image</h3><p>In Terminal, from your app directory:</p><pre># Build a container image using the Dockerfile in the current directory (.)<br># -t helloworld assigns the name (tag) &quot;helloworld&quot; to the image<br>podman build -t helloworld .</pre><p>This builds an image named helloworld from your Containerfile.</p><h3>Step 5: Run Your Node.js App Container</h3><pre># Run a container from the image named &quot;helloworld&quot;<br># -p 3000:3000 maps port 3000 of your host machine to port 3000 inside the container<br># This allows you to access the Node.js app running in the container at http://localhost:3000<br>podman run -p 3000:3000 helloworld</pre><p>Access the app at http://localhost:3000 and see “Hello World!”.</p><h3>Managing Containers</h3><pre># List all running containers with their IDs, names, ports, and status<br>podman ps  <br><br># Stop a running container using its container ID (or name)<br>podman stop &lt;container_id&gt;  <br><br># Remove a stopped container using its container ID (or name)<br>podman rm &lt;container_id&gt;</pre><h3>Sharing a Podman Image Through an Image Registry</h3><p>A convenient way to share your containerized Node.js app is by pushing our image to a container image registry which is a centralized service to store and distribute container images.</p><h3>How to Share Image Using Docker Hub (Example)</h3><ol><li>Tag your image for the registry</li></ol><pre># Create a new tag (name) for your local image &quot;helloworld&quot;<br># docker.io/&lt;username&gt;/helloworld:latest is the full path to your image on Docker Hub<br># Replace &lt;username&gt; with your actual Docker Hub username (e.g., gufran001)<br>podman tag helloworld docker.io/&lt;username&gt;/helloworld:latest</pre><p>2. Log in to Docker Hub<br>Login with your credentials:</p><pre>podman login docker.io</pre><p>3. Push your image to Docker Hub</p><pre># Push the tagged image from your local machine to Docker Hub<br># docker.io/&lt;username&gt;/helloworld:latest is the full path where the image will be stored<br># Replace &lt;username&gt; with your Docker Hub username (for you, it is gufran001)<br>podman push docker.io/&lt;username&gt;/helloworld:latest</pre><p>4. Your friend pulls the image</p><pre># Download (pull) the image from Docker Hub to your local machine<br># docker.io/&lt;username&gt;/helloworld:latest is the full path of the image on Docker Hub<br># Replace &lt;username&gt; with your Docker Hub username (for you, it is gufran001)<br>podman pull docker.io/&lt;username&gt;/helloworld:latest</pre><p>5. Run the container</p><pre># Run a container from the image stored on Docker Hub<br># -p 3000:3000 maps port 3000 of your local machine to port 3000 inside the container<br># Replace &lt;username&gt; with your Docker Hub username (for you, it is gufran001)<br># After running this, open http://localhost:3000 in your browser to see &quot;Hello World!&quot;<br>podman run -p 3000:3000 docker.io/&lt;username&gt;/helloworld:latest</pre><p>Your friend can now easily run your Node.js app with the exact environment you created.</p><h3>Conclusion</h3><p>Podman enables easy, secure containerization without the overhead of a daemon. Using containers and images ensures consistent environments for your applications. Although Podman requires a VM on macOS to run Linux containers, it provides a smooth developer experience. This guide laid out the steps from Node.js app creation through containerization to running with Podman.</p><p>Happy containerizing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0b07e7388fb2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basics of RAG (Retrieval-Augmented Generation)]]></title>
            <link>https://medium.com/@mohd.gufran/basics-of-rag-retrieval-augmented-generation-93730ef4a449?source=rss-ab25a514734e------2</link>
            <guid isPermaLink="false">https://medium.com/p/93730ef4a449</guid>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Mohd Gufran]]></dc:creator>
            <pubDate>Sun, 24 Aug 2025 07:04:01 GMT</pubDate>
            <atom:updated>2025-08-24T07:04:01.204Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Ever wished you could ask a computer a tough question and instantly get a clear, accurate answer even if the information was published just yesterday? That’s the promise of <strong>Retrieval-Augmented Generation (RAG)</strong>, a breakthrough that’s transforming the way we interact with artificial intelligence.</p><p>Whether you’re starting to explore AI or already working on the next big project, this read will explain RAG in simple terms. It will give you an overview of what RAG is, how it works, and why it’s becoming a game changer for smart applications.</p><h3>What is RAG?</h3><p>Think of RAG as a blend of a really smart search engine and a creative writer. Here’s what happens when you ask it a question:</p><ul><li><strong>Retrieval</strong><br> First, it searches through massive amounts of data like documents, articles, databases to pull out the most relevant facts.</li><li><strong>Augmentation</strong><br> Those facts are then handed over to a language model (like GPT or Llama), which reads and interprets them.</li><li><strong>Generation</strong><br> Finally, the model uses that knowledge to craft a natural, detailed answer grounded in fresh facts, not just what it memorized during training.</li></ul><h3>Why is RAG Important?</h3><ul><li><strong>Cuts down on “hallucinations”</strong><br> Traditional LLMs sometimes make up facts. RAG reduces these errors by grounding answers in real, external knowledge sources, making results far more trustworthy.</li><li><strong>No expensive retraining needed</strong><br> Instead of retraining a language model every time new data comes in (which is costly and time-consuming), RAG can simply plug in the latest information on the fly.</li><li><strong>Smarter, more personalized answers</strong><br> By pulling the most relevant pieces of context for each query, RAG can tailor responses to the user’s exact needs.</li></ul><h3>Core Components</h3><h3>1. Retriever</h3><p><strong>Role:</strong> Finds the most relevant pieces of information from a large knowledge base in response to a query.</p><p><strong>How it works:</strong></p><ul><li>A query (user question) is first embedded into a vector representation using an <strong>embedding model</strong>.</li><li>The retriever compares this query vector against all document vectors in a <strong>vector database</strong>.</li><li>It returns the <strong>top-k most relevant chunks/documents</strong> for the query.</li><li><strong>Example:</strong> If you ask, <em>“What is photosynthesis?”</em>, the retriever finds the passages about photosynthesis from a biology textbook or knowledge base.</li></ul><h3>2. Embedding Model</h3><p><strong>Role:</strong> Converts text into <strong>high-dimensional vectors</strong> (mathematical representations).</p><p><strong>Why important:</strong> Computers can’t compare meanings directly, but vectors allow measuring <strong>semantic similarity</strong> between queries and documents.</p><p><strong>Characteristics:</strong></p><ul><li>Embeddings capture <strong>contextual meaning</strong>, not just exact words.</li><li>Two semantically similar texts (e.g., <em>“car”</em> and <em>“automobile”</em>) will have vectors that are <strong>close</strong> in this high-dimensional space.</li><li><strong>Example:</strong> “AI” and “Artificial Intelligence” → embeddings place them near each other in vector space.</li></ul><h3>3. Vector Database</h3><p><strong>Role:</strong> Stores all embeddings (vectors) and performs <strong>efficient similarity searches</strong>.</p><p><strong>Why needed:</strong> With millions or billions of documents, searching raw text would be too slow. Vector DBs use <strong>Approximate Nearest Neighbor (ANN)</strong> algorithms for near-instant results.</p><p><strong>Example in action:</strong> A query vector for “climate change effects” is compared against stored vectors; the DB instantly returns the closest document embeddings about rising sea levels, global warming, etc.</p><h3>4. LLM (Large Language Model)</h3><p><strong>Role:</strong> Synthesizes a <strong>final answer</strong> by combining retrieved information with its own reasoning abilities.</p><p><strong>How it works in RAG pipeline:</strong></p><ul><li>Takes the user’s query + retrieved text chunks.</li><li>Reads and interprets retrieved facts.</li><li>Generates a fluent, context-aware, and <strong>grounded response</strong>.</li></ul><p><strong>Why critical:</strong></p><ul><li>Embeddings and retrievers are great at <em>finding</em> information, but LLMs can <em>explain, summarize, and contextualize</em> it.</li><li>Prevents hallucination by staying grounded in retrieved knowledge.</li><li><strong>Example:</strong> If retrieved facts explain the process of photosynthesis, the LLM will stitch them together into a clear answer like:</li><li>“Photosynthesis is the process by which plants convert sunlight, water, and carbon dioxide into glucose and oxygen. It mainly occurs in the chloroplasts of plant cells.”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UP-Gb2TuuJ7q2yxk.png" /><figcaption>The image shows a user query processed by a retriever accessing a vector database, with an LLM generating a detailed, accurate answer.</figcaption></figure><h3>Conclusion</h3><p>RAG is changing the game by transforming ordinary apps into extraordinary knowledge tools.</p><ul><li><strong>For beginners:</strong> It’s the easiest way to build powerful, context-aware AI without needing massive compute budgets or complex retraining.</li><li><strong>For experts:</strong> It offers a modular, scalable foundation for advanced NLP by cutting down hallucinations and giving more control over how AI reasons.</li></ul><p>At its core, RAG isn’t just about getting answers. It’s about connecting people to the right knowledge at the right time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93730ef4a449" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Expiration Rules in IBM COS Turn Idle Data into Savings]]></title>
            <link>https://medium.com/@mohd.gufran/how-expiration-rules-in-ibm-cos-turn-idle-data-into-savings-58c14236a981?source=rss-ab25a514734e------2</link>
            <guid isPermaLink="false">https://medium.com/p/58c14236a981</guid>
            <category><![CDATA[cloud-object-sto]]></category>
            <category><![CDATA[expiration-rules]]></category>
            <category><![CDATA[lifecycle-policy]]></category>
            <category><![CDATA[cos-configuration]]></category>
            <dc:creator><![CDATA[Mohd Gufran]]></dc:creator>
            <pubDate>Fri, 08 Aug 2025 09:52:22 GMT</pubDate>
            <atom:updated>2025-08-08T09:52:22.131Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Atul:</strong> “My IBM Cloud Object Storage bill went up again. I’ve got so many old files sitting there that I don’t even use anymore.”</p><p><strong>Jaya:</strong> “Have you thought about using expiration rules? They help automatically delete files you don’t need anymore, so you only pay for what’s actually important.”</p><p><strong>Atul:</strong> “Expiration rules? How do those work?”</p><p><strong>Jaya:</strong> “Think of expiration rules like setting an automatic trash schedule for your storage bucket. You tell IBM COS, ‘After 30 days, delete these files.’ So your storage stays clean and your bill stays smaller.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8r8n1A2ZbYtaMcdS.png" /></figure><h3>What Are Expiration Rules?</h3><p>Expiration rules, also called lifecycle policies, let you automatically remove objects from your IBM COS bucket after a specified duration from their creation date. This is great for keeping old backups, logs, or temporary files from piling up and costing you extra.</p><p>You can create up to 1,000 such rules per bucket, each targeting specific files using prefixes (like folders) or applying to the whole bucket.</p><h3>How Expiration Rules work in IBM COS</h3><h4>1. Without Versioning</h4><p>If your bucket does not have versioning enabled, expiration rules simply delete the objects once they hit the expiration date.</p><ul><li>Objects meeting the criteria are permanently removed.</li><li>Billing for storage of those objects immediately stops.</li></ul><h4>2. With Versioning Enabled</h4><p>When versioning is enabled, each modification or deletion creates a new object version or a delete marker.</p><p>Expiration rules handle this by:</p><ul><li>Deleting both current and noncurrent versions after your specified time.</li><li>Cleaning up delete markers to prevent accumulation of so-called “ghost files” that don’t hold data but still count as objects.</li><li>This helps avoid unexpected charges from keeping old versions indefinitely.</li></ul><h4>3. Handling Multipart Uploads</h4><p>Sometimes uploads are done in parts (multipart uploads). If these uploads are incomplete, they linger and take space.</p><p>Expiration rules can include a cleanup policy to automatically abort incomplete multipart uploads after a set duration, freeing up your storage.</p><h4>4. Delete Markers</h4><p>In versioned buckets, deleting an object inserts a delete marker — a special placeholder marking that the object is “deleted” without removing previous versions.</p><p>Expiration rules help by removing these delete markers when they are no longer needed, further reducing storage costs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jy8Ow0Gz_C47b1eDHeH2XQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*753N5CIBnaL6tnbYwoocPQ.png" /></figure><h3>Comparing Expiration Rules Across Major Cloud Object Storage Services: Similarities and Differences</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_8zJ9vwpfNTo9ga_-wO8Tw.png" /></figure><h3>Summary</h3><p>Expiration rules in IBM Cloud Object Storage are like a smart cleaning schedule for your storage buckets. By setting these rules, you reduce your storage bill by automatically deleting stale data, managing object versions effectively, and cleaning up abandoned uploads.</p><p>If you haven’t already, consider enabling expiration rules in your IBM COS buckets to keep your cloud storage lean and your costs under control.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58c14236a981" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Say Goodbye to Bugs: A Beginner’s Guide to Unit Testing in React]]></title>
            <link>https://medium.com/@mohd.gufran/say-goodbye-to-bugs-a-beginners-guide-to-unit-testing-in-react-2767d039aa55?source=rss-ab25a514734e------2</link>
            <guid isPermaLink="false">https://medium.com/p/2767d039aa55</guid>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[unit-testing-tools]]></category>
            <category><![CDATA[unit-testing-types]]></category>
            <category><![CDATA[unit-testing-framework]]></category>
            <category><![CDATA[unit-test-coverage]]></category>
            <dc:creator><![CDATA[Mohd Gufran]]></dc:creator>
            <pubDate>Sun, 20 Apr 2025 13:32:13 GMT</pubDate>
            <atom:updated>2025-04-20T13:32:13.412Z</atom:updated>
            <content:encoded><![CDATA[<p>Unit testing is a critical practice in software development, ensuring that individual components or functions in your code work as expected. A <strong>unit test</strong> focuses on verifying the functionality of the smallest possible unit of code in isolation, whether that’s a function, a method, or a React component. This allows developers to catch bugs early, making the code more stable and easier to maintain over time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0cb9AB-91htX7EHK.png" /></figure><h4><strong>Unit Tests in React and Why?</strong></h4><p>Unit testing is an essential practice in React applications, where we developers test small, isolated pieces of code typically functions or components. These tests ensure that each unit behaves as expected in isolation. Since React follows a component-based architecture, unit tests focus on testing individual components, which often represent distinct features of the app.</p><p>In React, unit tests generally focus on ensuring that components render correctly, handle inputs, and trigger events as expected. For example, a Button component might be tested to ensure it displays the correct label and that clicking it triggers the intended action. This isolation allows for focused testing, where developers can make sure each part of their app functions properly without worrying about other components.</p><h4>Popular Tools for Unit Testing in React: A Comparison</h4><p>There are several tools available for unit testing in React, each with its strengths and best-use cases.</p><ul><li><strong>Jest and @testing-library/react</strong> are the most widely used and recommended tools for React testing. Jest is a powerful testing framework that handles test running, assertions, and mocking. When combined with <strong>React Testing Library (RTL)</strong>, it provides a modern approach to testing React components, focusing on user interactions and component behavior rather than implementation details. RTL encourages testing in isolation, making it easy to verify that components function as intended. This setup is ideal for both beginners and experienced developers due to its simplicity and community support.</li><li><strong>React’s built-in testing tools</strong> like <strong>ReactTestUtils</strong> and <strong>ReactTestRenderer</strong> can be used for more direct interaction with components, but they are less commonly used today. These tools are suitable for low-level testing but are considered somewhat outdated compared to Jest and RTL.</li><li><strong>Enzyme</strong> was once a go-to for React testing, particularly for earlier versions of React (16 and below). However, Enzyme no longer officially supports React 17 and is not recommended for React 18, as it has not kept pace with React’s evolving features.</li></ul><p>In summary, <strong>Jest and React Testing Library</strong> are the most modern, widely used, and easiest tools for React unit testing. They are highly recommended for new projects, while tools like Enzyme are best avoided unless you’re working with older React versions.</p><h4><strong>How to approach writing a Unit Test in React</strong></h4><p><strong>Understand the component<br></strong>Let us understand this with the help of below example.<br>The below “Popup” component is designed to display a button initially, without showing any message. When the user clicks the button, a popup message appears on the screen. Until that interaction happens, the popup remains hidden, ensuring it only becomes visible after the button is clicked.</p><pre>import React, { useState } from &#39;react&#39;;<br><br>function Popup() {<br>  const [visible, setVisible] = useState(false);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;button onClick={() =&gt; setVisible(true)}&gt;Show Message&lt;/button&gt;<br>      {visible &amp;&amp; &lt;div role=&quot;alert&quot;&gt;Hello, this is your popup!&lt;/div&gt;}<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default Popup;</pre><p><strong>Now write the Unit Test for this component</strong></p><ul><li><strong>Import the required libraries<br></strong>First, import the testing utilities you’ll need to render components and simulate user interaction:</li></ul><pre>import { render, screen, fireEvent } from &#39;@testing-library/react&#39;;<br>import Popup from &#39;./Popup&#39;; // Adjust the path to your component</pre><ul><li><strong>Use ‘describe’ to Group Related Tests<br></strong>Group related tests using the ‘describe’ block. This helps organize your tests and makes output easier to read.</li></ul><pre>describe(&#39;Popup component&#39;, () =&gt; {<br>  // tests will go here<br>});</pre><ul><li><strong>Write Your Test Cases with ‘test’</strong></li></ul><pre>test(&#39;should not show popup message initially&#39;, () =&gt; {<br>  render(&lt;Popup /&gt;);<br>  expect(screen.queryByRole(&#39;alert&#39;)).toBeNull(); // Popup should be hidden by default<br>});<br><br>test(&#39;should show popup message when button is clicked&#39;, () =&gt; {<br>  render(&lt;Popup /&gt;);<br>  fireEvent.click(screen.getByText(&#39;Show Message&#39;)); // Simulate user action<br>  const alert = screen.getByRole(&#39;alert&#39;);<br>  expect(alert).toBeInTheDocument(); // Popup should appear<br>  expect(alert).toHaveTextContent(&#39;Hello, this is your popup!&#39;); // Message should be correct<br>});</pre><p>To write unit tests for a React component like Popup, start by importing the necessary functions from React Testing Library. Then, use a describe block to group related tests for better structure. Inside it, write individual test cases to check specific behaviors. First, ensure the popup is hidden by default. Then, simulate a button click to verify that the popup appears and displays the correct message. Use assertions like expect to validate what should or shouldn&#39;t be in the DOM. This structured approach helps ensure your component behaves as expected and makes your tests easy to read and maintain.</p><h4><strong>Best Practices for Writing Unit Test in React</strong></h4><p>Writing good tests isn’t just about coverage numbers — it’s about confidence in your code. Here are some key practices to keep in mind while testing React components:</p><ul><li><strong>Write Tests to Test the Code — Not Just to Increase Coverage<br></strong>Don’t write shallow tests just to check a box. Your goal should be to catch bugs, validate logic, and ensure user interactions work as expected. High coverage is nice, but meaningful coverage is better.</li><li><strong>Try to Cover All Logical Branches Early<br></strong>Make an effort to test all the different branches of your logic (like conditionals, edge cases, etc.) from the start. If you skip this, it becomes harder to retrofit tests later when your app is more complex.</li><li><strong>Test with Different Parameters and States<br></strong>Don’t just test the happy path. Try rendering your components with different props, invalid inputs, and edge cases. You’ll catch more issues and write more resilient code.</li><li><strong>Simulate Real User Behavior<br></strong>Use tools like ‘fireEvent’ or ‘userEvent’ to simulate actual user actions (clicks, typing, etc.). This ensures your components behave correctly under real-world usage.</li><li><strong>Keep Your Tests Clean and Readable<br></strong>A test is also documentation. Name your test cases clearly, and avoid deeply nested logic inside your test blocks. Anyone reading your code should understand what the component is expected to do at a glance.</li></ul><pre>// Good<br>test(&#39;displays error when email is invalid&#39;, () =&gt; {<br>  // ...<br>});<br><br>// Bad<br>test(&#39;does the thing right&#39;, () =&gt; {<br>  // ...<br>});</pre><ul><li><strong>Test What Matters, Not Implementation Details<br></strong>Avoid testing internal logic or private methods directly. Focus on the component’s behavior and what the user sees. If you rewrite the internals but the behavior doesn’t change, your tests shouldn’t break.</li><li><strong>Keep Tests Independent<br></strong>Each test should stand on its own. Don’t rely on the outcome of a previous test, this can lead to flaky tests and makes debugging much harder.</li></ul><p>Unit testing might feel overwhelming at first, especially if you’re just getting started with React or testing in general but it’s one of the most powerful habits you can build as a developer. By testing components in isolation, you’re not only preventing bugs but also boosting your confidence every time you make changes to your codebase.</p><p>Remember, writing effective unit tests isn’t about chasing 100% code coverage — it’s about writing tests that truly reflect how users interact with your app. Focus on real use cases, cover different states and edge cases, and always aim for clarity over complexity.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2767d039aa55" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>