<?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 Thejandeera Sandeepana on Medium]]></title>
        <description><![CDATA[Stories by Thejandeera Sandeepana on Medium]]></description>
        <link>https://medium.com/@thejandeera?source=rss-a4e3258d6c51------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*2GlJVStSlq7aBVc2</url>
            <title>Stories by Thejandeera Sandeepana on Medium</title>
            <link>https://medium.com/@thejandeera?source=rss-a4e3258d6c51------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 11:41:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@thejandeera/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The Million Token Lie: Why Your AI Still Forgets You Tomorrow (And What to Do About It)]]></title>
            <link>https://thejandeera.medium.com/the-million-token-lie-why-your-ai-still-forgets-you-tomorrow-and-what-to-do-about-it-b1c7bffbf3f9?source=rss-a4e3258d6c51------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1c7bffbf3f9</guid>
            <dc:creator><![CDATA[Thejandeera Sandeepana]]></dc:creator>
            <pubDate>Sat, 12 Sep 2026 11:55:10 GMT</pubDate>
            <atom:updated>2026-09-12T11:56:48.476Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Cover image" src="https://cdn-images-1.medium.com/max/1024/1*QK4KmXa_ra6IZeSyhWhSAw.png" /></figure><p>Let’s be honest😊 . We’ve all been completely seduced by the marketing spec sheets.</p><p>Every few months, some major AI lab rolls out a new model card with a context window that would have sounded like absolute science fiction just two years ago. A million tokens. Two million. Ten million!</p><p>The sales pitch writes itself<strong>: <em>“Stop worrying about retrieval! Stop chunking your files! Just dump your entire 500 page contract, your multi gigabyte codebase and your grandmother’s secret recipes directly into the prompt and let the AI sort it out!”</em></strong></p><p>It sounds amazing. It also happens to be a massive and expensive lie.</p><p>Because here is the cold, hard reality of production grade AI, A massive context window is working memory for a single inference call, not persistent memory across sessions. The moment your chat session ends or you click that “New Chat” button, the model suffers a complete, radical case of amnesia. If you ask it the exact same question tomorrow, it starts from absolute zero.</p><p>As the AI ecosystem matures, we are hitting a massive architectural wall. The secret that model providers don’t want to put on their landing pages is that context windows got huge, but your agents are still forgetting everything.</p><p>In this article, we’re going to dissect exactly why the “brute force” context approach is failing, what AI memory actually is and why the future of AI isn’t about building a bigger context window . It’s about building a smarter memory stack 😁 .</p><h3>1. The Context Window Arms Race</h3><p>If you’ve been following the AI space, the token count arms race feels like the classic megapixel wars of digital cameras.</p><p>We started in 2022 with a modest 4000 tokens on GPT 3. Then we celebrated 32K, then 128K. Now in 2026, we have a standard floor of 256K to 1M tokens across OpenAI’s models, Anthropic’s Claude and Google’s Gemini series. In the open source world, the Apache 2.0 licensed DeepSeek V4 Pro and Flash have pushed 1 million token boundaries into the mainstream. Gemini 3.1 Pro currently leads the pack with a massive 2 million token window as standard.</p><p>But what does a “million tokens” actually look like?</p><pre>┌────────────────────────────────┬─────────────────────────┬────────────────────┐<br>│ Asset                          │ Approximate Token Count │ Fits in 1M Tokens? │<br>├────────────────────────────────┼─────────────────────────┼────────────────────┤<br>│ Tolstoy’s War and Peace        │ ~580,000                │ Yes                │<br>│ The King James Bible           │ ~1,050,000              │ Just barely        │<br>│ React 19 Source Tree           │ ~1,100,000              │ No                 │<br>│ S&amp;P 500 Top 50 SEC 10-K Corpus │ ~2,400,000              │ No                 │<br>└────────────────────────────────┴─────────────────────────┴────────────────────┘</pre><h3>2. Context Is Not Memory (Ephemeral vs Persistent)</h3><p>The fundamental misunderstanding in AI engineering today is equating context with memory. They are entirely different cognitive concepts.</p><p>Think of a context window as a physical desk. Everything the model can “see” at any one second is laid out on this desk. your instructions, the chat history and the files you pasted. The model scans the desk, writes a response and then gone. A giant leaf blower clears the desk the moment you end the session.</p><figure><img alt="The content desk" src="https://cdn-images-1.medium.com/max/1024/1*IYccdTEUIwrqym6ReRaQSQ.png" /></figure><p>Working memory is ephemeral, persistent memory is stateful.</p><p>True AI memory is a non volatile, read write state engine that persists outside the context window. It writes to a database, reasons over what to keep and fetches only the relevant pieces across separate sessions.</p><p>If your AI system relies entirely on a massive context window, you are paying the “Stateless Tax”. Every single turn, you are paying to reload thousands of tokens of stable instructions, tool definitions and historical context just so the model doesn’t forget who it is talking to.</p><h3>The Distributed Systems Connection</h3><p>In distributed systems engineering keeping independent, unreliable nodes in sync requires a replicated state machine. In distributed databases we don’t just dump all historical transaction logs across the network on every single query and re run Paxos/Raft from scratch to agree on what’s true. That would be a complete, latency murdering disaster. Instead we maintain a persistent, validated state and use Multi Paxos or Raft log commitment to write updates incrementally.</p><p>Yet, in AI architecture today, we are doing exactly what distributed systems engineers spent decades trying to avoid. We are treating a massive context window as a stateless dump. When you run an agent session, every single turn, you are naively re loading thousands of tokens of stable instructions, tool schemas and chat history, expecting the LLM to “re agree” on who it is and what it is doing. That is the stateless tax.</p><h3>3. Why Bigger Context Isn’t Better</h3><p>So why don’t we just make the desk infinite? What’s the harm in dumping a million tokens into every single query?</p><p>Well, unless you have unlimited venture capital funding or a money printer hidden in your basement😒 , four massive problems make “brute force” context loading a disaster in production:</p><h3>A. The Quadratic VRAM Nightmare</h3><p>Under the hood of the standard Transformer model lies the Self Attention mechanism. In simple terms, every single token in a prompt must “look” at every other token to understand relationships. This means computation and GPU memory scale quadratically with prompt length.</p><p>If you double your context window from 500K to 1M tokens, your attention computation doesn’t double it quadruples. Storing the intermediate attention calculations (the KV cache) for a million tokens can swallow over 25+ GB of precious VRAM. That is more than the entire physical memory of most consumer graphics cards and a massive chunk of an enterprise data center GPU.</p><h3>B. “Lost in the Middle” and “Context Rot”</h3><p>Just because a model can accept a million tokens doesn’t mean it’s actually paying attention to them.</p><p>In 2023, Stanford and UC Berkeley researchers dropped a bombshell paper: <em>“Lost in the Middle: How Language Models Use Long Contexts.”</em> They proved that LLMs are highly biased toward the edges of their context window. They remember the beginning (primacy bias) and the end (recency bias) beautifully. But anything buried in the middle of a long prompt? It gets quietly ignored.</p><p>Chroma Research’s 2025 study of 18 frontier models (including GPT 4.1, Claude 4 and Gemini 2.5) confirmed this U shaped attention curve still exists. While edge information scored 85–95% accuracy, accuracy for information placed in the middle sagged down to 76–82%. On more complex reasoning tasks, accuracy fell off a cliff, dropping by 20–50%.</p><p>Even more embarrassing: on the NoLiMa benchmark, which tests models on reading without relying on surface level keyword matching, 11 out of 12 tested models fell below half their short context baseline by just 32K tokens.</p><p>Imagine pasting a 200 page contract into Claude and asking about the termination clause. If that clause is on page 112, right in the dead center of the context, the model will confidently hallucinate an answer. It’s not lying. its attention is just structurally incapable of holding onto the middle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1S-NQvMHdWw7L-K5BAheKg.png" /></figure><h3>C. Slower Inference &amp; Latency Murder</h3><p>Have you ever tried asking a model a question when its context is stuffed with 500000 tokens? You can go brew a cup of coffee, walk the dog and contemplate the meaning of existence before the first token appears on your screen. A million token inference can easily take 30 to 60 seconds of “think time”, destroying the user experience of interactive voice or chat assistants.</p><h3>D. The Linear Wallet Bleed</h3><p>In 2026, input tokens still cost real money. Let’s say you are running a long running agent loop that takes 50 turns to solve a complex coding task. If you naively pass the full accumulated history on every turn, you will watch your API bill explode.</p><p>A famous cautionary tale in the industry is Uber, which reportedly burned through its entire 2026 token budget in just 13 weeks because they were naively stuffing massive historical contexts into every single loop of their internal developer agents. Let’s avoid being the person who has to explain that to the CFO 😂 .</p><h3>4. What Is AI Memory?</h3><p>So, if we can’t just throw tokens at the problem, what is the alternative? We have to look to human biology. Human brains don’t store every single frame of our lives in raw video format. We extract, compress, categorize and recall.</p><p>The agent ecosystem in 2026 has converged on a beautiful 3 tier memory taxonomy that mirrors decades of cognitive science research:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MhJM3OXlo1DCkM_lTbThGw.png" /></figure><ol><li>Working Memory (In Context): The active scratchpad. The immediate conversation turn, the active task variables and the prompt. It lives inside the model’s prompt and is wiped on session end.</li><li>Episodic Memory (The Diary): A sequential record of past experiences. It remembers when a billing dispute happened in February, what the user’s immediate frustration was, and how it was resolved.</li><li>Semantic Memory (The Encyclopedia): Atemporal, structured facts. This is where we store user preferences (ex : <em>“vegetarian”</em> or <em>“prefers React over Vue”</em>) and stable domain knowledge.</li><li>Procedural Memory (The Skills): The “how to” library. This encodes learned workflows and tool call sequences. Instead of putting a 10000 word instruction manual in every system prompt, the agent dynamically retrieves only the relevant “skill” when a specific task is triggered.</li></ol><h3>5. How AI Memory Works</h3><p>To build this cognitive engine, we don’t use magic. We use software engineering. The primary production pattern is the Retrieve and Inject Loop:</p><figure><img alt="Memory Lifecycle Architecture" src="https://cdn-images-1.medium.com/max/1024/1*nKAyx2WGgbNmNjhOOYbW1Q.png" /></figure><ol><li>The Extraction Phase: At the end of a session, an extraction pipeline scans the dialogue, filters out the “slop” (ex : <em>“How’s the weather today?”</em>), and extracts atomic facts.</li><li>The Storage Phase: These facts are saved into physical storage databases. We use Vector Databases (Qdrant, Pinecone, pgvector) for fuzzy semantic search, Knowledge Graphs (Neo4j, Graphiti) to map structured entity relationships and PostgreSQL backed unified engines like MemoriesDB to combine vectors, time series, and relations.</li><li>The Retrieval &amp; Injection Phase: When the user returns tomorrow, the system doesn’t dump the whole database into the prompt. Instead, it runs a specialized retrieval query and injects only the most relevant snippets.</li></ol><p>A highly optimized memory system doesn’t just run simple cosine similarity search. It scores memories by balancing similarity, recency, and importance:</p><p><strong>Memory Score=(0.4×Similarity)+(0.35×Recency Decay)+(0.25×Importance)Memory Score=(0.4×Similarity)+(0.35×Recency Decay)+(0.25×Importance)</strong></p><p>This prevents critical context mistakes. If you tell an AI you like jazz music today and six months ago you stated you have a life threatening allergy to peanuts, a pure similarity search for a dinner recommendation might surface jazz. The scoring function ensures your deadly peanut allergy is prioritized over Miles Davis, saving your life in the process.</p><h3>6. Conclusion: Memory Is the Compass That Matters</h3><p>Let’s stop pretending that a bigger context window solves the fundamental limits of memory.</p><p>A larger context window is a bigger, wider table to work on. It is a massive capability, but it is not an architectural strategy. If you stuff that table with a messy, unorganized, million token mountain of raw text, the model is going to skim it, get confused in the middle, slow your application to a crawl and drain your budget before the end of the quarter.</p><p>The future of AI does not depend on how much information a model can see at once, but on how intelligently it can remember what actually matters.</p><p>An AI that reads everything but remembers nothing is just a highly expensive, extremely fluent stranger. Let’s build agents that actually get to know us.</p><h3>📚 References and Sources</h3><ol><li>Stanford &amp; University of Washington Research (Liu et al., 2023) -<em>“Lost in the Middle: How Language Models Use Long Contexts”</em></li><li>Chroma Research (2025/2026) -<em>“Context Rot: How Increasing Input Tokens Impacts LLM Performance”</em></li><li>LMU Munich &amp; Adobe Research (ICML 2025) -<em>“NoLiMa: Long-Context Evaluation Beyond Literal Matching”</em></li><li>Mem0 Research (April 2026) -<em>“Mem0: Production-Ready AI Agents with Scalable Long-Term Memory (arXiv:2504.19413)”</em></li><li>Zep Research (2025/2026) -<em>“Zep &amp; Graphiti: A Temporal Knowledge Graph Architecture for Agent Memory (arXiv:2501.13956)”</em></li><li>xMemory Research (arXiv:2602.02007) -<em>“Decoupling and Structuring dialogue streams for Agent Memory Systems”</em></li><li>IBM Research -<em>“The Ephemeral Nature of the Large Context Window”</em></li><li>RankSquire Master Content Engine (March 2026) -<em>“Agent Memory vs RAG: What Breaks at Scale 2026 (Analyzed)”</em></li><li>Zylos Research (2026) -<em>“Context Window Economics &amp; Session Lifecycle Management in Persistent AI Agents”</em></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1c7bffbf3f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Solved Authentication and Deployment Without Losing My Mind]]></title>
            <link>https://thejandeera.medium.com/how-i-solved-authentication-and-deployment-without-losing-my-mind-b5e5bda697c2?source=rss-a4e3258d6c51------2</link>
            <guid isPermaLink="false">https://medium.com/p/b5e5bda697c2</guid>
            <dc:creator><![CDATA[Thejandeera Sandeepana]]></dc:creator>
            <pubDate>Thu, 29 Jan 2026 14:31:40 GMT</pubDate>
            <atom:updated>2026-01-29T14:31:40.424Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DHurQ25_uB92zQ2Jd-tKdw.png" /></figure><p>If you ve ever built a full stack application for a university project or a hackathon, you know the struggle. You spend weeks coding the actual features in my case, <strong>CityPulse</strong>, a smart city platform where citizens report issues like potholes or broken lights , but then you hit a wall.</p><p>Suddenly, you have to figure out how to handle secure logins (which is terrifying to do from scratch) and how to get your code off localhost and onto the internet.</p><p>For CityPulse, I didn’t want to waste time configuring servers or writing complex security protocols. I wanted to focus on the AI and the user experience. So, I used <strong>Asgardeo</strong> for identity management and <strong>WSO2 Choreo</strong> for deployment.</p><p>Here is a deep dive into how I set this up, step-by-step.</p><h3>Part 1: Solving the Who Are You? Problem (Asgardeo)</h3><p>Let’s be honest, writing your own login system is a bad idea. You have to hash passwords, manage sessions, and worry about security vulnerabilities. I decided to offload all of that to <strong>Asgardeo</strong>. It basically handles the “Sign Up” and “Sign In” flow for me.</p><p><strong>Setting up the App Context</strong> I started by going into the Asgardeo console. The first thing I did was create a Standard Based Application for my React frontend. This is crucial because it gives you a <strong>client ID</strong> , a unique key that allows your React code to talk to Asgardeo safely.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1z_KasVhy-e4Cp_uOr4Zkw.png" /></figure><p><strong>Connecting React to Asgardeo</strong> , Once I had that Client ID, I didn’t have to write complex API calls. I used the “@asgardeo/auth-react library” . It provides a wrapper called Authprovider that you just wrap around your main App component.</p><p>Here is the actual code I wrote in my main.jsx . You can see I passed the clientId I got from the dashboard, and for testing, I set the redirect URLs to my localhost</p><pre>import React from &#39;react&#39;<br>import ReactDOM from &#39;react-dom/client&#39;<br>import App from &#39;./App.jsx&#39;<br>import &#39;./index.css&#39;<br>import { AuthProvider } from &quot;@asgardeo/auth-react&quot;;<br><br>const authConfig = {<br>  signInRedirectURL: &quot;http://localhost:5173&quot;,<br>  signOutRedirectURL: &quot;http://localhost:5173&quot;,<br>  clientID: &quot;use_your_client_id&quot;,<br>  baseUrl: &quot;https://api.asgardeo.io/t/use_ur_organization&quot;,<br>  scope: [&quot;openid&quot;, &quot;profile&quot;, &quot;email&quot;]<br>};<br><br>ReactDOM.createRoot(document.getElementById(&#39;root&#39;)).render(<br>  &lt;React.StrictMode&gt;<br>    &lt;AuthProvider config={authConfig}&gt;<br>      &lt;App /&gt;<br>    &lt;/AuthProvider&gt;<br>  &lt;/React.StrictMode&gt;,<br>)</pre><p><strong>Next Identifying the User</strong> Now, here is the cool part. When a user logs in, Asgardeo handles the credentials. But in my database (MongoDB), I need to link specific reports to specific users. I don’t store their password, but I do need a unique ID.</p><p>Asgardeo provides a standard OpenID Connect field called <strong>“sub” </strong>(Subject). In my code, I set up a “<strong>useEffect”</strong> hook to grab this ID as soon as the user authenticates. This ensures that when a user submits a picture of a pothole, the system knows exactly who sent it</p><pre>const { signIn, state, getBasicUserInfo } = useAuthContext();<br>const [userId, setUserId] = useState(null);<br><br>useEffect(() =&gt; {<br>    if (state.isAuthenticated) {<br>        getBasicUserInfo().then((user) =&gt; {<br><br>            setUserId(user.sub);<br>            console.log(&quot;Asgardeo Unique User ID (sub):&quot;, user.sub);<br>        }).catch((error) =&gt; {<br>            console.error(&quot;Error fetching user info:&quot;, error);<br>        });<br>    }<br>}, [state.isAuthenticated, getBasicUserInfo]);</pre><p><strong>Finally Managing the User Base</strong> , The best part about this is the dashboard. As people sign up for CityPulse, I can see them listed in the Asgardeo console. I can manage their accounts, reset access, or even block users if I need to, without ever touching a database query</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C9FYsCg0CpDgtKh5hwR8SA.png" /></figure><h3>Part 2: The Backend Deployment (Choreo)</h3><p>With authentication solved, I needed a place to run my backend. My backend is written in <strong>Ballerina</strong>, which is great for integration, but I needed it running on the cloud, not just my laptop. This is where <strong>Choreo</strong> comes in.</p><p><strong>Creating the Service</strong> I logged into Choreo and created a “Service” component. I connected my GitHub account, picked my repository, and pointed it to the “backend” folder. Choreo is smart enough to detect that I&#39;m using Ballerina and automatically selects the right build preset.</p><figure><img alt="Create backend service in choreo" src="https://cdn-images-1.medium.com/max/1024/1*r-ilGN06IgGiHdPm2z7BgQ.png" /></figure><p><strong>The “Magic” Build Pipeline</strong> is , Once you click create, Choreo sets up a CI/CD pipeline. You don’t have to write GitHub Actions or configure Jenkins. It just pulls the code, builds the container, scans it for security vulnerabilities (which is a huge plus for our student projects), and deploys it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hQOhCWaud1d0snuJ2lRQXQ.png" /></figure><p><strong>Next Handling Secrets (The Right Way) , </strong>My backend needs to talk to MongoDB and Hugging Face (for the AI classification) and cloudinary too. <strong>Never hardcode your API keys in your code!</strong> Choreo has this feature called “Configurables.” I defined my keys in the code, and Choreo gave me a secure form to input the actual values (like “connectionKey ”and “hfApiKey ”) so they are injected securely at runtime.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kkmD-BonYf5IScxZeYgYlw.png" /></figure><p><strong>Finally Testing in the Browser</strong> Before I even connected the frontend, I wanted to make sure the API worked. Choreo has a built-in “Test” console. I fired a request to my “<strong>/report </strong>”endpoint, and you can see the JSON response right there it successfully pulled data from my MongoDB Atlas database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KrG_vGC33KBO6Hd2zgnmig.png" /></figure><h3>Part 3: The Frontend Deployment</h3><p>Finally, I needed to get the React application live.</p><p><strong>Setting up the Web App</strong> In Choreo, I selected “Web Application” this time. I pointed it to the same repository but selected the “<strong>frontend</strong>” folder. I chose the <strong>React</strong> build preset. And i gave the command to run “<strong>npm run build</strong>” to generate the static files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*19QOtPj0hoG0neFe8ETOXg.png" /></figure><p><strong>Connecting Frontend to Backend</strong> This was a tricky part. My React app needs to know the URL of the backend API I just deployed. Instead of hardcoding it, Choreo let me use a <strong>File Mount</strong>. I mounted a config.js file into the container, which allows the app to read the backend URL dynamically. This makes the app super portable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lOuWyEmBZaxERB3eWaJQHw.png" /></figure><p><strong>Finally Monitoring Success</strong> , Once everything was live, I checked the <strong>“Usage Insights.”</strong> Choreo gives you this dashboard where you can see how much traffic you’re getting, your latency, and if any errors are happening. It’s incredibly satisfying to see that traffic spike when you demo the project!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L_eDP4z2vt87VV8EcHF1sQ.png" /></figure><h3>Conclusion</h3><p>Building CityPulse taught me that you <strong>don’t need to be a DevOps expert</strong> to deploy a scalable, secure application. Asgardeo took care of the security headache by handling <strong>OIDC authentication</strong> and user management. Choreo automated the entire build and deploy process, letting me go from “it works on my machine” to “it works on the cloud” in minutes. If you are a student working on a final year project, I highly recommend checking this stack out. It saves you so much time that you can spend on making your actual features better.</p><p>Finally, here are a few more snapshots from the deployment process !</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hQOhCWaud1d0snuJ2lRQXQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vAR07g215kg1YBwjds5_-A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_KIb5TekinxHNtv1mFwZCw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4oJzPTwMsbFTJJDsbsw_iA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IQeZEWvbpyLhcD5MJzeFwA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VEMQp3tkWpMgVi_2H-ytjA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5e5bda697c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ACID and BASE : Choosing the Right Data Consistency]]></title>
            <link>https://thejandeera.medium.com/acid-and-base-choosing-the-right-data-consistency-36483edf3dbd?source=rss-a4e3258d6c51------2</link>
            <guid isPermaLink="false">https://medium.com/p/36483edf3dbd</guid>
            <dc:creator><![CDATA[Thejandeera Sandeepana]]></dc:creator>
            <pubDate>Tue, 23 Dec 2025 17:46:01 GMT</pubDate>
            <atom:updated>2025-12-23T17:46:01.281Z</atom:updated>
            <content:encoded><![CDATA[<h3>ACID and BASE : Choosing the Right Data Consistency</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7bbmRkEjmW6YxHQi7dHuyQ.png" /></figure><p>If you’ve read my blog long enough, you’ll know that I usually stay away from writing “opinion” articles. Most of my writing simply describes how things work for example, detailing the mechanics of Two-Phase Commit or how vector clocks track causal history. There is not much room for opinions there.</p><p>Not this time! From time to time, I’m asked what I think about data integrity in distributed systems, specifically, how to handle the “truth” when you have massive scale. Can’t avoid opinions in something like this.</p><p>So, which consistency model should you choose these days? Should you cling to the safety of <strong>ACID </strong>transactions like a traditional banker? Or maybe you should embrace the modern, flexible approach of <strong>BASE</strong>? Should you force every microservice to agree instantly using <strong>2PC</strong>, or just let them settle it eventually?</p><p>So here’s my opinion, to kick off the discussion. <strong>Stop trying to force ACID everywhere! Embrace the chaos of Eventual Consistency.</strong></p><p>Happy reading if you’re curious about why, while I hide under a table, just in case. 😅</p><h3><strong>The “Truth” Spectrum ,Why We Can’t Have It All</strong></h3><p>In the world of distributed systems, we are constantly fighting against the <strong>CAP Theorem</strong>. This theorem dictates that a distributed system can only provide two of the following three guarantees: <strong>Consistency</strong> (everyone sees the same data), <strong>Availability</strong> (the system always responds), and <strong>Partition Tolerance</strong> (the system works even if the network breaks).</p><p>Since network failures are inevitable in distributed systems (Partition Tolerance is non-negotiable), we are forced to make a brutal choice, <strong>Consistency (CP) or Availability (AP)</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*c22jAAPjLFfStEY_MIRv_A.png" /></figure><p>This is where the battle between ACID and BASE begins.</p><h3><strong>The Strict Teacher: ACID</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bEKFWSvbWJo_YbZDpmtQNg.png" /></figure><p><strong>ACID</strong> (Atomicity, Consistency, Isolation, Durability) is the gold standard for traditional relational databases. It guarantees that transactions are processed reliably.</p><ul><li><strong>Atomicity:</strong> All or nothing. If one part of the transaction fails, the whole thing rolls back.</li><li><strong>Consistency:</strong> The database moves from one valid state to another.</li></ul><p>To achieve this in a distributed system, we often use protocols like <strong>Two-Phase Commit (2PC)</strong>. The coordinator asks everyone “Can you commit?”, and only if <em>everyone</em> says yes, does the data get saved.</p><p><strong>So What is the problem ?</strong> It’s a blocking protocol. If the coordinator crashes, everyone waits. It kills your availability and performance in favor of perfect correctness.</p><h3>The Chill Friend: BASE</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Dd-PyTSjdBW50tFY4CjBw.png" /></figure><p><strong>BASE</strong> is the alternative for modern, high-scale systems. It stands for:</p><ul><li><strong>Basically Available:</strong> The system prioritizes staying up, even if some nodes fail.</li><li><strong>Soft State:</strong> The state of the system might change over time, even without input (due to replication updates).</li><li><strong>Eventually Consistent:</strong> The system will become consistent <em>eventually</em>, but for a moment, different users might see different data.</li></ul><p><strong>My Opinion: Choose Availability (Mostly)</strong></p><p>Here is why I think you should lean towards BASE : <strong>Scalability and User Experience.</strong></p><p>In a distributed environment, “global coordination” (what ACID requires) is the enemy of speed. If you insist on strong consistency for everything, your users will stare at loading spinners every time a network packet gets dropped.</p><p><strong>The sources suggest that strict consistency is often overkill.</strong></p><ul><li><strong>Social Media:</strong> Does it matter if you see a “Like” count of 50 while your friend sees 51? No. You want the feed to load fast. This is a classic <strong>BASE scenario.</strong></li><li><strong>E-Commerce:</strong> Amazon famously uses a BASE model for shopping carts. They would rather let two people buy the last item (and apologize to one later) than prevent you from adding items to your cart because the database is “locking” the inventory.</li></ul><p>Of course, you can’t use BASE for everything. If you are building a banking ledger or medical record system, you absolutely need ACID. You cannot have “eventual consistency” with my bank balance!</p><p>But for the vast majority of modern applications analytics, content feeds, caching layers <strong>Eventual Consistency</strong> is not a bug . it is a feature that allows you to scale.</p><p>Ultimately, the choice comes down to your business requirements. But if you try to build the next Netflix or Twitter using strict ACID transactions for every interaction, you are building a system destined to crash under its own weight.</p><h3><strong>Think of it this way</strong></h3><p><strong><em>ACID</em></strong><em> is like signing a mortgage. Everyone (bank, buyer, seller, lawyers) must sit in a room, verify every document, and sign at the exact same time. If one person is missing, nothing happens. It’s safe, but slow.</em></p><p><strong>BASE</strong> <em>is like a busy coffee shop. You place an order, the cashier takes your money, and you step aside. The barista hasn’t made the coffee yet (the system is “inconsistent”), but the line keeps moving fast. Eventually, you get your coffee, and the state becomes consistent. For high-volume businesses, you want the coffee shop model, not the mortgage model.</em></p><h3>My Final Words</h3><p>My advice? <strong>Stop fighting the physics</strong>. We live in a world governed by the <strong>CAP Theorem</strong> since networks inevitably break (meaning Partition Tolerance is non-negotiable), you are forced to make a brutal choice do you want to be perfectly right (Consistency) or do you want to be online (Availability)?.</p><p><strong>Unless you are moving actual money or handling critical medical records</strong>, where absolute correctness is non-negotiable, <strong>your users will thank you for choosing Availability</strong>. They would much rather see a slightly outdated “Like” count (a stale read) than a “Service Unavailable” page (a failed request).</p><p>So, are you Team ACID or Team BASE? Let me know in the comments! 👇</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36483edf3dbd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Raft and Paxos: The Architecture of Distributed Consistency]]></title>
            <link>https://thejandeera.medium.com/raft-and-paxos-the-architecture-of-distributed-consistency-3c31c69f21d8?source=rss-a4e3258d6c51------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c31c69f21d8</guid>
            <dc:creator><![CDATA[Thejandeera Sandeepana]]></dc:creator>
            <pubDate>Thu, 27 Nov 2025 08:57:48 GMT</pubDate>
            <atom:updated>2025-11-27T08:57:48.711Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*4cBdI4liLH5z4zIweeg5Tw.png" /></figure><p>Most of my writing simply describes how things work for example, detailing the two-phase communication protocol used by Paxos or the precise mechanics of how Raft manages log replication using the AppendEntries RPC. There is not much room for opinions there.</p><p>Not this time! From time to time, I’m asked what I think about the central brain of distributed systems, specifically, how to handle <strong>coordination</strong> when network failures and crashes are guaranteed to happen. We are talking about <strong>Consensus Algorithms</strong>. Can’t avoid opinions in something like this.</p><p>So, which protocol should you choose these days to ensure <strong>strong consistency</strong> in your distributed databases or cloud services? Should you rely on the mathematically proven foundation of <strong>good old Paxos</strong>? Or maybe the newer, explicitly clear leadership model of <strong>Raft</strong>? Why not use the optimized, high-performance approach of <strong>Multi-Paxos</strong>? Or perhaps, if you have malicious nodes (Byzantine failures), do you immediately jump to <strong>PBFT</strong>? Why not just try to handle coordination without a leader instead?</p><p>So here’s my opinion, to kick off the discussion: <strong>You should prioritise understandability and clarity over abstract complexity!</strong></p><p>Happy reading if you’re curious about why, while I hide under a table, just in case. 😅</p><h3>The Central Brain of Distributed Systems: Why We Need Leader Election</h3><p>Distributed systems the backbone of huge cloud platforms like <strong>AWS </strong>and streaming giants like <strong>Netflix </strong>are basically lots of independent machines trying to act as one unified system. They’re built for scale and availability, but once you start spreading data and logic across so many nodes, a big question shows up: how do all these machines agree on what’s true, especially when failures are inevitable?</p><p>That’s where <strong>consensus algorithms</strong> come in. And at the heart of most of them is a familiar idea is choosing a leader.</p><h3><strong>Why Leader Election is the Anchor in Distributed Chaos</strong></h3><p>The core objective in a distributed environment is <strong>fault tolerance,</strong> the ability of the system to continue operating correctly even if some parts fail. The sources cite the <strong>FLP Impossibility Theorem</strong>, which formalizes the “harsh reality” that guaranteeing both safety and liveness (eventual decision-making) is impossible in a fully asynchronous system with even a single failure. This necessitates mechanisms, like a leader, to maintain order.</p><p><strong>The Leader’s primary jobs are essential for maintaining the system’s coherence:</strong></p><p>1. <strong>Serialization and Ordering:</strong> In systems requiring <strong>strong consistency</strong> (such as banking or distributed databases), the leader serves as the <strong>central sequencer</strong>, ensuring that all operations are applied in the exact same sequence across all replicas. This processing of client commands linearly prevents conflicting updates.</p><p>2. <strong>Conflict Prevention:</strong> The leader prevents chaos by acting as the <strong>single point of write entry</strong>, coordinating tasks and stopping multiple nodes from concurrently updating the same data, which would otherwise lead to inconsistencies.</p><p>3. <strong>Liveness Guarantee:</strong> If the currently elected leader crashes, the system must immediately execute a <strong>leader election protocol</strong> to select a healthy successor, thereby ensuring the system’s <strong>liveness</strong> (its ability to make progress). Services like Apache ZooKeeper rely on leader election for coordinating metadata and determining which nodes are currently alive.</p><h3>The Core Contenders: Paxos vs. Raft</h3><h3><strong>1. Paxos: The Foundational, Formal Consensus Algorithm</strong></h3><p>Paxos, developed by <strong>Leslie Lamport</strong>, is the mathematically proven foundation of fault-tolerant consensus. While immensely powerful, it is also notoriously <strong>complex and difficult to implement correctly</strong> based on the original paper.</p><p>Paxos is designed to tolerate up to F crash failures, requiring at least 2F+1 <strong>total nodes</strong> to ensure a majority decision can always be reached.</p><h4><strong>The Roles in Paxos</strong></h4><p>The algorithm defines three key, abstract roles, which often overlap within the physical nodes:</p><ul><li><strong>Proposers:</strong> Propose a value to be agreed upon.</li><li><strong>Acceptors:</strong> Vote on the proposed value.</li><li><strong>Learners:</strong> Discover the final agreed-upon value once a majority of acceptors reach consensus.</li></ul><h4><strong>The Two Phases of Agreement</strong></h4><p>Paxos guarantees safety through two communication phases:</p><p>1. <strong>Phase 1: Prepare and Promise:</strong></p><ul><li>A Proposer sends a <strong>Prepare(n)</strong> request with a unique number (higher than any previous number) to a majority (quorum) of Acceptors.</li><li>Acceptors respond with a <strong>Promise(n)</strong>, agreeing not to accept any proposals lower than <em>n</em> in the future.</li><li><strong>Crucially, the Acceptor must also return the highest-numbered value it has already accepted</strong> (n_v, v), if one exists.</li></ul><p>2. <strong>Phase 2: Accept and Accepted:</strong></p><ul><li>The Proposer collects a majority of Promises. If any Acceptor returned a previously accepted value (<em>v</em>), the Proposer <strong>must adopt</strong> the value associated with the highest <em>n</em>_<em>v</em> observed.</li><li>The Proposer sends an <strong>Accept(n, v)</strong> request to the Acceptors.</li><li>Acceptors send an <strong>Accepted(n, v)</strong> message if they accept the value <em>v</em>. This rigorous process ensures that consensus is reached on an earlier accepted value during conflicts.</li></ul><h4><strong>Advancing Paxos: Multi-Paxos</strong></h4><p>Basic Paxos is inefficient because it requires the full two-phase protocol for every decision. <strong>Multi-Paxos</strong> optimises this by establishing a stable leader using the initial Paxos phase. This leader can then handle multiple, sequential client updates without repeating the resource-intensive Prepare step, significantly improving performance. This optimized model is used in high-performance systems like Google Spanner and Amazon Cosmos DB.</p><h3>2. Raft: Consensus Designed for Understandability</h3><p>Raft achieves the same safety and fault tolerance guarantees as Paxos but was <strong>intentionally designed to be easier to understand and implement</strong>. This clarity has led to its wide adoption in critical distributed coordination systems like Kubernetes’ <strong>etcd</strong> and HashiCorp <strong>Consul</strong>. Raft is also Crash Fault Tolerant (CFT).</p><p>Raft uses an <strong>explicit leadership model</strong>, where each node is clearly defined as a <strong>Leader</strong>, <strong>Follower</strong>, or <strong>Candidate</strong>.</p><p>The Raft protocol relies on three key components:</p><p>1. <strong>Leader Election (The Heartbeat of the System):</strong></p><ul><li>Nodes start as <strong>Followers</strong>.</li><li>Followers use a <strong>randomized election timeout</strong>. If a Follower misses a periodic heartbeat from the Leader within this time, it assumes failure.</li><li>The Follower transitions to a <strong>Candidate</strong>, increments its term number (the unique identifier for the current leadership period), and issues a <strong>RequestVote RPC</strong>.</li><li>A Candidate becomes the new <strong>Leader</strong> if it secures votes from a <strong>majority</strong> of nodes.</li></ul><p>2. <strong>Log Replication (The Single Source of Truth):</strong></p><ul><li>Once a Leader is elected, it manages all client interaction.</li><li>The Leader appends a client command as a new entry to its own local log.</li><li>The Leader replicates this new log entry to all Followers using the <strong>AppendEntries RPC</strong>.</li></ul><p>3. <strong>Commitment (Applying the Change):</strong></p><ul><li>The Leader waits until it receives acknowledgements from a <strong>majority</strong> of Followers.</li><li>The Leader then marks the entry as <strong>committed</strong> and applies the command to the shared <strong>state machine</strong> (e.g., updating a balance). This process guarantees <strong>strong consistency</strong> by ensuring all correct nodes apply the exact same sequence of commands in the same order.</li></ul><p>Advanced Considerations: Trade-offs and Beyond</p><h3>Crash Faults vs. Byzantine Faults</h3><p>Paxos and Raft are designed primarily for environments where nodes experience <strong>crash failures</strong> (stopping abruptly). They require a strong majority (&gt;50% honest nodes, or 2F+1 total nodes to tolerate F failures).</p><p>In environments where nodes might be malicious or send conflicting, dishonest messages (<strong>Byzantine failures</strong>), different algorithms are required.</p><ul><li><strong>Practical Byzantine Fault Tolerance (PBFT):</strong> This deterministic algorithm is designed for Byzantine faults. It requires at least 3F+1<strong> total nodes</strong> to tolerate <em>F </em>Byzantine nodes but introduces significantly higher communication overhead than Paxos or Raft.</li><li><strong>Blockchain Consensus (PoW/PoS):</strong> These algorithms offer <strong>probabilistic</strong> Byzantine Fault Tolerance, prioritizing decentralization and security over immediate speed by making it computationally or economically difficult for malicious nodes to achieve a majority.</li></ul><h3><strong>Conclusion</strong></h3><p>In distributed systems, keeping a bunch of machines in sync is absolutely essential if you want things to stay reliable, correct, and highly available. But here’s the tricky part . without some form of coordination, all those machines have no guaranteed way to agree on anything especially when the network is unpredictable. That’s exactly why leader election exists.</p><p>Consensus algorithms like Raft and Paxos act like the rulebooks that keep everything in order. Paxos brings the deep mathematical foundation behind ultra-reliable systems, while Raft focuses on being clear, practical, and easy to implement one of the reasons it drives tools like Kubernetes today.</p><p>So choosing between them often comes down to a simple question: do you want the pure mathematical rigor of Paxos or the engineering-friendly simplicity of Raft? Either way, both ensure that even when parts of your system fail, the overall “brain” keeps functioning smoothly.</p><p>The best way to visualize this is like an aircraft’s cockpit. If the main pilot (leader) suddenly becomes unresponsive, the co-pilots (followers) must quickly and safely choose a new pilot. But if two co-pilots both claim to be in charge at the same time… well, that’s a disaster waiting to happen. <br> Raft and Paxos prevent that scenario by guaranteeing that the system always has one, and only one, legitimate leader keeping the whole flight stable and safe.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c31c69f21d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>