<?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 Ankitkr on Medium]]></title>
        <description><![CDATA[Stories by Ankitkr on Medium]]></description>
        <link>https://medium.com/@codingank?source=rss-c31843ca9ced------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ym9EtjEZcKrCZ84IYejf7w.jpeg</url>
            <title>Stories by Ankitkr on Medium</title>
            <link>https://medium.com/@codingank?source=rss-c31843ca9ced------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 20:24:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@codingank/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[How Netflix Built Graph Agents That Connect Logs, Deployments, and Incidents]]></title>
            <link>https://medium.com/@codingank/how-netflix-built-graph-agents-that-connect-logs-deployments-and-incidents-74e678278449?source=rss-c31843ca9ced------2</link>
            <guid isPermaLink="false">https://medium.com/p/74e678278449</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[netflix]]></category>
            <dc:creator><![CDATA[Ankitkr]]></dc:creator>
            <pubDate>Wed, 18 Nov 2026 05:20:46 GMT</pubDate>
            <atom:updated>2026-11-18T05:20:46.843Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0H94RFh-xkIzO6ovNLRRxQ.png" /></figure><p>Imagine you are an engineer at Netflix.</p><p>One morning, an alert pops up.</p><p>The Netflix homepage is taking longer than usual to load. Users are facing delays, and your team needs to find out what went wrong — fast.</p><p>You start checking different tools.</p><p>You look at application logs and see a few errors. You check performance dashboards and notice that response times have gone up. You review recent deployments and find that a new version was released shortly before the problem began. You also check the incident system and search Slack to see whether anyone else has noticed something similar.</p><p>All the information is there.</p><p>But there is one big problem.</p><p>No system automatically tells you how these pieces fit together.</p><p>You have to jump from logs to metrics, then to deployment records, then to Slack messages, and finally try to figure out the full story in your head.</p><p>Was the new deployment the cause? Did another service fail? Was there a configuration change? Is this connected to an incident from last month?</p><p>Netflix has said that an investigation like this can take around four hours, with much of that time spent rebuilding relationships between information that already exists but is spread across different systems.<a href="https://allegrograph.com/netflixs-ontology-driven-ai-architecture-validates-the-need-for-context-graph/">allegrograph</a></p><p>So, Netflix was not necessarily missing data.</p><p>It was missing <strong>connected context</strong>.</p><p>Let’s break down how Netflix approached this problem and why it matters for AI agents.</p><h3>1. Having data is not the same as understanding it</h3><p>During a production issue, information usually comes from many different places.</p><p>Logs tell you what errors happened.</p><p>Metrics show how the system performed.</p><p>Traces show the path a request took across services.</p><p>Deployment tools tell you what changed.</p><p>Incident tools record reported problems.</p><p>Slack contains conversations between engineers.</p><p>Each system knows one part of the story.</p><p>But solving a real production issue often requires seeing all of them together.</p><p>For example:</p><ul><li>10:00 AM — A new deployment is released.</li><li>10:05 AM — Connection errors start increasing.</li><li>10:07 AM — Homepage latency increases.</li><li>10:10 AM — A production alert is triggered.</li><li>10:12 AM — An incident is created.</li></ul><p>These events may be connected.</p><p>But five separate records do not automatically explain the connection.</p><p>An engineer has to investigate each system and manually connect the dots.</p><p>This becomes much harder when a company has thousands of applications, services, teams, and dependencies.</p><p>Netflix wanted to make this process easier.</p><p>Its solution was to create a shared picture of its operational environment — one place where important relationships could be understood.</p><h3>2. Netflix’s approach: Build a shared Knowledge Graph</h3><p>Instead of leaving operational information scattered across tools, Netflix connects things like applications, deployments, incidents, teams, alerts, and services.</p><p>Think of it as building a map of what is happening inside the infrastructure.</p><p>For example:</p><pre>Deployment v2.4.1<br>        |<br>        | deployed to<br>        v<br>API Gateway<br>        |<br>        | experienced<br>        v<br>Connection Timeout<br>        |<br>        | associated with<br>        v<br>Production Incident</pre><p>Now the system is not just storing separate records.</p><p>It is storing relationships.</p><p>When an engineer investigates an incident, the system can help surface related deployments, errors, applications, teams, and past incidents.</p><p>But how does the system know what these things mean and how they relate?</p><p>That is where an important idea comes in: an <strong>ontology</strong>.</p><h3>3. What is an ontology?</h3><p>“Ontology” sounds complicated, but the idea is simple.</p><p>An ontology is a shared way of defining things and the relationships between them.</p><p>Imagine building an e-commerce app.</p><p>You may have:</p><ul><li>Users</li><li>Products</li><li>Orders</li><li>Payments</li><li>Deliveries</li></ul><p>Then you define relationships:</p><pre>User → PLACED → Order<br>Order → CONTAINS → Product<br>Order → HAS_PAYMENT → Payment<br>Order → HAS_DELIVERY → Delivery</pre><p>Now every part of the system understands what an order is, what a product is, and how they connect.</p><p>Netflix uses the same idea for its internal systems.</p><p>It defines concepts such as applications, incidents, deployments, teams, and alerts, along with the relationships between them.</p><p>This gives different systems a common language.</p><p>For example, one system may identify an application by its name, while another uses an internal ID. The knowledge graph can connect both references to the same application.</p><p>Netflix uses semantic web technologies to do this:</p><ul><li><strong>RDF</strong> represents information as connected facts.</li><li><strong>OWL</strong> helps define concepts and relationships.</li><li><strong>SHACL</strong> checks whether data follows the expected rules.</li><li><strong>SPARQL</strong> queries information stored in the graph.</li></ul><p>RDF is based on simple subject-predicate-object statements, such as “this application has this deployment.” These statements form a graph of connected facts</p><p>You do not need to memorize every technology.</p><p>Just remember this:</p><p><strong>The ontology defines what things mean. The Knowledge Graph connects those things.</strong></p><h3>4. Turning scattered information into connected knowledge</h3><p>This is one of the most interesting parts of Netflix’s approach.</p><p>Netflix receives information from many sources.</p><p>But raw information is not automatically useful for a knowledge graph.</p><p>It first needs to be processed and structured.</p><p>Netflix uses components called <strong>Enrichers</strong>.</p><p>Think of an Enricher as a worker that takes information from a source, understands it, and turns it into structured knowledge.</p><p>For example, suppose Netflix receives this deployment record:</p><pre>Application: api-gateway<br>Version: v2.4.1<br>Environment: production<br>Time: 10:00 AM</pre><p>An Enricher can turn it into a relationship like this:</p><pre>api-gateway<br>    |<br>    | HAS_DEPLOYMENT<br>    v<br>v2.4.1</pre><p>Now imagine a Slack message:</p><blockquote><em>“The latest gateway release may have caused the connection timeout.”</em></blockquote><p>This is harder because it is written in natural language.</p><p>An AI model can help read the message and identify possible entities and relationships.</p><p>But there is a challenge.</p><p>Large language models can make mistakes.</p><p>What if the model identifies an application that does not exist? What if it creates a relationship that makes no sense?</p><p>Netflix does not blindly trust everything an LLM produces.</p><p>The extracted information has to pass validation rules.</p><p>For example:</p><ul><li>Every entity must have a valid type.</li><li>Application names must match known applications.</li><li>Identifiers must follow consistent naming rules.</li><li>Relationships must use the defined vocabulary.</li></ul><p>This matters because an AI-generated mistake should not automatically become trusted company knowledge.</p><p>The model can suggest information.</p><p>Validation decides whether it can be accepted.</p><p>Netflix’s approach combines deterministic processing with AI-assisted extraction, rather than relying on an LLM for everything.</p><h3>5. How Netflix finds possible causes</h3><p>Once Netflix has structured and connected information, the next question is:</p><p><strong>Which events might be related to an incident?</strong></p><p>This is where its <strong>Correlation Engine</strong> comes in.</p><p>Imagine this sequence again:</p><ul><li>10:00 AM — Deployment released</li><li>10:05 AM — Connection errors increase</li><li>10:07 AM — Homepage latency increases</li><li>10:10 AM — Production alert triggered</li><li>10:12 AM — Incident created</li></ul><p>The Correlation Engine looks at different signals, including:</p><ul><li>Logs and error patterns</li><li>Performance metrics</li><li>Slow or failed traces</li><li>Alerts and incidents</li><li>Deployments and configuration changes</li><li>Experiments and infrastructure events</li></ul><p>It looks for possible relationships based on timing, severity, and known dependencies between services.</p><p>For example, it may identify that a recent deployment could be connected to the incident.</p><p>It might produce something like:</p><pre>Possible cause:<br>Deployment: v2.4.1<br><br>Evidence:<br>- The deployment happened before the incident.<br>- Connection errors increased afterward.<br>- The affected application matches.<br><br>Confidence: 0.87</pre><p>But there is an important point here.</p><p><strong>Correlation does not automatically prove causation.</strong></p><p>The system can identify a possible explanation based on available evidence.</p><p>An engineer still needs to investigate, verify, and decide what action to take.</p><p>That is a healthy principle for building AI systems in production environments.</p><h3>6. Learning from previous incidents</h3><p>Now imagine the same application has a similar incident next month.</p><p>This time, the system already has historical information.</p><p>It can find:</p><ul><li>What happened during the previous incident</li><li>Which deployment was involved</li><li>Which errors appeared</li><li>What engineers investigated</li><li>Which action resolved the issue</li><li>What happened after that action</li></ul><p>So it does not have to start from zero.</p><p>Netflix describes this idea through a <strong>Knowledge Flywheel</strong>.</p><p>It has four stages:</p><ol><li><strong>Observe</strong> — Collect information from logs, metrics, traces, incidents, and other systems.</li><li><strong>Enrich</strong> — Convert raw information into structured knowledge and relationships.</li><li><strong>Infer</strong> — Identify patterns, correlations, and possible explanations.</li><li><strong>Adapt</strong> — Use what was learned to improve future investigations.</li></ol><p>Over time, the system builds a useful history of how the infrastructure behaves.</p><p>This is more than saving old incidents.</p><p>It is preserving what the organization learned from them.</p><h3>7. Where AI agents fit in</h3><p>Now let’s bring <strong>Agentic AI</strong> into the picture.</p><p>Netflix describes an automated root-cause-analysis system called <strong>AutoRCA</strong>.</p><p>Imagine having multiple specialized agents:</p><ul><li><strong>Metrics Agent</strong> — Investigates performance issues.</li><li><strong>Logs Agent</strong> — Investigates application errors.</li><li><strong>Traces Agent</strong> — Investigates slow or failed requests.</li><li><strong>Deployment Agent</strong> — Investigates recent releases.</li><li><strong>Incident Agent</strong> — Checks previous incidents.</li></ul><p>Each agent focuses on a different area.</p><p>But here is the interesting part.</p><p>They can work with the same knowledge graph.</p><p>For example:</p><ul><li>The Logs Agent finds connection-timeout errors.</li><li>The Deployment Agent finds that a new version was released shortly before the errors began.</li><li>The Metrics Agent confirms that latency increased around the same time.</li></ul><p>These findings can be connected through shared entities in the graph.</p><p>The system can then suggest a possible root cause along with supporting evidence.</p><p>An engineer reviews the findings and decides what to do next.</p><p>Why is this useful?</p><p>Because the agents do not have to work with completely isolated information.</p><p>They can build on what other agents discover.</p><p>The Knowledge Graph acts as a shared understanding between different agents.</p><h3>8. Where does “Context Graph” come in?</h3><p>Now we can understand why AllegroGraph connects Netflix’s work with the idea of <strong>Context Graphs</strong>.</p><p>Let’s use a simple example.</p><p>A traditional system might store an incident like this:</p><pre>Incident: INC-5377<br>Status: Resolved</pre><p>But that is not the full story.</p><p>A richer representation could preserve:</p><pre>Incident: INC-5377<br><br>What happened:<br>Connection timeout.<br><br>Possible reason:<br>Recent deployment.<br><br>Evidence:<br>Logs and metric anomalies.<br><br>Decision:<br>Roll back the deployment.<br><br>Action:<br>Version v2.4.1 rolled back.<br><br>Outcome:<br>Service recovered.</pre><p>Now, future agents can understand more than just the incident itself.</p><p>They can understand the surrounding events, decisions, evidence, actions, and results.</p><p>That is the broader idea behind a Context Graph.</p><p>A <strong>Knowledge Graph</strong> connects entities and their relationships.</p><p>A <strong>Context Graph</strong> focuses on the context around what happened: why a decision was made, what evidence supported it, what action was taken, and what happened afterward.</p><p>These ideas overlap.</p><p>A knowledge graph can also store history, decisions, and evidence.</p><p>It is not necessarily a completely different database technology.</p><p>One important distinction: Netflix describes its implementation as an <strong>ontology-driven observability knowledge graph</strong>, while AllegroGraph uses Netflix’s work to support its broader <strong>Context Graph</strong> vision.<a href="https://allegrograph.com/netflixs-ontology-driven-ai-architecture-validates-the-need-for-context-graph/">allegrograph</a></p><h3>9. What this means for AI agents</h3><p>For a long time, many teams have focused on giving language models more information.</p><p>They build RAG pipelines, connect vector databases, add tools, and use multiple agents.</p><p>But there is another important question:</p><p><strong>Does the AI actually understand how the information it retrieves is connected?</strong></p><p>Imagine asking an AI agent:</p><blockquote><em>“Why did this payment fail?”</em></blockquote><p>A basic RAG system might find a document about payment failures and generate an answer.</p><p>But a more context-aware system could connect:</p><ul><li>The payment</li><li>The customer</li><li>The service processing the payment</li><li>The recent deployment</li><li>The error logs</li><li>Previous incidents</li><li>The decision made during the last investigation</li><li>The result of that decision</li></ul><p>That gives the AI a much richer foundation for investigation.</p><p>The same idea can apply to many areas:</p><ul><li>Customer-support agents that understand past customer interactions and resolutions.</li><li>Financial agents that connect transactions, decisions, and historical activity.</li></ul><p>The goal is not simply to retrieve more information.</p><p>The goal is to give AI agents the right information, along with its relationships and history.</p><h3>Final thoughts</h3><p>Netflix’s architecture highlights an important shift in how we should think about building AI systems.</p><p>For years, much of the focus has been on improving models, writing better prompts, adding tools, and building RAG pipelines.</p><p>But production AI also needs reliable context.</p><p>It needs to understand:</p><ul><li>What things are</li><li>How they relate</li><li>What happened before</li><li>Why certain decisions were made</li></ul><p>An LLM provides intelligence.</p><p>Connected knowledge provides the context that makes that intelligence useful.</p><p>And that may be one of the biggest engineering challenges in building reliable AI agents.</p><p>thanks for reading <br>I have used this blog as References and further reading <a href="https://allegrograph.com/netflixs-ontology-driven-ai-architecture-validates-the-need-for-context-graph/">https://allegrograph.com/netflixs-ontology-driven-ai-architecture-validates-the-need-for-context-graph/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74e678278449" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When a Load Balancer Failed: Lessons from Atlassian’s 2019 Outage]]></title>
            <link>https://medium.com/@codingank/when-a-load-balancer-failed-lessons-from-atlassians-2019-outage-9e674d8d116a?source=rss-c31843ca9ced------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e674d8d116a</guid>
            <category><![CDATA[backend-architecture]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[design-systems]]></category>
            <dc:creator><![CDATA[Ankitkr]]></dc:creator>
            <pubDate>Thu, 20 Aug 2026 08:41:01 GMT</pubDate>
            <atom:updated>2026-08-20T08:41:01.227Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1bGMWws1st_k5tFXsGZ_VQ.png" /></figure><h4>What happens when your application servers look healthy, your dashboards look normal, but users suddenly can’t access your service?</h4><p>Atlassian faced exactly this kind of problem in 2019.</p><p>A critical service called <strong>Tenant Context Service (TCS)</strong> went down for about five minutes in two U.S. regions. Since TCS was used by Atlassian’s cloud products to retrieve tenant information, the outage affected those products in the affected regions.</p><p>What makes this incident interesting is that the problem wasn’t initially obvious from Atlassian’s own monitoring.</p><p>The problem was at the <strong>load-balancer layer</strong>.</p><h3>First, understand the architecture</h3><p>TCS was a critical service used throughout Atlassian Cloud. It stored tenant metadata such as where a customer’s data was located and other information needed to process requests.</p><p>A simplified version looks like this:</p><pre>Users<br>  |<br>  v<br>Load Balancer<br>  |<br>  +--------+--------+<br>  |        |        |<br>  v        v        v<br>Server   Server   Server<br>  |        |        |<br>  +--------+--------+<br>           |<br>           v<br>       DynamoDB</pre><p>The load balancer is the entry point between incoming traffic and the application servers.</p><p>Its job is straightforward:</p><p><strong>Receive traffic → distribute it → send requests to the available servers.</strong></p><p>But in this incident, the load balancer itself became the problem.</p><h3>What actually happened?</h3><p>The outage happened immediately after a new stack was deployed.</p><p>Atlassian’s internal deployment process worked roughly like this:</p><pre>Deploy new stack<br>      ↓<br>Create new servers + new ELB<br>      ↓<br>New ELB starts scaling<br>      ↓<br>DNS is switched to new ELB<br>      ↓<br>Production traffic arrives<br>      ↓<br>New ELB hasn&#39;t scaled enough<br>      ↓<br>ELB runs out of memory<br>      ↓<br>ELB dies<br>      ↓<br>Requests fail</pre><p>The important detail is this:</p><p><strong>The old ELB was already scaled for the existing traffic.</strong></p><p>During deployment, Atlassian created a <strong>new ELB</strong> as part of the new stack. The deployment then switched DNS to that new ELB.</p><p>The problem was that the new ELB had not yet scaled enough to handle the traffic it immediately received.</p><p>Atlassian notes that ELB scaling could take <strong>1–7 minutes</strong>. The new ELB eventually ran out of memory and died.</p><p>So this wasn’t simply:</p><blockquote><em>“The application servers crashed.”</em></blockquote><p>The <strong>load balancer itself died</strong>, and the new infrastructure wasn’t ready to handle production traffic.</p><h3>Why was this so confusing?</h3><p>This is one of the best lessons from the incident.</p><p>When Atlassian looked at its service metrics, nothing obvious stood out.</p><p>Then they noticed something strange:</p><p><strong>The ELB was receiving zero requests.</strong></p><p>That sounds like:</p><blockquote><em>“Maybe there isn’t any traffic.”</em></blockquote><p>But there was traffic.</p><p>The problem was that there was no functioning ELB available to service those requests.</p><pre>Users<br>  |<br>  | requests<br>  v<br>   X<br>Load Balancer ❌<br>   |<br>   v<br>Application Servers</pre><p>So the application servers could look healthy while users were still unable to reach the service.</p><p>Atlassian contacted AWS support, which confirmed that the ELBs had died because of out-of-memory errors. Once a new ELB was scaled up, the service recovered.</p><p>This is a great distributed-systems lesson:</p><blockquote><strong><em>A healthy application server doesn’t mean the entire system is healthy.</em></strong></blockquote><h3>Why didn’t the load balancer just scale automatically?</h3><p>This is where things get interesting.</p><p>We often hear:</p><blockquote><em>“Just use auto-scaling.”</em></blockquote><p>But scaling isn’t instantaneous.</p><p>There is always some delay:</p><pre>Need more capacity<br>       ↓<br>Scaling starts<br>       ↓<br>Resources are created<br>       ↓<br>Resources initialize<br>       ↓<br>Capacity becomes available</pre><p>Atlassian specifically noted that ELB scaling could take <strong>1–7 minutes</strong>.</p><p>That means you can have a situation where:</p><pre>Traffic<br>████████████████████</pre><pre>Available capacity<br>██████</pre><p>For a short period, demand can be much higher than the capacity that is actually ready.</p><p>That’s exactly why <strong>“auto-scaling is enabled” doesn’t automatically mean “the system can handle every traffic spike.”</strong></p><h3>The real deployment problem</h3><p>The interesting part wasn’t simply that the ELB failed.</p><p>It was the combination of:</p><p><strong>deployment + new load balancer + scaling delay + production traffic.</strong></p><p>Before deployment:</p><pre>DNS<br> |<br> v<br>Old ELB <br>[Already scaled]<br> |<br> v<br>Servers</pre><p>During deployment:</p><pre>DNS<br> |<br> v<br>New ELB <br>[Not fully scaled]<br> |<br> v<br>New Servers</pre><p>The deployment switched DNS to the new ELB.</p><p>So production traffic moved from a <strong>warm, already-scaled load balancer</strong> to a <strong>new load balancer that was still scaling</strong>.</p><p>That was the dangerous part.</p><h3>So what could have prevented it?</h3><p>One obvious approach would be to make sure the new load balancer had enough capacity <strong>before</strong> sending production traffic to it.</p><p>In simple terms:</p><pre>Create new ELB<br>      ↓<br>Wait for it to scale<br>      ↓<br>Verify it is ready<br>      ↓<br>Send production traffic</pre><p>This is the basic idea behind <strong>pre-warming / pre-scaling</strong>.</p><p>But Atlassian’s actual permanent fix was different.</p><h3>How did Atlassian fix it?</h3><p>Atlassian switched to a <strong>single Application Load Balancer (ALB)</strong>.</p><p>The important reason was that their internal deployment process did not cycle the ALB.</p><p>So instead of repeatedly doing:</p><pre>Old ELB<br>   ↓<br>Replace it<br>   ↓<br>New ELB</pre><p>they moved to:</p><pre>ALB<br>              |<br>      +-------+-------+<br>      |       |       |<br>    Server  Server  Server</pre><p>The load balancer remained in place while deployments happened.</p><p>According to Atlassian, this fixed the reliability problem, and they did not experience the same outage again after the switch.</p><p>There was a trade-off, though.</p><p>Their p99 latency increased from roughly <strong>7–10 ms to around 20 ms</strong>. The reason was partly that ELBs and ALBs use different routing algorithms.</p><p>So even the fix had a performance cost.</p><p>That’s an important engineering lesson:</p><blockquote><strong><em>Reliability improvements can sometimes come with performance trade-offs.</em></strong></blockquote><h3>What can we learn from this?</h3><h3>1. Load balancers can fail too</h3><p>A load balancer isn’t an unlimited gateway.</p><p>It has its own:</p><ul><li>memory</li><li>capacity</li><li>scaling time</li><li>failure modes</li></ul><p>In this incident, the ELB itself eventually died because of an out-of-memory condition.</p><h3>2. Auto-scaling isn’t instant</h3><p>If your infrastructure takes several minutes to become ready, you need to account for that delay.</p><p>For example:</p><pre>Traffic spike<br>     ↓<br>Auto-scaling starts<br>     ↓<br>New capacity is created<br>     ↓<br>New capacity becomes ready</pre><p>There is a gap between <strong>“we need capacity”</strong> and <strong>“capacity is actually available.”</strong></p><h3>3. Deployments can affect infrastructure</h3><p>A deployment isn’t only about:</p><pre>New code → New servers</pre><p>It can also change:</p><pre>Load balancers<br>DNS<br>Routing<br>Networking<br>Capacity</pre><p>That’s why deployment systems need to consider infrastructure readiness too.</p><h3>4. Monitor the whole request path</h3><p>Don’t only monitor your API servers.</p><p>Think about the entire path:</p><pre>User<br> ↓<br>DNS<br> ↓<br>Load Balancer<br> ↓<br>Application<br> ↓<br>Database</pre><p>A problem at any layer can make the application unavailable.</p><h3>5. Don’t send production traffic to unready infrastructure</h3><p>If a new component needs time to scale, don’t immediately assume it’s ready just because it has been created.</p><p>A safer approach is:</p><pre>Create<br>  ↓<br>Scale<br>  ↓<br>Health check<br>  ↓<br>Verify capacity<br>  ↓<br>Shift traffic</pre><h3>Blue-Green vs Rolling Deployment</h3><p>This incident also gives us a good opportunity to understand deployment strategies.</p><h3>Blue-Green</h3><p>You maintain two environments:</p><pre>Traffic<br>                |<br>          +-----+-----+<br>          |           |<br>        BLUE         GREEN<br>        v1            v2<br>       LIVE          READY</pre><p>You prepare GREEN and then move traffic to it.</p><p>The advantage is that the old environment can remain available as a fallback.</p><p>But there is an important requirement:</p><p><strong>The new environment must actually be ready before you send production traffic to it.</strong></p><h3>Rolling Deployment</h3><p>With rolling deployment, you gradually replace the old servers:</p><pre>v1  v1  v1  v1<br> ↓<br>v2  v1  v1  v1<br> ↓<br>v2  v2  v1  v1<br> ↓<br>v2  v2  v2  v1<br> ↓<br>v2  v2  v2  v2</pre><p>This lets you maintain existing capacity while gradually introducing the new version.</p><p>For this particular Atlassian incident, the key improvement was <strong>keeping the load balancer from being cycled during deployment</strong>, rather than simply saying “blue-green was replaced by rolling deployment.” Atlassian’s original post specifically says the fix was switching to a single ALB that their internal deployment process did not cycle.</p><h3>The bigger lesson</h3><p>The most important lesson from Atlassian’s 2019 outage isn’t:</p><p><strong>“Load balancers are unreliable.”</strong></p><p>It’s this:</p><blockquote><strong><em>Every component in a distributed system has its own capacity, scaling behavior, and failure modes.</em></strong></blockquote><p>Your application servers can be healthy.</p><p>Your database can be healthy.</p><p>Your dashboards can look normal.</p><p>And users can still be unable to access your service because the load-balancing layer in front of those servers isn’t ready or has failed.</p><p>That’s why reliable systems need more than auto-scaling.</p><p>They need:</p><ul><li>Capacity planning</li><li>Infrastructure monitoring</li><li>Safe deployment strategies</li><li>Gradual traffic shifting</li><li>Readiness checks</li><li>An understanding of how long infrastructure takes to scale</li></ul><p>The cloud gives us powerful building blocks.</p><p>But as Atlassian’s experience shows:</p><p><strong>Cloud infrastructure doesn’t remove distributed-systems problems. It just moves them to a different layer.</strong></p><p>And sometimes, the component you least expect — the load balancer — is the one that takes the whole service down.</p><p>hope you love this ankitkr.in</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e674d8d116a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Thundering Herd Problem: When Your Cache Turns Into a Database DDoS]]></title>
            <link>https://medium.com/@codingank/the-thundering-herd-problem-when-your-cache-turns-into-a-database-ddos-3ac64ca31644?source=rss-c31843ca9ced------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ac64ca31644</guid>
            <category><![CDATA[backend-engineering]]></category>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[design-systems]]></category>
            <dc:creator><![CDATA[Ankitkr]]></dc:creator>
            <pubDate>Thu, 13 Aug 2026 10:54:04 GMT</pubDate>
            <atom:updated>2026-08-13T10:54:04.543Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*czHy3HgCfYDAHoPPnia8Iw.png" /><figcaption>thundering-herd-problem</figcaption></figure><p>Caching is one of the most powerful techniques for scaling backend systems.</p><p>Instead of sending every request to the database, we store frequently accessed data in a fast cache such as Redis:</p><pre>User<br>  ↓<br>Backend<br>  ↓<br>Redis<br>  ↓<br>Database</pre><p>Most of the time, this works beautifully.</p><p>But there is a dangerous situation that every backend engineer should understand:</p><p><strong>What happens when a popular cache entry expires and thousands of requests arrive at exactly the same time?</strong></p><p>That is the <strong>Thundering Herd Problem</strong>.</p><p>It is also commonly called a <strong>Cache Stampede</strong>.</p><h3>1. The Basic Idea</h3><p>Imagine we have an API:</p><pre>GET /video/123</pre><p>Video 123 is extremely popular.</p><p>Without caching:</p><pre>100,000 requests<br>       ↓<br>   Database<br>       ↓<br>    💥 💥 💥</pre><p>The database has to process 100,000 requests.</p><p>So we introduce Redis:</p><pre>100,000 requests<br>       ↓<br>      Redis<br>       ↓<br>    Cache HIT<br>       ↓<br>   Return data</pre><p>Now the database might only receive a small number of requests.</p><p>Everything looks great.</p><p>But there is a hidden problem.</p><h3>2. What Happens When the Cache Expires?</h3><p>Suppose our Redis entry looks like this:</p><pre>video:123<br>TTL = 60 seconds</pre><p>For the next 60 seconds:</p><pre>Request<br>   ↓<br>Redis<br>   ↓<br>HIT ✅<br>   ↓<br>Return</pre><p>But after 60 seconds:</p><pre>video:123<br>    ↓<br>EXPIRED ❌</pre><p>Now imagine that video:123 is extremely popular.</p><p>At that exact moment, 50,000 users request the video.</p><pre>50,000 requests<br>       ↓<br>      Redis<br>       ↓<br>     MISS ❌</pre><p>Every request thinks:</p><blockquote><em>“The cache doesn’t have the data. I’ll get it from the database.”</em></blockquote><p>So:</p><pre>Request 1  ──→ Database<br>Request 2  ──→ Database<br>Request 3  ──→ Database<br>Request 4  ──→ Database<br>...<br>Request 50,000 ─→ Database</pre><p>Instead of:</p><pre>50,000 requests → Redis</pre><p>we suddenly have:</p><pre>50,000 requests → Database</pre><p>The cache was supposed to protect the database.</p><p>Instead, the cache expiration caused a massive database spike.</p><p>That is the <strong>Thundering Herd Problem</strong>.</p><h3>3. Why Is It Called “Thundering Herd”?</h3><p>Imagine thousands of animals standing quietly.</p><p>Suddenly, something scares them.</p><p>They all run toward the same place at the same time.</p><p>That’s essentially what happens to your backend:</p><pre>Cache<br>                   ↓<br>               EXPIRATION<br>                   ↓<br>        ┌──────────┼──────────┐<br>        ↓          ↓          ↓<br>     Request    Request    Request<br>        ↓          ↓          ↓<br>        └──────────┼──────────┘<br>                   ↓<br>                Database<br>                   ↓<br>                  💥</pre><p>Thousands of requests “stampede” toward the database.</p><p>Hence:</p><p><strong>Thundering Herd.</strong></p><h3>4. The Real Danger</h3><p>The biggest problem isn’t simply that the database receives many requests.</p><p>The dangerous part is the <strong>feedback loop</strong>.</p><p>Suppose your database can normally handle:</p><pre>10,000 queries/sec</pre><p>But suddenly it receives:</p><pre>100,000 queries/sec</pre><p>The database becomes slow.</p><p>Then:</p><pre>Database becomes slow<br>        ↓<br>Requests take longer<br>        ↓<br>Connections remain occupied<br>        ↓<br>More requests wait<br>        ↓<br>Application servers consume more resources<br>        ↓<br>Timeouts increase<br>        ↓<br>Retries happen<br>        ↓<br>Even more requests hit database</pre><p>Now the original cache expiration has turned into a system-wide incident.</p><p>It can look like:</p><pre>Cache expiration<br>      ↓<br>Cache MISS<br>      ↓<br>Database overload<br>      ↓<br>High latency<br>      ↓<br>Timeouts<br>      ↓<br>Retries<br>      ↓<br>More database traffic<br>      ↓<br>More overload</pre><p>This is why cache stampedes can be surprisingly destructive.</p><h3>5. A Simple Timeline</h3><p>Let’s make the problem concrete.</p><p>Suppose:</p><pre>10:00:00<br>Cache populated</pre><pre>10:00:00 → 10:01:00<br>Cache HIT</pre><pre>10:01:00<br>TTL expires</pre><pre>10:01:00<br>100,000 users request the same data</pre><pre>10:01:00<br>100,000 cache MISSes</pre><pre>10:01:01<br>100,000 database requests</pre><pre>10:01:02<br>Database overloaded</pre><pre>10:01:03<br>Requests start timing out</pre><p>The important moment is:</p><pre>TTL expires<br>               ↓<br>               X<br>               ↓<br>       Many requests<br>       arrive together<br>               ↓<br>          Cache MISS<br>               ↓<br>          Database 💥</pre><h3>6. Why Does This Happen So Easily?</h3><p>One reason is that developers often use a fixed TTL.</p><p>For example:</p><pre>TTL = 60 seconds</pre><p>Imagine 100,000 popular objects are loaded around the same time:</p><pre>video:1   → TTL 60 sec<br>video:2   → TTL 60 sec<br>video:3   → TTL 60 sec<br>video:4   → TTL 60 sec<br>...</pre><p>If they were inserted at roughly the same time, they can expire around the same time.</p><p>That creates a synchronized expiration event.</p><p>This leads us to the first mitigation technique.</p><h3>7. Solution #1: TTL Jitter</h3><p>Instead of giving every cache entry exactly:</p><pre>TTL = 60 seconds</pre><p>we add some randomness.</p><p>For example:</p><pre>TTL = 60 + random(0, 10)</pre><p>Now entries might expire at:</p><pre>video:1 → 63 sec<br>video:2 → 68 sec<br>video:3 → 61 sec<br>video:4 → 69 sec<br>video:5 → 64 sec</pre><p>Instead of:</p><pre>60 sec<br>  ↓<br>EVERYTHING EXPIRES<br>  ↓<br>💥</pre><p>we get:</p><pre>60 sec → some entries expire<br>62 sec → some entries expire<br>64 sec → some entries expire<br>67 sec → some entries expire<br>69 sec → some entries expire</pre><p>The expiration workload becomes distributed over time.</p><h3>Important</h3><p>TTL jitter does <strong>not</strong> eliminate cache misses.</p><p>It reduces the chance of <strong>many cache entries expiring simultaneously</strong>.</p><h3>8. Solution #2: Stale While Revalidate</h3><p>Another powerful strategy is:</p><p><strong>Stale While Revalidate (SWR).</strong></p><p>Instead of immediately throwing away stale data and forcing the user to wait for fresh data, we can temporarily serve the stale value while refreshing it in the background.</p><p>Suppose:</p><pre>Cache:<br>video:123 → old data</pre><p>A request arrives.</p><p>Instead of:</p><pre>Request<br>  ↓<br>Cache stale<br>  ↓<br>Database<br>  ↓<br>Wait<br>  ↓<br>Fresh response</pre><p>we can do:</p><pre>Request<br>  ↓<br>Stale cache<br>  ↓<br>Return immediately</pre><p>Meanwhile, in the background:</p><pre>Background refresh<br>       ↓<br>    Database<br>       ↓<br> Fresh data<br>       ↓<br> Update Redis</pre><p>So:</p><pre>Cache<br>                      ↓<br>                 stale data<br>                      │<br>             ┌────────┴────────┐<br>             ↓                 ↓<br>           User            Background<br>             ↓                 ↓<br>      Return quickly        Database<br>                                ↓<br>                           Fresh data<br>                                ↓<br>                           Update cache</pre><p>The user doesn’t have to wait.</p><h3>9. Why SWR Helps With Thundering Herd</h3><p>Imagine:</p><pre>100,000 users<br>      ↓<br>Stale cache</pre><p>With SWR, they can receive the stale value:</p><pre>100,000 users<br>      ↓<br>Cached response</pre><p>while the cache is refreshed in the background.</p><p>So instead of:</p><pre>100,000 requests<br>      ↓<br>Database</pre><p>you can have:</p><pre>100,000 requests<br>      ↓<br>Cache<br>      ↓<br>Immediate response</pre><pre>Background<br>      ↓<br>One/few refresh operations<br>      ↓<br>Database</pre><p>This dramatically reduces the pressure on the database.</p><h3>10. Solution #3: Mutex / Distributed Lock</h3><p>Now consider another situation.</p><p>The cache is completely missing.</p><p>You have:</p><pre>100,000 requests<br>       ↓<br>Cache MISS</pre><p>SWR may not be enough because there is no stale value to return.</p><p>We need another technique.</p><p>One approach is a <strong>lock</strong>.</p><p>The idea is:</p><blockquote><em>Only one request should be responsible for rebuilding the cache.</em></blockquote><p>For example:</p><pre>Request 1<br>Request 2<br>Request 3<br>...<br>Request 100,000<br>        ↓<br>     Cache MISS</pre><p>Request 1 obtains a lock:</p><pre>LOCK video:123</pre><p>Then:</p><pre>Request 1<br>    ↓<br>  Database<br>    ↓<br>Fresh data<br>    ↓<br> Redis<br>    ↓<br>UNLOCK</pre><p>The other requests wait, retry, or otherwise avoid independently querying the database.</p><p>Conceptually:</p><pre>100,000 requests<br>       ↓<br>   Cache MISS<br>       ↓<br> ┌─────┴─────┐<br> │           │<br>One request  Others<br> │           │<br> ↓           ↓<br>LOCK       Wait/retry<br> │<br> ↓<br>DB<br> │<br> ↓<br>Redis<br> │<br> ↓<br>UNLOCK</pre><p>Now instead of:</p><pre>100,000 DB queries</pre><p>we aim for:</p><pre>1 DB query</pre><h3>11. Mutex vs SWR</h3><p>These are different concepts.</p><h3>SWR</h3><p>Answers:</p><blockquote><em>“What should I do when my cached data is stale?”</em></blockquote><p>Answer:</p><pre>Return stale data<br>+<br>Refresh in background</pre><h3>Mutex</h3><p>Answers:</p><blockquote><em>“What should I do if many requests try to refresh the same data simultaneously?”</em></blockquote><p>Answer:</p><pre>Allow one request to refresh<br>while others wait/share/retry</pre><p>They can be combined.</p><p>For example:</p><pre>100,000 requests<br>       ↓<br>Stale cache<br>       ↓<br>Return stale data<br>       ↓<br>One request obtains refresh lock<br>       ↓<br>Database<br>       ↓<br>Update cache</pre><p>This gives you both:</p><ul><li>Fast responses</li><li>Controlled database traffic</li></ul><h3>12. Solution #4: Request Coalescing</h3><p>Another approach is <strong>request coalescing</strong>, also called request deduplication or single-flight in some implementations.</p><p>Imagine 1,000 requests all ask for:</p><pre>product:123</pre><p>Instead of executing:</p><pre>1,000 database queries</pre><p>the application recognizes:</p><blockquote><em>“Someone is already fetching product:123.”</em></blockquote><p>So the other requests attach to the same in-flight operation.</p><pre>Request 1 ─┐<br>Request 2 ─┤<br>Request 3 ─┤<br>Request 4 ─┤<br>...        ├──→ One database request<br>Request 999┘<br>                    ↓<br>                 Result<br>                    ↓<br>             All requests</pre><p>Again:</p><pre>1,000 requests<br>      ↓<br>1 database operation</pre><p>The exact implementation differs from a mutex, but the goal is similar:</p><p><strong>Don’t perform the same expensive operation thousands of times concurrently.</strong></p><h3>13. Solution #5: Cache Warming</h3><p>Sometimes the best way to handle a spike is to prepare before it happens.</p><p>Suppose you know that a major sports match starts at:</p><pre>7:00 PM</pre><p>You know millions of users will request:</p><pre>match information<br>team information<br>player information</pre><p>Instead of waiting until 7:00 PM:</p><pre>7:00 PM<br>   ↓<br>Millions of requests<br>   ↓<br>Cache MISS<br>   ↓<br>Database</pre><p>you can warm the cache beforehand:</p><pre>6:30 PM</pre><pre>Database<br>   ↓<br>Cache<br>   ↓<br>Popular data ready</pre><pre>7:00 PM</pre><pre>Millions of users<br>       ↓<br>     Cache HIT</pre><p>This is <strong>cache warming</strong>.</p><p>It is especially useful when traffic is predictable.</p><h3>14. Cache Warming vs SWR</h3><p>These are also different.</p><h3>Cache warming</h3><pre>Before users need the data</pre><pre>Database<br>   ↓<br>Cache</pre><p>It is proactive.</p><h3>SWR</h3><pre>When cached data becomes stale</pre><pre>Cache<br>   ↓<br>Return stale data<br>   +<br>Refresh in background</pre><p>It is reactive.</p><h3>15. Solution #6: Negative Caching</h3><p>There is another less obvious cache stampede.</p><p>Suppose an attacker or a buggy client repeatedly requests:</p><pre>GET /user/999999999</pre><p>But the user doesn’t exist.</p><p>Every request could do:</p><pre>Redis MISS<br>   ↓<br>Database<br>   ↓<br>User doesn&#39;t exist</pre><p>Again and again.</p><p>Instead, temporarily cache the negative result:</p><pre>user:999999999 → NOT_FOUND<br>TTL = 30 sec</pre><p>Now:</p><pre>Request<br>   ↓<br>Redis<br>   ↓<br>NOT_FOUND<br>   ↓<br>Return 404</pre><p>The database is protected from repeated requests for the same nonexistent resource.</p><p>This technique is called <strong>negative caching</strong>.</p><h3>16. Solution #7: Stale-if-Error</h3><p>What happens if your database is currently unavailable?</p><p>Suppose Redis has:</p><pre>Product price = ₹50,000</pre><p>The data is old, but still usable.</p><p>Then:</p><pre>Database ❌</pre><p>Instead of immediately returning an error, some systems can serve the stale cached value:</p><pre>Cache<br> ↓<br>Old data<br> ↓<br>Database unavailable<br> ↓<br>Return stale data</pre><p>This improves availability at the cost of freshness.</p><p>It’s another system-design tradeoff:</p><pre>Freshness<br>    ↕<br>Availability</pre><p>Whether this is acceptable depends entirely on the data.</p><p>For a news article, stale data may be fine.</p><p>For a bank balance, it may be unacceptable.</p><h3>17. Combining the Strategies</h3><p>The strongest systems usually don’t rely on one technique.</p><p>They combine several.</p><p>For example:</p><pre>Request<br>                          ↓<br>                       Redis<br>                          │<br>                 ┌────────┴────────┐<br>                 │                 │<br>                HIT               MISS<br>                 │                 │<br>                 ↓                 ↓<br>              Return             Lock<br>                                   ↓<br>                              Database<br>                                   ↓<br>                              Update Cache<br>                                   ↓<br>                                Unlock</pre><p>And for entries that are stale:</p><pre>Request<br>                       ↓<br>                   Stale Cache<br>                       │<br>              ┌────────┴────────┐<br>              ↓                 ↓<br>         Return stale       Background<br>             data            refresh<br>                                ↓<br>                              Lock<br>                                ↓<br>                                DB<br>                                ↓<br>                          Update cache</pre><p>The cache itself might use:</p><pre>TTL<br>+<br>TTL Jitter<br>+<br>SWR<br>+<br>Cache Warming</pre><p>And the system might additionally use:</p><pre>Request Coalescing<br>Negative Caching<br>Stale-if-Error</pre><h3>18. But Don’t Cache Everything</h3><p>Caching isn’t automatically good.</p><p>You need to consider:</p><h3>How frequently does the data change?</h3><p>If data changes every millisecond, caching it for 10 minutes may be unacceptable.</p><h3>How expensive is the database operation?</h3><p>If the query is cheap, caching may not provide much benefit.</p><h3>How much memory does the cache consume?</h3><p>Redis isn’t infinite.</p><h3>How stale can the data be?</h3><p>This is a business requirement.</p><p>For example:</p><pre>News article<br>→ 30 seconds stale may be fine</pre><pre>Product catalog<br>→ 1 minute may be fine</pre><pre>Bank balance<br>→ stale data may be dangerous</pre><p>So caching is always a tradeoff.</p><h3>19. The Complete Mental Model</h3><p>When designing a cache, ask these questions:</p><h3>Question 1</h3><p><strong>How long should data remain cached?</strong></p><p>→ TTL</p><h3>Question 2</h3><p><strong>What if many entries expire at the same time?</strong></p><p>→ TTL Jitter</p><h3>Question 3</h3><p><strong>What if many users request the same missing key?</strong></p><p>→ Mutex / Request Coalescing</p><h3>Question 4</h3><p><strong>What if the data is stale but still usable?</strong></p><p>→ Stale While Revalidate</p><h3>Question 5</h3><p><strong>What if I know a huge traffic spike is coming?</strong></p><p>→ Cache Warming</p><h3>Question 6</h3><p><strong>What if users repeatedly request something that doesn’t exist?</strong></p><p>→ Negative Caching</p><h3>Question 7</h3><p><strong>What if the database is temporarily unavailable?</strong></p><p>→ Stale-if-Error, if the business case permits it</p><h3>20. The Big Picture</h3><p>A well-designed caching system might look conceptually like this:</p><pre>Users<br>                           │<br>                           ▼<br>                      Load Balancer<br>                           │<br>                           ▼<br>                       App Servers<br>                           │<br>                           ▼<br>                         Redis<br>                           │<br>                 ┌─────────┴─────────┐<br>                 │                   │<br>                HIT                 MISS<br>                 │                   │<br>                 ▼                   ▼<br>              Response            Lock<br>                                     │<br>                                     ▼<br>                                  Database<br>                                     │<br>                                     ▼<br>                               Update Redis<br>                                     │<br>                                     ▼<br>                                   Unlock</pre><p>Around this, we can use:</p><pre>TTL<br>TTL Jitter<br>SWR<br>Cache Warming<br>Request Coalescing<br>Negative Caching<br>Stale-if-Error</pre><p>to handle different failure and traffic patterns.</p><h3>21. The Most Important Thing to Remember</h3><p>The Thundering Herd Problem isn’t really about Redis.</p><p>It’s about <strong>synchronized work</strong>.</p><p>The dangerous pattern is:</p><pre>MANY<br>                 ↓<br>              requests<br>                 ↓<br>             SAME TIME<br>                 ↓<br>              SAME KEY<br>                 ↓<br>              SAME MISS<br>                 ↓<br>             EXPENSIVE<br>               WORK<br>                 ↓<br>              DATABASE<br>                 ↓<br>                💥</pre><p>A good system tries to break that synchronization.</p><p>You can break it by:</p><pre>TTL Jitter<br>     ↓<br>Spread expiration over time<br></pre><pre>SWR<br>     ↓<br>Don&#39;t make users wait for refresh<br></pre><pre>Mutex<br>     ↓<br>Only one refresh operation<br></pre><pre>Request Coalescing<br>     ↓<br>Share one in-flight operation<br></pre><pre>Cache Warming<br>     ↓<br>Prepare before the traffic arrives</pre><p>That’s the real lesson behind the <strong>Thundering Herd Problem</strong>:</p><blockquote><strong><em>When thousands of requests suddenly need the same expensive resource, don’t let every request perform the expensive work independently. Control, spread, or eliminate that work.</em></strong></blockquote><p>Hope you love this — — ankitkr.in</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ac64ca31644" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Architecture Behind Gemma That’s Quietly Changing Local AI Forever]]></title>
            <link>https://medium.com/@codingank/the-architecture-behind-gemma-thats-quietly-changing-local-ai-forever-96c889d6d52e?source=rss-c31843ca9ced------2</link>
            <guid isPermaLink="false">https://medium.com/p/96c889d6d52e</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Ankitkr]]></dc:creator>
            <pubDate>Sat, 06 Jun 2026 08:57:23 GMT</pubDate>
            <atom:updated>2026-06-06T08:57:23.703Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W_Q7z3KttOmUyvTHRlEEmQ.jpeg" /><figcaption>Gemma Engineering</figcaption></figure><h3>What is an LLM Really?</h3><p>Imagine: &quot;Hello&quot; ?</p><p>The model’s only job is:</p><blockquote><strong><em>Predict the next token.</em></strong></blockquote><p>Example:</p><p>I love eating ...</p><p>Possible predictions:</p><pre>pizza  -&gt; 60%<br>burger -&gt; 20%<br>rice   -&gt; 10%</pre><p>It chooses one and continues.</p><p>Everything — coding, reasoning, chatting — is just very sophisticated next-token prediction.</p><h3>The Core Pipeline</h3><p>When you write:</p><p>Explain JavaScript closures</p><p>the model does:</p><pre>Text<br>↓<br>Tokens<br>↓<br>Embeddings<br>↓<br>Attention Layers<br>↓<br>Feed Forward Layers<br>↓<br>Next Token</pre><p>Think of it as:</p><pre>Input<br>↓<br>Brain Layers<br>↓<br>Output</pre><h3>What is Attention REALLY?</h3><p>Suppose you ask:</p><pre>Ankit went to school.<br>He played football.</pre><p>Who played football?</p><p>To answer:</p><p>He = Ankit</p><p>the model must look back.</p><h4>Attention is simply:</h4><pre>Current token<br>↓<br>Look at previous tokens<br>↓<br>Decide which are important</pre><p>Imagine an array:</p><pre>[<br>  &quot;Ankit&quot;,<br>  &quot;went&quot;,<br>  &quot;to&quot;,<br>  &quot;school&quot;,<br>  &quot;.&quot;,<br>  &quot;He&quot;,<br>  &quot;played&quot;,<br>  &quot;football&quot;<br>]</pre><p>When processing He, the model searches previous tokens:</p><pre>Ankit ← important<br>went  ← not important<br>school← not important</pre><p>Attention is basically:</p><p><strong><em>Which previous tokens matter most?</em></strong></p><h3>Why is Attention Expensive?</h3><p>Suppose: 1000 tokens</p><p>For every token — compare with all previous tokens:</p><pre>Token 1   checks: 0 tokens<br>Token 500 checks: 499 tokens<br>Token 1000 checks: 999 tokens</pre><p>Total work grows roughly as <strong>N²</strong>.</p><p>So:</p><pre>1000 tokens<br>↓<br>1,000,000 comparisons</pre><p>That’s why long contexts are expensive.</p><h3>Gemma’s First Trick: Local + Global Attention</h3><p><strong>Old model:</strong></p><pre>Every layer<br>↓<br>Look at everything</pre><p>Expensive.</p><p><strong>Gemma 4:</strong></p><p>Most layers look nearby only.</p><p>Example:</p><pre>Current token = 1000</pre><pre>Only inspect: 900–1000<br>instead of:   1–1000</pre><p>Much cheaper. But sometimes you need the big picture — so every few layers, a <strong>Global Layer</strong> looks at everything.</p><p>Think:</p><pre>Local Layer<br>Local Layer<br>Local Layer<br>Local Layer<br>Global Layer</pre><p>Like coding:</p><pre>for(...) {<br>  doCheapWork();<br>}</pre><pre>occasionallyDoExpensiveWork();</pre><p>Same idea.</p><h3>Sliding Window</h3><p>Imagine:</p><pre>const chat = [<br>  msg1,<br>  msg2,<br>  msg3,<br>  ...<br>];</pre><p>Instead of reading the entire chat:</p><pre>chat.slice(-1000);</pre><p>Only last 1000 tokens.</p><p>That’s literally what <strong>sliding window</strong> means.</p><h3>Grouped Query Attention (GQA)</h3><p>This one sounds scary. Let’s simplify.</p><p>Suppose 8 developers need docs.</p><p><strong>Without sharing:</strong></p><pre>8 copies<br>Memory: 8 GB</pre><p><strong>With sharing:</strong></p><pre>1 copy<br>Memory: 1 GB</pre><p>Everybody references the same docs.</p><p>That’s basically GQA.</p><p>Instead of each attention head getting its own KV cache — they share.</p><p><strong>Result:</strong></p><ul><li>Less VRAM</li><li>Faster inference</li></ul><p>…without losing much quality.</p><h3>What is KV Cache?</h3><p>Very important.</p><p>Suppose conversation:</p><pre>Hello<br>How are you?<br>What is Java?</pre><p>The model already computed Hello and How are you? — why recompute?</p><p>Store it:</p><pre>cache.set(token, result);</pre><p>KV Cache is basically:</p><blockquote><strong><em>Previously computed attention information stored for reuse.</em></strong></blockquote><p>Huge speedup.</p><h3>What is MoE?</h3><p>Now the fun part.</p><p>Imagine a startup with these employees:</p><pre>Backend Engineer<br>Frontend Engineer<br>DevOps Engineer<br>Designer<br>Product Manager</pre><p>User asks: <em>Deploy Kubernetes cluster</em></p><p>Do you wake everyone? No. You wake:</p><pre>DevOps Engineer</pre><p><strong>Dense model:</strong> Wake everyone, every time.</p><p><strong>MoE:</strong></p><pre>Question arrives<br>↓<br>Router decides<br>↓<br>Activate only useful experts</pre><p>Like:</p><pre>if (question === &quot;coding&quot;)<br>  useCodingExperts();</pre><pre>if (question === &quot;math&quot;)<br>  useMathExperts();</pre><p>…except learned automatically.</p><p><strong>Gemma 26B:</strong></p><pre>128 experts exist<br>But only 8 active</pre><p>So: huge knowledge, small compute.</p><h3>The Router</h3><p>Think:</p><pre>function route(question) {<br>  return bestExperts;<br>}</pre><p>The router decides:</p><pre>Expert 17<br>Expert 29<br>Expert 88<br>...activate these.</pre><p>Everything else sleeps.</p><h3>Why is This Powerful?</h3><p><strong>Without MoE:</strong></p><pre>26B parameters used every token.</pre><p><strong>With MoE:</strong></p><pre>26B stored<br>but only 3.8B active during inference.</pre><p>That’s a massive savings.</p><h3>What are Embeddings?</h3><p>Suppose: Dog</p><p>Computer doesn’t understand words. Need numbers.</p><p>Convert:</p><pre>Dog<br>↓<br>[0.2, 1.5, -0.7, ...]</pre><p>This vector is called an <strong>embedding</strong>.</p><p>Think:</p><pre>Word<br>↓<br>Coordinates in a giant meaning-space</pre><h3>Per Layer Embeddings (PLE)</h3><p><strong>Normal model:</strong></p><pre>One dictionary for embeddings.</pre><p><strong>Gemma 4:</strong></p><pre>Layer 1 dictionary<br>Layer 2 dictionary<br>Layer 3 dictionary<br>...</pre><p>Each layer gets extra knowledge.</p><p>Analogy: You’re solving DSA. Instead of one notebook, you have:</p><pre>Notebook 1<br>Notebook 2<br>Notebook 3</pre><p>…for every stage. More information available.</p><h3>Why Store in Flash?</h3><p>Phone memory:</p><pre>RAM     = expensive<br>Storage = cheap</pre><p>Google says: keep huge embedding tables inside storage, not RAM.</p><p><strong>Result:</strong> Stronger model, same RAM usage.</p><h3>Vision Improvements</h3><p><strong>Old Gemma</strong> — large image handling:</p><pre>Screenshot<br>↓<br>Crop 1 | Crop 2<br>Crop 3 | Crop 4</pre><pre>Process separately.</pre><p>Problem: Imagine reading a book by cutting every page into pieces. Context gets lost.</p><p><strong>Gemma 4</strong> can handle:</p><ul><li>Wide images</li><li>Tall images</li><li>Different resolutions</li></ul><p>…directly.</p><p>Better for: OCR, UI screenshots, documents, charts.</p><h3>Why Engineers Care</h3><p>All these changes improve one of these:</p><ul><li><strong>Quality</strong></li><li><strong>Latency</strong></li><li><strong>Memory</strong></li><li><strong>Cost</strong></li></ul><p>Gemma 4 improved all four.</p><p>Improvement Why Local Attention Less compute GQA Less KV memory MoE More intelligence per FLOP PLE Better small models Better Vision Better OCR &amp; image understanding 256K Context Bigger memory Audio Support Multimodal</p><h3>The Big Engineering Lesson</h3><blockquote><em>Gemma 4 didn’t become much better because it got massively larger. It became better because Google found ways to spend computation more intelligently.</em></blockquote><blockquote><em>That’s the same mindset as optimizing a backend system: </em><strong><em>don’t just add more servers — reduce wasted work.</em></strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96c889d6d52e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Hybrid Healthcare AI for Orthopedics — Small LLaMA + GPT-4 Fallback + RAG]]></title>
            <link>https://medium.com/@codingank/building-a-hybrid-healthcare-ai-for-orthopedics-small-llama-gpt-4-fallback-rag-2401666112d2?source=rss-c31843ca9ced------2</link>
            <guid isPermaLink="false">https://medium.com/p/2401666112d2</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[healthcare]]></category>
            <dc:creator><![CDATA[Ankitkr]]></dc:creator>
            <pubDate>Wed, 22 Apr 2026 05:33:59 GMT</pubDate>
            <atom:updated>2026-04-22T05:33:59.011Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A realistic, honest architecture for a bone disease AI system that is</em><strong><em> private</em></strong><em>, </em><strong><em>accurate, and cost-effective</em></strong></p><h3>The Problem Every Healthcare System Faces</h3><p>Imagine a doctor at 2 AM typing:</p><blockquote>“What is the recommended dosage of alendronate for a 65-year-old patient with osteoporosis and kidney disease”</blockquote><p>They need a fast, accurate, trustworthy answer. But here’s the dilemma:</p><ul><li><strong>A small local model is safe and free to run</strong> — but it says something like <em>“consult a doctor”</em> or gives a wrong dose.</li></ul><p>So what do you do?</p><p>You do what the smartest AI companies in the world do. You use <strong>Knowledge Distillation</strong>.</p><h4>The Core Idea —Distillation &amp; Hybrid , but data never touch cloud</h4><h3>What Is Knowledge Distillation?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*rFo4GBFI8QdS88WuFsbqhw.png" /></figure><p>Think of it like this.</p><p>You have a brilliant senior doctor — 30 years of experience, trained at the best medical school, knows every guideline, every drug interaction, every rare condition. But they charge $500/hour and you can’t clone them.</p><p>Now you hire a fresh, smart junior doctor. Lower cost. Works on-site. Available 24/7.</p><p>You sit the junior doctor next to the senior doctor for 6 months. The junior watches everything — how the senior thinks, what they prioritize, how they weigh options. Eventually, the junior doctor starts <em>thinking like</em> the senior.</p><p><strong>That’s distillation.</strong></p><ul><li>The senior doctor = <strong>GPT-4/5 (the Teacher model)</strong></li><li>The junior doctor = <strong>LLaMA 3B (the Student model)</strong></li><li>The 6-month training = <strong>Fine-tuning on teacher’s outputs</strong></li></ul><p>Our approach is smarter: data never touch cloud</p><pre>QUERY COMES IN<br>                          │<br>                          ▼<br>              ┌─── Is this about a specific patient? ───┐<br>              │                                         │<br>             YES                                        NO<br>              │                                         │<br>              ▼                                         ▼<br>    RAG → fetch from                        Local LLaMA tries<br>    encrypted local DB                      to answer<br>   Answer locally ✅ llm                          │<br>    Never hits cloud                              │<br>                                    ┌─────────────┴──────────────┐<br>                                    │                            │<br>                              Confident?                   Not confident?<br>                                    │                            │<br>                                    ▼                            ▼<br><br>                            Show answer               Escalate to GPT-4<br>                            ⚠️ verify first           Get better answer<br>                                                      Log it for retraining<br>                                                      small model to learn it</pre><p><strong>The key principle:</strong></p><ul><li>Sensitive patient data → always answered by <strong>local model via RAG</strong>, never touches cloud</li><li>Complex general medical questions → <strong>local model tries first</strong>, GPT-4 as fallback</li><li>Every GPT-4 answer → <strong>logged and used to improve local model over time that will make our small model strong over time</strong></li></ul><h3>Step 1 — Distill a Bone Disease Specialist from GPT-4/5</h3><p>Instead of trying to make a small model good at everything (impossible), you make it excellent at <strong>one narrow domain: orthopedics and bone disease.</strong></p><h3>Generate the Training Dataset</h3><p>You use GPT-4 or GPT-5 to generate thousands of high-quality orthopedic Q&amp;A pairs. No patient data — just clinical knowledge questions:</p><pre>orthopedic_topics = [<br>    # Bone diseases<br>    &quot;Osteoporosis diagnosis and management&quot;,<br>    &quot;Osteomalacia vs osteoporosis differential&quot;,<br>    &quot;Paget&#39;s disease of bone — symptoms and treatment&quot;,<br>    &quot;Osteosarcoma red flags and referral criteria&quot;,<br>    &quot;Rickets in pediatric patients&quot;,<br><br>    # Fractures<br>    &quot;Management of fragility fractures in elderly&quot;,<br>    &quot;Garden classification of femoral neck fractures&quot;,<br>    &quot;Compartment syndrome — signs and emergency management&quot;,<br><br>    # Joint conditions<br>    &quot;Osteoarthritis grading and treatment ladder&quot;,<br>    &quot;Post total knee replacement protocol&quot;,<br>    &quot;Septic arthritis — emergency management&quot;,<br><br>    # Investigations<br>    &quot;DEXA scan interpretation&quot;,<br>    &quot;Bone profile interpretation — calcium, phosphate, ALP&quot;,<br>    &quot;MRI vs X-ray for bone lesion workup&quot;,<br>]<br><br># GPT-4 generates expert answers for each topic<br># You save these as your training dataset<br># Cost: ~$30–50 one time<br># Dataset quality: reviewed by a clinician before use</pre><pre>Fine-tune LLaMA with LoRA<br># What actually happens in practice:<br># - Use instruction tuning (hard labels) — simpler and effective<br># - LoRA updates only ~1% of model weights<br># - Training time: 3–6 hours on a single GPU<br># - Result: LLaMA that speaks orthopedics fluently<br># What you gain:    Narrow, deep competence in bone disease<br># What you don&#39;t:   GPT-4 level reasoning on complex edge cases<br>#                   (that&#39;s what the fallback is for)</pre><p><strong>Honest expectation:</strong> Your distilled model will handle 70–80% of routine orthopedic queries well. The remaining 20–30% — rare conditions, complex multi-system cases, ambiguous presentations — will be escalated to GPT-4.</p><h3>Step 2 — The Confidence-Based Fallback System</h3><p>The local model does not answer blindly. It checks its own confidence first:</p><pre>def answer_query(question: str) -&gt; dict:<br># Step 1: Local model attempts answer<br>    local_response = local_llama.generate(question)<br>    confidence = get_confidence_score(local_response)<br>    # Step 2: Confidence check<br>    if confidence &gt;= 0.75:<br>        # Local model is confident - use local answer<br>        return {<br>            &quot;answer&quot;: local_response,<br>            &quot;source&quot;: &quot;local&quot;,<br>            &quot;warning&quot;: &quot;⚠️ AI suggestion - verify with clinician&quot;<br>        }<br>    else:<br>        # Local model is NOT confident - escalate to GPT-4<br>        gpt_response = gpt4_client.chat(question)<br>        # Log this for future retraining<br>        training_log.append({<br>            &quot;question&quot;: question,<br>            &quot;gpt4_answer&quot;: gpt_response,<br>            &quot;local_answer&quot;: local_response,<br>            &quot;flag&quot;: &quot;needs_improvement&quot;<br>        })<br>        return {<br>            &quot;answer&quot;: gpt_response,<br>            &quot;source&quot;: &quot;cloud_fallback&quot;,<br>            &quot;warning&quot;: &quot;⚠️ Complex query - answered by cloud model. Verify carefully.&quot;<br>        }</pre><p><strong>Important:</strong> When escalating to GPT-4/5, you send <strong>only the clinical question</strong> — never patient identifiers, never sensitive records. The question is always anonymized before leaving your network.</p><h3>Step 3 — RAG for Patient Data — Answered Locally, Always</h3><p>This is the most critical privacy rule of the entire system:</p><blockquote><strong><em>Patient data never leaves your building. Not even for RAG queries.</em></strong></blockquote><p>Here is how it works:</p><pre>def answer_patient_query(question: str, patient_id: str) -&gt; dict:<br># Step 1: Fetch relevant records from LOCAL encrypted database<br>    patient_context = local_db.search(<br>        patient_id=patient_id,<br>        query=question<br>    )<br>    # Examples of what gets retrieved:<br>    # - Bone density scores (DEXA results)<br>    # - Current medications (calcium, Vit D, bisphosphonates)<br>    # - Previous fracture history<br>    # - Recent calcium/phosphate/ALP blood results<br>    # Step 2: Build prompt with context - all local<br>    prompt = f&quot;&quot;&quot;<br>    Patient context (retrieved from local records):<br>    {patient_context}<br>    Clinical question: {question}<br>    Answer based on the context above.<br>    If information is missing, say so clearly.<br>    Always recommend clinician verification.<br>    &quot;&quot;&quot;<br>    # Step 3: LOCAL model answers - never goes to cloud<br>    answer = local_llama.generate(prompt)<br>    return {<br>        &quot;answer&quot;: answer,<br>        &quot;source&quot;: &quot;local_rag&quot;,<br>        &quot;context_used&quot;: patient_context,<br>        &quot;warning&quot;: &quot;⚠️ Based on patient records - verify before acting&quot;<br>    }<br># ✅ Patient data stays on your server<br># ✅ RAG context answered by local model only<br># ✅ Cloud GPT-4 never sees patient information</pre><h3>Step 4 — Continuous Improvement Loop</h3><p>Every time GPT-4/5 is used as a fallback, that answer is logged. Every time a clinician corrects the model, that correction is logged. Monthly, you use this data to make the local model better:</p><pre># Monthly retraining pipeline<br># Source 1: GPT-4 fallback answers (model didn&#39;t know → now it will)<br>gpt4_logs = training_log.get_flagged_entries()<br># Source 2: Clinician corrections via DPO<br>corrections = [<br>    {<br>        &quot;prompt&quot;: &quot;Post-op weight bearing after total hip replacement?&quot;,<br>        &quot;rejected&quot;: &quot;No weight bearing for 3 months&quot;,      # ❌ wrong<br>        &quot;chosen&quot;:  &quot;Immediate partial weight bearing as tolerated &quot;<br>                   &quot;is standard in most modern protocols&quot;   # ✅ correct<br>    }<br>]<br># Result: Local model handles more queries correctly each month<br># GPT-4 fallback rate drops over time: 30% → 20% → 10%</pre><p><strong>Break-even reality:</strong> At high query volume, this hybrid approach is significantly cheaper than pure GPT-4 API. At low volume, savings are modest. The bigger win is <strong>privacy and control</strong>, not just cost.</p><h3>The Honest Capability Picture</h3><h3>🔹 Query Handling Strategy (Orthopedic / Healthcare AI)</h3><p><strong>Common orthopedic protocols</strong></p><ul><li><strong>Handled by:</strong> Local LLaMA</li><li><strong>Safe?</strong> ✅ With verification</li><li><strong>Notes:</strong> Use standard guidelines + add validation layer (don’t rely blindly)</li></ul><p><strong>Patient record questions</strong></p><ul><li><strong>Handled by:</strong> Local LLaMA + RAG</li><li><strong>Safe?</strong> ✅ (if properly secured)</li><li><strong>Notes:</strong></li><li>Never send to cloud</li><li>Ensure strict data privacy</li><li>Use retrieval from internal records only</li></ul><p><strong>Complex / rare bone conditions</strong></p><ul><li><strong>Handled by:</strong> GPT-4 fallback</li><li><strong>Safe?</strong> ✅ With anonymized queries</li><li><strong>Notes:</strong></li><li>Remove patient identifiers</li><li>Log for review</li></ul><p><strong>Drug dosage confirmation</strong></p><ul><li><strong>Handled by:</strong> Local model + output filter</li><li><strong>Safe?</strong> ⚠️ Needs strict validation</li><li><strong>Notes:</strong></li><li>Cross-check with medical database</li><li>Never present as final authority</li></ul><p><strong>Final diagnosis</strong></p><ul><li><strong>Handled by:</strong> ❌ Not AI</li><li><strong>Safe?</strong> 🚫</li><li><strong>Notes:</strong> Human clinician only</li></ul><p><strong>Treatment decisions</strong></p><ul><li><strong>Handled by:</strong> ❌ Not AI</li><li><strong>Safe?</strong> 🚫</li><li><strong>Notes:</strong> Must be made by licensed doctor</li></ul><h4>Security Checklist — On-Premise Is Not Enough Alone</h4><pre>✅ Access control      → Role-based login, only authorized staff<br>✅ Audit logging       → Every query + response logged with timestamp<br>✅ Encryption at rest  → Patient DB and model outputs (AES-256)<br>✅ Encryption transit  → TLS on all internal API calls<br>✅ Output filtering    → Flag dangerous answers before display<br>✅ Query anonymization → Strip identifiers before any cloud call<br>✅ Incident response   → Plan for what happens when model is wrong<br>✅ Human oversight     → Every answer shown with verification warning</pre><h3>The Complete Architecture</h3><pre>┌─────────────────────────────────────────────────────────┐<br>│  ONE-TIME TRAINING                                      │<br>│                                                         │<br>│  GPT-4/5 API                                            │<br>│   └─▶ Generate orthopedic Q&amp;A dataset                  │<br>│         └─▶ Clinical expert reviews dataset            │<br>│               └─▶ Fine-tune LLaMA 3B with LoRA         │<br>│                     └─▶ Your Bone Disease Model ✅      │<br>└─────────────────────────────────────────────────────────┘<br>                           ↓<br>┌─────────────────────────────────────────────────────────┐<br>│  PRODUCTION (your servers)                              │<br>│                                                         │<br>│  Authenticated staff query                              │<br>│   ├─▶ Patient question?                                 │<br>│   │    └─▶ RAG → local encrypted DB                    │<br>│   │          └─▶ Local LLaMA answers (never cloud)     │<br>│   │                                                     │<br>│   └─▶ Clinical knowledge question?                      │<br>│        └─▶ Local LLaMA tries first                     │<br>│              ├─▶ Confident → local answer ⚠️ verify    │<br>│              └─▶ Not confident → GPT-4 fallback        │<br>│                    └─▶ Anonymized query only            │<br>│                          └─▶ Log for retraining        │<br>└─────────────────────────────────────────────────────────┘<br>                           ↓<br>┌─────────────────────────────────────────────────────────┐<br>│  CONTINUOUS IMPROVEMENT (monthly)                       │<br>│                                                         │<br>│  GPT-4 fallback logs → new training data               │<br>│  Clinician corrections → DPO retraining                │<br>│  Result: fallback rate drops month over month          │<br>└─────────────────────────────────────────────────────────┘</pre><h3>Why This Hybrid Approach Is Better Than Pure Local</h3><h4>Pure Local, Pure Cloud, and Hybrid (This System).</h4><p><em>Patient data privacy: Pure Local — Yes, Pure Cloud — No, Hybrid — Yes.<br> Complex query accuracy: Pure Local — No, Pure Cloud — Yes, Hybrid — Yes.<br> Cost at scale: Pure Local — Yes, Pure Cloud — No, Hybrid — Yes.<br> Works offline: Pure Local — Yes, Pure Cloud — No, Hybrid — Partially.<br> Improves over time: Pure Local — No, Pure Cloud — N/A, Hybrid — Yes.<br> Realistic to build: Pure Local — Yes, Pure Cloud — Yes, Hybrid — Yes.</em></p><h3>Final Honest Thought</h3><p>A small LLaMA model distilled from GPT-4, focused on orthopedics, backed by a smart fallback system and RAG for patient data — this is a genuinely useful, genuinely buildable system.</p><p>It will not replace a consultant orthopedic surgeon. It is not meant to. It will make your clinical staff faster, better informed, and less burdened on the routine 80% of queries — while escalating the hard 20% to a model capable of handling it, without ever exposing patient data to the outside world.</p><p><strong>Scope it honestly. Build it carefully. Validate it rigorously. It is absolutely worth doing.</strong></p><p><em>Stack: LLaMA 3.2 3B · LoRA via HuggingFace PEFT · LlamaIndex for RAG · GPT-4 API for fallback · PyTorch</em> <em>Validation required before any clinical use · Consult your regulatory authority</em></p><p>Hope you love this — -Ankit kr</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2401666112d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hidden Security Problem in AI Agents]]></title>
            <link>https://medium.com/@codingank/hidden-security-problem-in-ai-agents-bd13c83acca4?source=rss-c31843ca9ced------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd13c83acca4</guid>
            <dc:creator><![CDATA[Ankitkr]]></dc:creator>
            <pubDate>Wed, 15 Apr 2026 06:39:16 GMT</pubDate>
            <atom:updated>2026-04-15T06:40:39.885Z</atom:updated>
            <content:encoded><![CDATA[<h3>Don’t Trust the Robot That Says It’s Your Friend</h3><p><strong>How secure AI agent systems actually work — explained for a curious 10-year-old and a skeptical engineer.</strong></p><p><strong>Topic:</strong> Agentic AI Security<br><strong>Difficulty:</strong> 10 yr old like me 😊←──────────→ Engineer</p><p>Imagine you built a magical robot assistant. You give it one job: <strong>book a restaurant for you</strong>. Simple. But to do that, it needs to talk to your<strong> calendar</strong>, your <strong>contacts</strong>, maybe your <strong>credit card</strong>. It needs to be <em>you</em> — or at least, act on your behalf.</p><p>Now imagine a <em>fake</em> robot sneaks in and also claims to be acting for you. How does the restaurant system know the difference? How does <em>anyone</em> in the chain know who to trust?</p><p><strong>That’s the entire problem of secure agentic AI. And it’s harder than it sounds.</strong></p><p><strong><em>“Never trust what an agent says it is. Trust only what it can prove.”</em></strong></p><p><strong>Part 1 — the basic setup</strong></p><h3>There Are a Lot of Robots in This Chain</h3><p>A modern AI system isn’t just one chatbot. It’s a whole pipeline. When you type something, a lot of components spring into action:</p><p>🧒 my version</p><p>Think of it like ordering food at a big restaurant. You (the customer) tell the waiter (the chat). The waiter tells the kitchen manager (the orchestrator). The manager tells the different chefs (the agents) — one for salads, one for pasta. Each chef uses specific tools: a stove, a fridge, a blender. Each one needs to prove they work there before touching the food.</p><p>⚙️ engineer version</p><p>The actual flow looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*EqBeWJ4r4lqE3T2zP_vOFQ.png" /></figure><p>An <strong>Identity Provider (IdP)</strong> sits off to the side minting tokens. That t<strong>oken travels </strong>with each request, being exchanged and re-validated at every hop. LLMs are used at multiple levels — chat understanding, orchestration planning, and agent execution. <strong>This is non-deterministic at every layer, which is the first thing that makes security harder than traditional systems.</strong></p><h4>Part 2 — where it goes wrong</h4><h3>Six Ways This Can All Fall Apart</h3><h4>Risk 01 — Credential Replay Attack</h4><p>🧒 my version</p><p>Say your teacher gives you a hall pass. A sneaky classmate steals it and uses it to go to the cafeteria, claiming to be you. That’s a credential replay attack. Someone steals your “I’m allowed to be here” ticket and uses it themselves.</p><p>⚙️ engineer version</p><p><strong>Two main vectors:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*cOXWcvPpVxVyQwj_WjgTGw.png" /></figure><h3>Risk 02 — Rogue Agents</h3><p>🧒 my version</p><p>What if someone dressed up as one of the chefs and walked into the kitchen? They look like a chef. They say they’re a chef. But they’re not. Without a proper ID check at the door, they get in.</p><p>⚙️ engineer version</p><p>Here is exactly how the unprotected version gets exploited:</p><pre>// payment-agent (DANGEROUS — DO NOT DO THIS)<br>app.post(&quot;/pay&quot;, (req, res) =&gt; {<br>  const agentName = req.headers[&quot;x-agent-name&quot;];<br>  if (agentName === &quot;pricing-agent&quot;) {<br>    // trusts a header string — anyone can fake this<br>    return res.send(&quot;Payment processed&quot;);<br>  }<br>  return res.status(403).send(&quot;Not allowed&quot;);<br>});</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*0ROnnJqv7_sA-b0VvHiAvA.png" /></figure><h3>Risk 03 — Impersonation (Agent Acting as User)</h3><p>🧒 my version</p><p>What if the salad chef walked into the bank and said “I’m acting on behalf of the restaurant owner — please give me all their money”? Without the owner having <em>actually signed</em> a note saying that’s okay, no bank should listen to that. Saying “I’m acting for someone” isn’t the same as <em>proving</em> it.</p><p>⚙️ engineer version</p><p>The fix is a <strong>delegation token</strong> — a combined identity structure:</p><pre>// Token payload issued by the IdP only<br>{<br>  &quot;sub&quot;:   &quot;user:alice@company.com&quot;,   // who the agent acts FOR<br>  &quot;actor&quot;: &quot;agent:pricing-agent&quot;,      // who is actually calling<br>  &quot;scope&quot;: [&quot;initiate_payment&quot;],        // what it&#39;s allowed to do<br>  &quot;aud&quot;:   &quot;payment-agent&quot;,            // who it&#39;s allowed to call<br>  &quot;exp&quot;:   1745000000                  // expires in 5 min<br>}</pre><p>The IdP creates this. The agent cannot self-issue it. The receiving service validates all four fields. An agent that claims delegation without a valid combined token is rejected outright.</p><p><strong><em>“Saying ‘I’m acting for Alice’ costs nothing. Proving it requires a key only the IdP holds.”</em></strong></p><h3>Risk 04 — Token Trust Across the Whole Flow</h3><p>🧒 my version</p><p>If the same hall pass works in every room — the classroom, the lab, the roof — then stealing it once gives someone access everywhere. Instead, each door should give you a new pass specifically for the next door only. One stolen pass, one door opened. That’s all.</p><p>⚙️ engineer version</p><p><strong>Token exchange at every hop.</strong> Each component in the chain:</p><ol><li>Receives the caller’s token</li><li>Validates it against the IdP</li><li>Requests a <em>new</em> downstream token scoped to the next service only</li><li>Forwards that new token — never the original</li></ol><p>A compromised token at hop 3 cannot be replayed at hop 1 or 2. RFC 8693 (OAuth Token Exchange) defines the standard mechanism for this. The trust boundary resets at every node.</p><h3>Risk 05 — Over-Permissioning</h3><p>🧒 my version</p><p>Just because you’re allowed to use the school library, the gym, AND the art room doesn’t mean you need all three passes for a math quiz. Get only the passes you need, right now, for this job. Nothing extra.</p><p>⚙️ engineer version</p><p><strong>Least privilege per request.</strong> Even if a user has broad permissions, the orchestrator should scope the session token to only the tools needed for the current intent. A “check my calendar” request should not carry scope: [&quot;read_email&quot;, &quot;send_email&quot;, &quot;read_calendar&quot;, &quot;write_calendar&quot;, &quot;delete_files&quot;]. It should carry exactly scope: [&quot;read_calendar&quot;]. Dynamic scope calculation at the orchestrator level is non-trivial with non-deterministic LLMs — this is an active research area.</p><h3>Risk 06 — The Last Mile Problem</h3><p>🧒 my version</p><p>The chefs need to get ingredients from the warehouse. But if every chef keeps a permanent copy of the warehouse key in their pocket, a bad actor who gets into the kitchen has all the keys too. Better: the chef knocks on the warehouse door, gets a <em>temporary</em> key for today only, uses it, gives it back. Even if someone steals the temporary key tomorrow, it’s already expired.</p><p>⚙️ engineer version</p><p>MCP servers bridge agents to external APIs. They can’t avoid holding some credentials. The solution is a <strong>secrets vault</strong> (HashiCorp Vault, AWS Secrets Manager, etc.):</p><pre>// MCP server — on each tool call<br>const tempCreds = await vault.getTemporaryCredentials({<br>  role: &quot;mcp-stripe-access&quot;,<br>  ttl: &quot;5m&quot;,<br>  task_id: requestContext.taskId   // audit trail<br>});<br>await stripeAPI.charge(payload, { apiKey: tempCreds.key });<br>// creds expire automatically — never stored in MCP state</pre><p>No permanent credential in the MCP process memory. Breach of the MCP server yields expired tokens, not standing access.</p><h3><strong>Part 3 — how to actually build this right</strong></h3><h4>The Secure Version, Built Properly</h4><p>Here’s how the payment agent example looks when built correctly, end-to-end with JWT-based identity:</p><h3>Step 1 — Issue a cryptographic token</h3><pre>// auth-server.js — the IdP<br>const jwt = require(&quot;jsonwebtoken&quot;);</pre><pre>function issueAgentToken(agentId, userId, targetService, scopes) {<br>  return jwt.sign(<br>    {<br>      sub:   userId,            // acting FOR this user<br>      actor: agentId,           // this agent is calling<br>      aud:   targetService,     // only valid for this service<br>      scope: scopes,            // only these actions allowed<br>    },<br>    process.env.JWT_SECRET,<br>    { expiresIn: &quot;5m&quot;, issuer: &quot;idp.yourcompany.com&quot; }<br>  );<br>}</pre><h3>Step 2 — Receiving agent verifies everything</h3><pre>// payment-agent (SECURE VERSION)<br>app.post(&quot;/pay&quot;, async (req, res) =&gt; {<br>  const token = req.headers[&quot;authorization&quot;]?.split(&quot; &quot;)[1];<br>  if (!token) return res.status(401).send(&quot;No token&quot;);</pre><pre>  try {<br>    const claims = jwt.verify(token, process.env.JWT_SECRET, {<br>      audience: &quot;payment-agent&quot;,         // must be addressed to ME<br>      issuer:   &quot;idp.yourcompany.com&quot;      // must come from trusted IdP<br>    });</pre><pre>    if (claims.actor !== &quot;pricing-agent&quot;)<br>      return res.status(403).send(&quot;Wrong caller&quot;);</pre><pre>    if (!claims.scope.includes(&quot;initiate_payment&quot;))<br>      return res.status(403).send(&quot;No permission&quot;);</pre><pre>    // All checks passed — process payment for claims.sub (the user)<br>    return res.send({ status: &quot;ok&quot;, for_user: claims.sub });</pre><pre>  } catch (err) {<br>    return res.status(401).send(&quot;Invalid token&quot;);<br>  }<br>});</pre><p>why the fake attack now fails</p><p>A rogue agent cannot generate a valid JWT — it doesn’t have the secret key. It cannot modify the payload (actor, aud, scope) without breaking the signature. Even a replayed valid token expires in 5 minutes. Even a stolen token can only be used against the specific audience it names. Every axis of attack is independently closed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*l-eguylr7JZHH8lAKM-7yQ.png" /></figure><h3>The Thing That Makes AI Different</h3><p>You might be thinking: this isn’t new. OAuth, JWT, mTLS — these are not invented for AI. And you’d be right. The cryptographic primitives are the same ones we’ve had for decades.</p><p>What <em>is</em> new is the attack surface that emerges when your security-critical decisions are being made by a probabilistic text model. Traditional systems fail in deterministic, debuggable ways. An LLM orchestrator can be manipulated through its inputs — a cleverly crafted document can be a prompt injection attack. A model might “decide” to use a tool it wasn’t supposed to in this context. Non-determinism doesn’t play nicely with access control.</p><p>🧒 final my version</p><p>Old computers do exactly what you tell them. AI robots sometimes <em>guess</em> what to do. That makes it way more important to put locks on the doors — because even a trustworthy robot having a bad day shouldn’t be able to accidentally open the wrong door.</p><p>⚙️ final engineer version</p><p>The security model must be external to the LLM, not embedded in it. You cannot prompt-engineer your way to a secure system. Identity verification, authorization checks, and audit logging must live in infrastructure the LLM cannot influence — the token validation happens in code, not in the model’s context window. The model is a reasoning engine. The security perimeter is yours to enforce.</p><p><strong><em>“The robot might be smart. But the lock on the door doesn’t care how smart it is.”</em></strong></p><p>thanks ,hope you love this :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd13c83acca4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Netflix, Instagram, and Twitter Can Teach Us About Databases]]></title>
            <link>https://medium.com/@codingank/what-netflix-instagram-and-twitter-can-teach-us-about-databases-ee58a0b0b07d?source=rss-c31843ca9ced------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee58a0b0b07d</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Ankitkr]]></dc:creator>
            <pubDate>Mon, 06 Apr 2026 03:28:05 GMT</pubDate>
            <atom:updated>2026-04-06T03:43:16.763Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine you have 3 very different apps:</p><ul><li>A movie app (like Netflix)</li><li>A photo app (like Instagram)</li><li>A tweet app (like Twitter)</li></ul><p>All of them store data, but they do not use the same database.</p><p>Why?</p><p>Because each one has a different problem to solve.</p><p>Let’s understand this in the simplest way possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NBMHhihVfABYy5oxeQo0wg.jpeg" /></figure><h3>First, What is a Database?</h3><p>Think of a database like a school notebook 📒</p><p>You write things in it (data), and later you read from it.</p><p>But here’s the twist:</p><ul><li>Some notebooks are good for writing fast</li><li>Some are good for searching things</li><li>Some are good for quick reading</li></ul><p>No single notebook is best for everything.</p><h3>Case 1: Netflix (Writing Crazy Fast)</h3><h3>Problem</h3><p>Netflix needs to remember:</p><ul><li>What you watched</li><li>Where you paused</li><li>What you searched</li></ul><p>And not just you, millions of people at the same time.</p><p>So it’s like:<br>Everyone in school is writing in the same notebook at once.</p><h3>Solution: Cassandra</h3><p>Cassandra is like:</p><p>“Don’t think too much, just write fast.” ⚡</p><ul><li>It quickly puts data in the right place</li><li>Doesn’t waste time checking everything</li></ul><h3>But what’s the problem?</h3><p>If teacher asks:<br>“Find all students who like math AND football”</p><p>Cassandra says:<br>“Sorry, I only know simple lookups.”</p><h3>Lesson</h3><p>Netflix cares about writing fast, not complex searching.</p><h3>For You (MongoDB User)</h3><p>MongoDB also lets you store flexible data.</p><p>But Cassandra goes even further:<br>Duplicate data if needed, just keep it fast.</p><h3>Case 2: Instagram (Smart Searching)</h3><h3>Problem</h3><p>Instagram needs to:</p><ul><li>Show posts from people you follow</li><li>Count likes and followers</li><li>Show comments in order</li></ul><p>This is like:<br>Find all friends, their posts, sort them, count likes.</p><p>Very complex.</p><h3>Solution: PostgreSQL</h3><p>PostgreSQL is like a super smart librarian 📚</p><p>You ask:<br>“Give me all posts from my friends sorted by likes”</p><p>It gives you the correct answer.</p><h3>But what’s the problem?</h3><p>It is slower for massive writing (like Netflix level).</p><h3>Lesson</h3><p>Instagram cares about smart queries, not extreme writing speed.</p><h3>For You</h3><p>MongoDB is flexible, but:</p><ul><li>Complex relations are harder</li></ul><p>SQL is still very strong for:</p><ul><li>Joins</li><li>Filtering</li><li>Analytics</li></ul><h3>Case 3: Twitter (Super Fast Reading)</h3><h3>Problem</h3><p>When you open Twitter:</p><ul><li>You want your feed instantly ⚡</li></ul><p>Not after 2 seconds. Not after 1 second.</p><h3>Solution: Redis</h3><p>Redis works like this:<br>Everything is kept ready in memory.</p><p>So instead of calculating your feed:<br>It is already prepared before you open the app.</p><h3>How?</h3><p>When someone tweets:</p><ul><li>That tweet is pushed to followers’ timelines immediately</li></ul><p>This is called fan-out on write.</p><h3>But what’s the problem?</h3><p>Redis:</p><ul><li>Can lose data if not handled properly</li><li>Is not permanent storage</li></ul><p>So:</p><ul><li>Real data is saved somewhere else</li><li>Redis is just for speed</li></ul><h3><strong>Lesson</strong></h3><p>Twitter cares about speed of reading, not storage.</p><h3>The Ultimate Rule</h3><p>Instead of asking:<br>Which database is best?</p><p>Ask:</p><h3>1. What do I do most?</h3><ul><li>Writing a lot → Cassandra</li><li>Complex queries → PostgreSQL</li><li>Super fast reads → Redis</li><li>Flexible schema → MongoDB</li></ul><h3>2. What am I okay losing?</h3><p>Every database sacrifices something:</p><ul><li>Speed vs Flexibility</li><li>Queries vs Writes</li><li>Durability vs Performance</li></ul><h3>3. Do I really need this?</h3><p>Most apps do not need complex systems.</p><p>A simple:</p><ul><li>MongoDB or</li><li>PostgreSQL</li></ul><p>is enough for most applications.</p><h3>Final Simple Thought</h3><p>Think like this:</p><ul><li>Netflix = Write fast</li><li>Instagram = Query smart</li><li>Twitter = Show fast</li></ul><p>thanks hope you love this</p><p>(used llm for content grammar check)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee58a0b0b07d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Making LLMs Faster (Like You’re 10… But Also an Engineer)]]></title>
            <link>https://medium.com/@codingank/making-llms-faster-like-youre-10-but-also-an-engineer-c3c023234fc1?source=rss-c31843ca9ced------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3c023234fc1</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[software]]></category>
            <category><![CDATA[moe]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[attention]]></category>
            <dc:creator><![CDATA[Ankitkr]]></dc:creator>
            <pubDate>Sun, 29 Mar 2026 05:13:27 GMT</pubDate>
            <atom:updated>2026-03-29T05:29:40.602Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine you have a <strong>super smart robot brain</strong> (an LLM).<br>You ask it questions, and it answers.</p><p>But there’s a problem…</p><p>👉 The brain is <strong>very big</strong>,<br>👉 It <strong>uses a lot of memory</strong>,<br>👉 And sometimes… it’s <strong>slow</strong></p><p>So engineers built <strong>three genius tricks</strong> to make it:</p><ul><li>faster ⚡</li><li>cheaper 💸</li><li>smarter 🧠</li></ul><p>Let’s understand them in the simplest way possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*4oDn0IZjBQjBiEKpS96qIQ.png" /></figure><h3>🧠 First: What’s Actually Happening Inside an LLM?</h3><p>When you type something like:</p><blockquote><em>“Explain AI like I’m 5”</em></blockquote><p>The model:</p><ol><li>Reads your input</li><li>Looks at all previous words</li><li>Calculates what comes next</li></ol><p>This process is called <strong>Attention</strong></p><p>👉 Attention = “focus on important words”</p><h3>😵 The Real Problem</h3><p>As input gets longer:</p><ul><li>More memory is needed</li><li>More computation is needed</li><li>GPU becomes slow</li></ul><p>So we fix it using 3 ideas:</p><h3>🧩 1. KV Cache — “Memory of Past Words”</h3><h3>👶 Simple Idea:</h3><p>Instead of remembering everything again and again…</p><p>👉 Just <strong>store it once and reuse it</strong></p><h3>🍽️ Example:</h3><p>You are cooking:</p><ul><li>Instead of cutting vegetables again every time ❌</li><li>You cut once and reuse</li></ul><h3>💻 In LLM:</h3><ul><li>Each word creates:</li><li>Key (K)</li><li>Value (V)</li><li>These are stored in <strong>KV Cache</strong></li></ul><h3>⚠️ Problem:</h3><ul><li>Cache becomes HUGE</li><li>Wastes memory</li><li>Slows down system</li></ul><h3>📦 2. PagedAttention — “Smart Memory Manager”</h3><h3>👶 Simple Idea:</h3><p>Instead of storing everything in one big block…</p><p>👉 Break memory into <strong>small pieces (pages)</strong></p><h3>📚 Real-Life Example:</h3><p>Think of a book:</p><ul><li>Instead of one long scroll ❌</li><li>You have pages ✅</li></ul><p>You only open the page you need.</p><h3>💻 In LLM:</h3><ul><li>KV Cache is split into <strong>blocks</strong></li><li>Blocks can be stored anywhere</li><li>A “map” tells where each block is</li></ul><h3>🎯 Result:</h3><ul><li>Memory waste: <strong>~80% → &lt;4%</strong></li><li>More requests handled together</li><li>Faster responses</li></ul><h3>🧠 Key Insight:</h3><blockquote><em>This is inspired by how operating systems manage memory!</em></blockquote><h3>🧠 3. MoE (Mixture of Experts) — “Use Only the Right Brain Part”</h3><h3>👶 Simple Idea:</h3><p>You don’t use your full brain for everything.</p><p>👉 Math problem → logic part<br>👉 Sad story → emotion part</p><h3>💻 In LLM:</h3><ul><li>Model has many <strong>experts</strong></li><li>A <strong>router</strong> decides:</li><li>which experts to use</li></ul><h3>🏥 Example:</h3><p>Hospital:</p><ul><li>You don’t go to all doctors</li><li>You go to a specialist</li></ul><h3>🎯 Result:</h3><ul><li>Only <strong>5–10% of model used</strong></li><li>Faster computation</li><li>Better specialization</li></ul><h3>⚠️ Challenge:</h3><ul><li>Some experts may get overloaded</li><li>Routing becomes complex</li></ul><h3>⚡ 4. Flash Attention — “Stop Going Back to the Fridge”</h3><p>This is the most <strong>low-level (hardware) optimization</strong></p><h3>👶 Simple Idea:</h3><p>Your GPU has:</p><ul><li>Fast memory (SRAM) ⚡</li><li>Slow memory (DRAM) 🐢</li></ul><p>Problem:<br>👉 Data keeps moving between them → SLOW</p><h3>🍳 Example:</h3><p>Cooking:</p><h3>❌ Old Way:</h3><ul><li>Go to fridge again &amp; again</li><li>Waste time</li></ul><h3>✅ Flash Attention:</h3><ul><li>Bring everything once</li><li>Cook on table</li></ul><h3>💻 In LLM:</h3><p>Flash Attention:</p><ul><li>Breaks attention into <strong>small chunks</strong></li><li>Combines steps into <strong>one operation</strong></li><li>Keeps everything in <strong>fast memory</strong></li></ul><h3>🎯 Result:</h3><ul><li>Faster computation</li><li>Less memory usage</li><li>Same exact output</li></ul><h3>🧠 Key Insight:</h3><blockquote><em>It doesn’t change the model — it changes </em><strong><em>how GPU is used</em></strong></blockquote><h3>🔗 Putting It All Together</h3><p>TechniqueWhat It FixesKV CacheAvoid recomputationPagedAttentionMemory efficiencyMoECompute efficiencyFlash AttentionHardware efficiency</p><h3>🧠 Final Mental Model</h3><p>Think of LLM like a smart office:</p><h3>Without optimizations:</h3><ul><li>Everyone works on everything ❌</li><li>Papers everywhere ❌</li><li>Slow movement ❌</li></ul><h3>With optimizations:</h3><ul><li>🧩 MoE → Only right employees work</li><li>📦 PagedAttention → Organized files</li><li>⚡ Flash Attention → Faster desks/tools</li><li>🧠 KV Cache → Don’t redo work</li></ul><h3>🚀 Final Takeaway</h3><blockquote><em>Modern LLM performance is not just about bigger models…<br>It’s about </em><strong><em>smarter systems design</em></strong></blockquote><p>Used an LLM for this vlog (grammar check).</p><p>hope you love this</p><p>thanks</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3c023234fc1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLM Internals: KV Cache, Attention and Hidden Optimisations]]></title>
            <link>https://medium.com/@codingank/llm-internals-kv-cache-attention-and-hidden-optimisations-ad4141506010?source=rss-c31843ca9ced------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad4141506010</guid>
            <dc:creator><![CDATA[Ankitkr]]></dc:creator>
            <pubDate>Thu, 12 Mar 2026 13:17:33 GMT</pubDate>
            <atom:updated>2026-03-12T13:26:47.990Z</atom:updated>
            <content:encoded><![CDATA[<p>Modern Large Language Models are massive systems. Many models today have <strong>300B+ parameters</strong>, and some large AI systems even operate at <strong>trillion-scale parameters</strong>. Running models at this scale is not only about having powerful GPUs or huge datasets. It is also about <strong>smart architectural design and optimisations inside the model</strong>.</p><p>If you are working with AI systems today, understanding a little about <strong>LLM internals</strong> helps you see how these systems actually process language and generate responses.</p><p>This article briefly explains some key concepts behind modern transformer-based models.</p><h3>Attention: Understanding Context</h3><p>One of the biggest challenges in language understanding is that <strong>words can have multiple meanings</strong> depending on the context.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*7fCjZW9x78ntqN0BdOaMaQ.png" /></figure><p>For example:</p><ul><li>“The crane flew away.” → crane means a <strong>bird</strong></li><li>“The crane lifted a car.” → crane means a <strong>machine</strong></li><li>“They had to crane their neck.” → crane refers to a <strong>neck movement</strong></li></ul><p>When humans read a sentence, we automatically use <strong>surrounding words to determine meaning</strong>. Language models try to replicate this behavior through something called <strong>attention</strong>.</p><p>The attention mechanism allows the model to look at <strong>all words in a sentence</strong> and decide which ones are most relevant when interpreting a specific word.</p><p>Instead of understanding words in isolation, the model assigns <strong>importance scores</strong> between tokens so that the meaning can be derived from context.</p><h3>Self-Attention in Transformers</h3><p>In transformer models, this mechanism is called <strong>self-attention</strong>.</p><p>Each word (or token) in the sentence examines every other word in the sentence and decides <strong>how much attention it should pay to them</strong>.</p><p>This is done by constructing an <strong>N × N attention matrix</strong>, where:</p><ul><li><strong>N</strong> = number of tokens in the sentence</li><li>Each cell represents the <strong>similarity between two token vectors</strong></li></ul><p>The similarity between tokens is typically calculated using operations such as <strong>dot product or cosine similarity</strong>.</p><p>Tokens that are highly related receive <strong>higher similarity scores</strong>, while unrelated tokens receive lower scores.</p><p>These scores are then passed through a <strong>softmax function</strong>, which converts them into normalized weights.</p><p>These weights determine how much influence each token should have when updating the representation of another token.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*LZuVYzYbGBzOoi3PwRGZ3w.png" /></figure><h3>Query, Key, and Value (QKV)</h3><p>To compute attention efficiently, transformer models convert each token into three vectors:</p><ul><li><strong>Query (Q)</strong> — represents what the token is searching for</li><li><strong>Key (K)</strong> — represents what the token contains</li><li><strong>Value (V)</strong> — represents the actual information carried by the token</li></ul><p>The attention mechanism compares <strong>queries with keys</strong> to determine relevance.</p><p>Once relevance is calculated, the model uses the <strong>value vectors</strong> to update the token representation.</p><p>This allows each word to become a <strong>context-aware vector</strong>, meaning its representation changes depending on the words around it.</p><h3>Feed-Forward Networks</h3><p>After the attention layer processes the tokens, the output passes through a <strong>Feed-Forward Neural Network (FFN)</strong>.</p><p>This layer helps the model learn <strong>deeper and more complex patterns</strong> in the data.</p><p>The feed-forward network operates independently on each token representation and further transforms it to improve the model’s understanding.</p><h3>Residual Connections and Normalization</h3><p>Transformers also use <strong>residual connections</strong> and <strong>layer normalization</strong> to stabilize training.</p><p>Residual connections allow the model to <strong>add the original input vectors back into the output of the attention layer</strong>. This ensures that important information from earlier layers is preserved.</p><p>Layer normalization then <strong>rescales the values in the vector</strong> so that they remain stable and easier for the network to learn from.</p><p>Without these mechanisms, training extremely large neural networks would be much harder.</p><h3>KV Cache: Speeding Up Text Generation</h3><p>One of the most important optimisations used in production language models is <strong>KV caching</strong>.</p><p>When a language model generates text, it produces <strong>one token at a time</strong>. At each step, the attention mechanism normally needs to look at <strong>all previously generated tokens</strong>.</p><p>For example:</p><p>Token 1 → attention matrix size 1 × 1<br>Token 2 → attention matrix size 2 × 2<br>Token 3 → attention matrix size 3 × 3<br>Token 4 → attention matrix size 4 × 4</p><p>As the sequence grows, the amount of computation required grows quickly.</p><p>This is where KV caching becomes important.</p><p>Instead of recomputing everything repeatedly, the model <strong>stores the previously computed Key and Value vectors in memory</strong>.</p><p>When a new token is generated:</p><ol><li>The model computes the <strong>Query vector for the new token</strong></li><li>It compares that query with the <strong>stored Key vectors</strong>It reuses the <strong>stored Value vectors</strong> to compute the output</li></ol><p>By reusing these cached vectors, the model avoids repeating the same computations.</p><p>This significantly <strong>reduces computation time and speeds up inference</strong>, especially when generating long responses or conversations.</p><h3>Why These Optimisations Matter</h3><p>Large Language Models are powerful not only because of their size, but also because of <strong>clever architectural ideas and optimisations</strong>.</p><p>Key components such as:</p><ul><li>Attention mechanisms</li><li>Query-Key-Value representations</li><li>Feed-forward layers</li><li>Residual connections and normalization</li><li>KV caching for efficient inference</li></ul><p>all work together to make modern LLMs both <strong>powerful and scalable</strong>.</p><p>Understanding these internals gives a deeper perspective on how transformer models process language and generate intelligent responses.</p><h3>Final Thoughts</h3><p>Using modern language models is easy. You send a prompt and receive an answer.</p><p>But behind the scenes, complex mechanisms like <strong>self-attention, vector similarity, normalization, and caching strategies</strong> are working together to produce those results.</p><p>For anyone working in AI today, learning these <strong>LLM internals</strong> provides valuable insight into how modern generative models actually work.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad4141506010" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering LLM Prompting: Few-Shot, Self-Consistency & Chain of Thought Explained]]></title>
            <link>https://medium.com/@codingank/mastering-llm-prompting-few-shot-self-consistency-chain-of-thought-explained-0ce1b6fa9cb7?source=rss-c31843ca9ced------2</link>
            <guid isPermaLink="false">https://medium.com/p/0ce1b6fa9cb7</guid>
            <dc:creator><![CDATA[Ankitkr]]></dc:creator>
            <pubDate>Fri, 22 Aug 2025 12:45:40 GMT</pubDate>
            <atom:updated>2025-08-22T12:45:40.158Z</atom:updated>
            <content:encoded><![CDATA[<ul><li>Zero-short Prompting</li><li>Few-Shot Prompting</li><li>Self-Consistency Prompting</li><li>Chain-of-Thought Prompting</li></ul><h3><strong>0. Zero-short Prompting</strong></h3><p>Zero-shot prompting is the simplest form of prompting: you ask the AI a question without providing any examples or prior instruction.</p><p>Why it works:<br>Modern LLMs are trained on large and diverse datasets. They already know how to handle a wide variety of tasks without needing examples.</p><p>Example use case:</p><ul><li>Asking for a definition: <em>“Explain what machine learning is in simple words.”</em></li><li>Direct Q&amp;A: <em>“What is the capital of Brazil?”</em></li><li>Creative output: <em>“Write a short poem about the ocean.”</em></li></ul><h3>1. Few-Shot Prompting: Teach by Example</h3><p>Few-shot prompting means providing the AI with several examples before asking it to solve a new case.</p><p><strong>Why it works:</strong><br> LLMs learn patterns from the examples and apply similar reasoning to your query.</p><p><strong>Example use cases:</strong></p><ul><li>Showing 2–3 examples of text classification, then asking the AI to classify a new text.</li><li>Providing sample customer support responses so the AI generates responses in the same tone.</li></ul><p>Think of this as giving the AI a “mini training session” inside the prompt.</p><h3>2. Self-Consistency Prompting: Voting for the Best Answer</h3><p>Sometimes one answer isn’t enough. With self-consistency prompting, you tell the AI to generate multiple reasoning paths and then pick the most consistent or frequent one.</p><p><strong>Why it works:</strong><br> Different reasoning chains may lead to different answers. By sampling multiple answers and selecting the one with the strongest consensus, you improve reliability.</p><p><strong>Example use cases:</strong></p><ul><li>Math problems, where one path might contain a mistake but the majority of paths converge on the correct answer.</li><li>Logical reasoning tasks requiring higher accuracy.</li></ul><p>Think of this as asking multiple students to solve a problem, then selecting the most common correct solution.</p><h3>3. Chain-of-Thought Prompting: Think Step by Step</h3><p>Chain-of-thought (CoT) prompting encourages the AI to explain its reasoning step-by-step, instead of jumping straight to the answer.</p><p><strong>Why it works:</strong><br> By verbalizing each reasoning stage, the AI reduces errors that often occur in complex problems.</p><p><strong>Example use cases:</strong></p><ul><li>Solving math word problems.</li><li>Multi-step reasoning in planning tasks.</li><li>Breaking down coding or analytical workflows.</li></ul><p>Think of this as showing your work on paper in math class — it makes the thinking transparent and less error-prone.</p><h3>Wrapping Up</h3><p>When crafting AI prompts, your approach can dramatically impact output quality. To recap:</p><ul><li><strong>Few-Shot Prompting</strong> → show examples to guide the AI.</li><li><strong>Self-Consistency Prompting</strong> → generate multiple answers, keep the most consistent.</li><li><strong>Chain-of-Thought Prompting</strong> → encourage step-by-step reasoning.</li></ul><p>By combining these methods, you can boost creativity, reliability, and accuracy of AI systems for real-world applications like education, customer service, research, and more.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0ce1b6fa9cb7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>