<?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 Sanjay Mishra on Medium]]></title>
        <description><![CDATA[Stories by Sanjay Mishra on Medium]]></description>
        <link>https://medium.com/@sharpsanjay?source=rss-f16a028be298------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Sanjay Mishra on Medium</title>
            <link>https://medium.com/@sharpsanjay?source=rss-f16a028be298------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 18:11:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sharpsanjay/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[From Amnesia to Savant: How RAG Gave AI a Permanent Memory]]></title>
            <link>https://medium.com/@sharpsanjay/from-amnesia-to-savant-how-rag-gave-ai-a-permanent-memory-c28a196f73a7?source=rss-f16a028be298------2</link>
            <guid isPermaLink="false">https://medium.com/p/c28a196f73a7</guid>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[systems-thinking]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Sanjay Mishra]]></dc:creator>
            <pubDate>Mon, 08 Jun 2026 21:02:17 GMT</pubDate>
            <atom:updated>2026-06-08T21:02:17.805Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine you are taking a massive, closed-book history exam.</p><p>If you rely purely on your own memory, you might get most facts right, but you might also mix up dates or completely make up a detail that sounds plausible. That is exactly how a standard Large Language Model (LLM) works — it relies entirely on what it “memorized” during training.</p><p>Now, imagine the teacher says, <em>“Actually, you can take this exam open-book. Here is a massive library of up-to-date encyclopedias. Before you answer any question, you can go grab the exact page you need, read it, and then write your answer.”</em></p><p>That is RAG, or Retrieval-Augmented Generation.</p><p>Instead of just guessing or relying on old memory, an AI using RAG looks up the right information first, then uses that information to give you a perfect answer.</p><h3>How RAG Works (The 3-Step Dance)</h3><p>RAG connects an AI model to an external database. Every time you ask it a question, it goes through a quick three-step process:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZK9M8Cmrpw1M88Kj" /></figure><h3>1. Retrieve (The Librarian)</h3><p>When you ask a question (e.g., “What were our company’s Q1 financial results?”), the system doesn’t ask the AI yet. Instead, a search algorithm acts like a hyper-fast librarian. It translates your question into math, searches your private documents or the live internet, and pulls up the 3 or 4 most relevant paragraphs.</p><h3>2. Augment (The Briefing)</h3><p>The system takes those paragraphs and glues them right on top of your original question. It creates a neat little package that essentially says to the AI: <em>“Here is the user’s question, and here is the exact data needed to answer it. Read this first.”</em></p><h3>3. Generate (The Writer)</h3><p>Finally, the LLM reads this combined package. Because it has the facts sitting right in front of it, it doesn’t have to guess. It cleanly summarizes the facts into a natural, easy-to-read response.</p><h3>Why RAG is a Game Changer</h3><p>Before RAG, fixing an AI’s memory gaps was incredibly expensive and difficult. RAG solved the biggest headaches in AI overnight:</p><p>No More Hallucinations: Because the AI is “open-book,” it stops making things up. If the information isn’t in the provided documents, it can just say, “I can’t find that in the text.”</p><p>Up-to-the-Minute Knowledge: Standard AIs are frozen in time (whenever their training ended). With RAG, if a document changes in your database, the AI instantly knows the new info without needing any retraining.</p><p>Privacy &amp; Security: You can feed an AI your private company files, medical records, or personal notes safely. The AI doesn’t “absorb” them permanently; it just references them to answer your specific prompt.</p><p>In short: Standard AI is a smart student trying to pass a test from memory. RAG is that same smart student with a search engine and a library card.</p><h3>Use cases of RAG:</h3><h3>1. The “Super-Doctor” Second Opinion</h3><p>Instead of an AI guessing based on random internet medical forums, RAG feeds it millions of real, anonymized clinical trial pages, textbook breakthroughs, and a patient’s specific health history.</p><p>A doctor can type in a bizarre mix of symptoms, and the AI acts as a global medical board — instantly cross-referencing global research in seconds to spot rare diseases humans might miss.</p><h3>2. The Corporate Time-Machine</h3><p>Large companies have millions of scattered PDFs, Slack logs, old emails, and Notion pages buried across a decade of work.</p><p>New employees can ask, <em>“Why did we stop using the 2019 software vendor, and what did Sarah think of the backup plan?”</em> RAG instantly digs through years of dead internal communication to construct a perfect, immediate answer.</p><h3>3. Hyper-Personalized AI Companions</h3><p>Standard AI forgets everything you said the moment you open a new chat window. RAG connects the AI to a secure, private memory vault of your past interactions.</p><p>You can say, <em>“Based on my goals from last month, edit this workout routine,”</em> and it will remember your knee injury, your favorite exercises, and what time you like to go to the gym.</p><h3>4. Interactive Legal Wizards</h3><p>Law firms deal with thousands of pages of dizzying, microscopic contract language and constantly shifting local regulations.</p><p>A lawyer can upload a brand-new 500-page corporate merger agreement and ask, <em>“Does anything in Section 9 conflict with California tax updates passed three weeks ago?”</em> RAG isolates the exact loopholes instantly.</p><h3>5. Automated Customer Support (That Doesn’t Suck)</h3><p>We all hate chatbots that just loop the same three unhelpful answers. RAG links the support bot directly to the live product manual, shipping database, and return policies</p><p>You can type, <em>“My drone is flashing a blue light twice, then beeping,”</em> and it won’t give you generic troubleshooting. It will pull up the exact page of the hardware manual for your specific serial number and tell you exactly how to fix it.</p><blockquote><em>The Takeaway: RAG takes AI out of the clouds and grounds it in the real world. It transforms AI from a “creative writer” into a flawless, factual execution engine.</em></blockquote><h3>Building Your First RAG System:</h3><p>Welcome to the kitchen! Building a Retrieval-Augmented Generation (RAG) system is surprisingly like cooking a gourmet meal. If you just toss raw data into a basic AI model, you get a messy, inaccurate soup. But if you prep your ingredients correctly, you get a flawless, Michelin-star assistant.</p><p>To build a professional-grade RAG system, we have to collect our ingredients and understand our tools. Let’s look at the master recipe, and then we will master Step 1: Preparing the Raw Data.</p><h3>The Master Recipe</h3><p>To build a RAG system, you need four core ingredients:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NwgcjeHqGYMT6pyr" /></figure><h3>Step 1: Prepping the Data (The Secret Art of “Chunking”)</h3><p>You might think you can just hand a 500-page company handbook PDF straight to an AI and say, <em>“Search this!”</em></p><p>You can’t. If you feed the AI too much text at once, it gets overwhelmed, loses focus, and costs you a fortune in “token fees” (the cost of processing text). Instead, we have to do what any good chef does: we chop it up.</p><p>In AI, this is called Chunking.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/0*V8RxQfY0XIAqARFH" /></figure><p>Think of this as an industrial assembly line for data. It shows a massive, unreadable 5,000-word handbook entering a processing track. The system uses “sliding windows” to slice the document into precise, bite-sized packages. Instead of cutting lines blindly, it strategically creates a shared “Overlap Layer” that acts as a bridge, ensuring the meaning of the text remains perfectly intact from one chunk to the next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/0*3dxeYO-Z-3R6joPP" /></figure><p>This diagram isolates exactly <em>why</em> we overlap text, using a real-world corporate example. If we sliced a document perfectly in half, Chunk 1 would contain the warning about the gate code changing, but Chunk 2 would contain the actual code numbers — completely separating the two pieces of information. By “zipping” them together with a 10% overlap, the critical warning is duplicated in both chunks, ensuring the AI never loses the context.</p><p>Example code:</p><pre># A preview of what our data prep looks like under the hood:<br>from langchain_text_splitters import RecursiveCharacterTextSplitter<br># 1. Load the raw document<br>raw_document = “Our server passcode is 12345. Do not share it...”<br># 2. Configure the “Chef’s Knife”<br>splitter = RecursiveCharacterTextSplitter(<br>    chunk_size=300,      # Chop into 300-word paragraphs<br>    chunk_overlap=50     # Overlap by 50 words so no context is lost<br>)<br># 3. Cut it up!<br>final_chunks = splitter.split_text(raw_document)</pre><h3>Step 2 — The Spice Blend (Text Embeddings)</h3><p>Welcome back to the kitchen! In Step 1, we took our massive raw document and chopped it up into perfectly bite-sized, overlapping chunks of text.</p><p>Now, it’s time to apply the Spice Blend.</p><p>Computers are brilliant at math, but they are completely illiterate. They don’t actually understand words like “Apple,” “iPhone,” or “Fruit.” To make our text searchable, we have to translate human language into something a computer <em>loves</em>: numbers.</p><p>In the AI world, this step is called creating Text Embeddings.</p><h3>Why Do We Need Embeddings? (The Extinction of Keyword Search)</h3><p>In the old days of the internet, search engines used “Keyword Matching.” If you searched for <em>“How to fix a flat tire,”</em> the computer looked for documents that contained those exact words.</p><p>But what if a document said, <em>“Repairing a punctured rubber wheel”</em>? The old computer would miss it entirely because none of the words matched, even though the meaning was identical.</p><p>Embeddings solve this. An embedding model reads a piece of text and extracts its <em>core concept, tone, and meaning</em>, ignoring the exact vocabulary used.</p><h3>What Do the Experts Do Mathematically? (The Latitude &amp; Longitude of Meaning)</h3><p>Imagine you want to map every city on Earth. You don’t describe a city using a giant paragraph; you assign it two numbers: Latitude and Longitude. If two cities have similar numbers, you know they are geographically close to each other.</p><p>An embedding model does the exact same thing, but instead of mapping cities on a 2D map, it maps meanings in a hyper-dimensional space.</p><p>When you pass a chunk of text through an embedding model, the model outputs a massive list of numbers (a vector). Depending on the model, this list might be 768, 1,536, or even 4,096 numbers long!</p><p>Think of these numbers as a “GPS Coordinate for Ideas.”</p><p>If you embed the word “Apple” (the fruit) and the word “Banana”, the mathematical distance between their coordinates will be tiny because they are both fruits. But if you embed “Apple” (the company) and “Banana”, the model looks at the context and places “Apple” closer to “Microsoft” and “Stock Market.”</p><blockquote><em>The Math Metric: To find the right data later, the RAG system uses a formula called Cosine Similarity. It measures the angle between these coordinate arrows. An angle of 1.0 means they point to the exact same concept; a 0.0 means they are totally unrelated.</em></blockquote><h3>Who Are the “Master Spice Blenders” (The Top Models)</h3><p>You don’t have to build these mathematical models yourself. Industry leaders have trained massive neural networks solely to act as translators. The top choices balance cost, speed, and intelligence:</p><ol><li>The Production Baselines (The Easiest Start): * OpenAI (text-embedding-3-small / large): The gold standard for developers starting out. It’s incredibly cheap, reliable, and outputs vectors up to 3,072 dimensions.</li><li>The Open-Source Kings (For Privacy &amp; Power):</li><li>The Specialists:</li></ol><h3>A Glimpse Under the Hood</h3><p>If we were to look at our kitchen script, injecting our text chunks with this spice blend takes just a few lines of code:</p><pre>from langchain_openai import OpenAIEmbeddings<br># 1. Open our jar of spice<br>spice_blender = OpenAIEmbeddings(model=”text-embedding-3-small”)<br># 2. Grab a text chunk from Step 1<br>text_chunk = “The secret server passcode is 12345-Secure.”<br># 3. Translate it into GPS coordinates!<br>numerical_vector = spice_blender.embed_query(text_chunk)<br>print(numerical_vector[:5]) <br># Output looks like math coordinates: [-0.0234, 0.0112, -0.0054, 0.0891, -0.0432...]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9prjHrX-Y-AhOgMj" /></figure><h3>Step 3 — The Pantry (Vector Databases):</h3><p>Your text chunks are perfectly sliced (Step 1), and you’ve spiced them with mathematical “GPS coordinates” called embeddings (Step 2).</p><p>Now, we need a place to store them.</p><p>You cannot use a traditional database like MySQL or PostgreSQL (out of the box) for raw vector storage at scale. If you ask a standard database to find the closest coordinate vector out of 10 million entries, it has to look at every single entry one by one. Your application would grind to a halt.</p><p>We need The Pantry: a Vector Database.</p><h3>What Does a Vector Database Actually Do?</h3><p>A vector database doesn’t just store your numbers; it indexes them.</p><p>Imagine walking into a massive grocery store looking for hot sauce. If all the items were thrown randomly onto shelves, you would have to read every single label in the store to find it. Instead, the store groups things by category: <em>Aisle 4 — Condiments &amp; Sauces</em>.</p><p>Vector databases build mathematical “aisles” using an algorithm called ANN (Approximate Nearest Neighbor).</p><p>The most dominant algorithm used is HNSW (<em>Hierarchical Navigable Small World</em>). It groups similar vectors together into a multi-layered web graph.</p><p>Imagine you live in a tiny, remote village in the countryside of England, and you need to visit a specific friend who lives in a tiny, remote village in the mountains of Japan.</p><p>You don’t walk out your front door and march in a straight line across oceans and continents. You use a hierarchical network:</p><ol><li>The Express Layer (Global Hubs): You take a local train to London, hop on a massive international flight, and fly straight across the world to Tokyo. You just covered 6,000 miles in one giant “hop.”</li><li>The Suburb Layer (Regional Hubs): From Tokyo, you switch to a regional bullet train that takes you to the specific prefecture or city where your friend lives.</li><li>The Street Layer (Local Neighborhoods): Finally, you get off the train, hop into a local taxi, and drive down the small neighborhood streets until you knock on your friend’s front door.</li></ol><p>That is exactly how HNSW searches for vectors. It separates your data points into a multi-layered graph. The top layers have very few points and long-distance connections (international flights), while the bottom layer contains every single data point with tight, local connections (local neighborhood streets).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/0*c4mUcCVvLzT0yU7P" /></figure><h3>Walking Through the Search Path</h3><p>When your RAG system runs a query, it executes a Greedy Search from top to bottom:</p><ol><li>Step 1: The database enters Layer 2 at a default entry point. It looks around at its immediate neighbors and asks: <em>“Which node points closest to our User Query?”</em> It takes a massive leap over to Global Hub B. It realizes it can’t get any closer on this layer.</li><li>Step 2: It drops straight down into the exact same geographical coordinate space in Layer 1. Starting from this position, it scans the regional connections and quickly shifts over to Regional Hub C.</li><li>Step 3: It drops down to the final Layer 0 (Local Streets). Here, it checks the immediate surrounding data chunks and effortlessly identifies the exact Target Vector containing the answer.</li></ol><h3>Why this is a miracle for performance:</h3><p>If the database searched through Layer 0 line-by-line, it would have to compute math equations for millions of nodes.</p><p>By using the HNSW hierarchy, it only had to look at a tiny handful of nodes across the top layers to teleport straight to the correct neighborhood. This changes search time from an exhausting marathon into a lightning-fast jump, ensuring your RAG system responds in the blink of an eye.</p><h3>Picking Your Pantry: The Standouts</h3><p>The landscape features specialized options depending on what you are building:</p><h3>1. The Zero-Ops Choice: Pinecone</h3><ul><li>The Vibe: The cloud-native default. You don’t manage servers, configure RAM, or fiddle with index settings. You just spin it up via an API web link and start writing data.</li><li>Best For: Fast-moving startups or production apps where developer time is more expensive than infrastructure bills.</li></ul><h3>2. The Local &amp; Open-Source Kings: Qdrant &amp; Weaviate</h3><ul><li>The Vibe: Powerful, developer-first, and highly customizable. Qdrant is built in Rust (meaning it is blindingly fast and highly memory efficient) and has an amazing free tier. Weaviate is excellent if you want to mix standard keyword searches with vector searches.</li><li>Best For: Teams that want full architectural control or need to self-host to ensure data privacy.</li></ul><h3>3. The “You Already Have It” Winner: pgvector (PostgreSQL)</h3><ul><li>The Vibe: An extension that transforms standard Postgres into a vector database.</li><li>Best For: Applications with under 10–50 million chunks. If your core app data already lives in Postgres, installing pgvector means you don’t have to spin up, secure, or monitor a completely separate database system.</li></ul><h3>4. The Prototype Tool: ChromaDB</h3><ul><li>The Vibe: A lightweight database that can run completely in-memory inside your local Python notebook.</li><li>Best For: Testing things out on your laptop before pushing code to a cloud environment.</li></ul><h3>Writing the Code: Stocking the Pantry</h3><p>Let’s see how our kitchen script stores our seasoned chunks using an open-source, local vector database like ChromaDB:</p><pre>from langchain_chroma import Chroma<br>from langchain_openai import OpenAIEmbeddings<br># 1. Grab our spice blender from Step 2<br>spice_blender = OpenAIEmbeddings(model=”text-embedding-3-small”)<br># 2. Grab our chopped text nuggets from Step 1<br>chunks_to_store = [<br>    “🧩 Chunk A: The server passcode is 12345-Secure.”,<br>    “🧩 Chunk B: Python source code for the backend API goes here...”<br>]<br># 3. Create the Database Pantry and save everything!<br>pantry_db = Chroma.from_texts(<br>    texts=chunks_to_store,<br>    embedding=spice_blender,<br>    persist_directory=”./my_pantry_folder” # Saves it to your hard drive<br>)<br>print(”Pantry fully stocked!”)</pre><p>The database automatically handles the heaviest lifting: it sends the text chunks to OpenAI, receives the math coordinates, maps the HNSW neighborhood graphs, and saves it all to disk.</p><p>Our database pantry is officially fully stocked. Next up, we actually get to open the kitchen doors, take a user’s live order (query), and pull the exact information back out!</p><h3>Step 4 — The Retrieval (Taking the Live Order)</h3><p>Welcome back to the kitchen! Your pantry is stocked, your text chunks are indexed on their HNSW geometric graphs (Step 3), and the kitchen doors are officially open.</p><p>It is time for Step 4: The Retrieval Phase.</p><p>This is the exact moment a user sits down at the table, looks at the menu, and asks a live question. Our system’s job is to take that order, run to our vector pantry, and pull out the <em>exact right ingredients</em> needed to answer it.</p><h3>The Query Flow (The 3-Part Workflow)</h3><p>When a user submits a prompt, it kicks off a beautifully coordinated, sub-second workflow to extract the facts. Let’s see what happens behind the scenes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/0*FGr1IepGg6L_PHFW" /></figure><h3>4.1 Vectorizing the Question</h3><p>When a user types: <em>“How do I reset my server passcode?”</em>, our database pantry cannot read those words directly. First, we must pass this question through the exact same Embedding Model (the Spice Blend from Step 2) we used on our documents. This converts the user’s question into a live search coordinate vector.</p><h3>4.2 The Mathematical Handshake</h3><p>The database takes that fresh search coordinate and drops it into the HNSW network map we explored. It calculates the Cosine Similarity between the user’s question vector and our stored document vectors.</p><p>The database doesn’t look for keyword matches. It looks for <em>conceptual proximity</em>. Even if your document uses the words “credentials” or “access key” instead of “passcode,” the vectors will naturally drift toward each other because the core concept is identical.</p><h3>4.3 Returning “Top K” Results</h3><p>In production systems, you will hear engineers talk about the parameter “Top K” (or k). This is simply a fancy setting that tells the database: <em>“Hey, give me the top </em>K<em> closest matching text blocks.”</em></p><p>Usually, we set k=3 or k=5. The database packs up those top-winning text chunks and hands them back to our application layer.</p><h3>The Code: Pulling Data From the Pantry</h3><p>Let’s look at how beautifully simple it is to write the code for the retrieval phase using our initialized database:</p><pre>from langchain_chroma import Chroma<br>from langchain_openai import OpenAIEmbeddings<br># 1. Initialize our tools (pointing to our existing directory)<br>spice_blender = OpenAIEmbeddings(model=”text-embedding-3-small”)<br>pantry_db = Chroma(persist_directory=”./my_pantry_folder”, embedding_function=spice_blender)<br># 2. Take the live user order<br>user_question = “How do I reset my server passcode?”<br># 3. Configure the “Top K” retriever to grab the top 2 closest chunks<br>retriever = pantry_db.as_retriever(search_kwargs={”k”: 2})<br># 4. Fetch the matches!<br>winning_chunks = retriever.invoke(user_question)<br># Let’s print what we pulled from the pantry<br>for i, chunk in enumerate(winning_chunks):<br>    print(f”Match #{i+1}: {chunk.page_content}\n”)</pre><h3>What just happened under the hood?</h3><p>In less than 50 milliseconds, your system:</p><ol><li>Converted your live question into a string of numbers.</li><li>Traversed the localized database layers.</li><li>Ignored thousands of irrelevant files.</li><li>Brought back the exact paragraphs dealing with server credentials.</li></ol><h3>Pro-Tip: The “Metadata Filtering” Superpower</h3><p>What if your database grows to hold millions of documents from 50 different clients? If Client A asks a question, you don’t want the retriever pulling up confidential information belonging to Client B.</p><p>To solve this, professional RAG developers use Metadata Filtering. When you save chunks in Step 3, you attach tiny tags to them (e.g., {“client_id”: “A”, “department”: “HR”}).</p><p>During retrieval, you can tell your database: <em>“Only look at vectors where the </em>client_id<em> equals </em>A<em>.”</em> This ensures ironclad security, incredibly sharp search scopes, and zero cross-contamination of private files.</p><h3>Step 5 — Augment &amp; Generate (Serving the Plate)</h3><p>Welcome to the grand finale! Our text nuggets are prepped, spiced, stored, and the winning paragraphs have just been pulled from the pantry counter (Step 4).</p><p>Now, we hit Step 5: Augment &amp; Generate.</p><p>This is where the magic happens. We are going to take the user’s original question, seamlessly glue the retrieved facts right on top of it (Augment), and hand it over to the Large Language Model to write a flawless, hallucination-free answer (Generate).</p><h3>The Engineering Blueprint (The System Prompt)</h3><p>How do we actually force an AI model to read our files instead of just guessing from memory? We use a System Prompt.</p><p>Think of this as giving strict marching orders to a world-class assistant. We wrap our data inside clear structural boundaries (often using XML-style tags like &lt;context&gt;) so the AI knows exactly where the facts end and where the user’s question begins.</p><p>Here is what the combined “Augmented” package looks like right before it gets fired off to the LLM:</p><p>By framing the prompt this way, we completely eliminate the AI’s need to guess. It has the open-book answer sitting right on its screen.</p><h3>Writing the Final Code Block</h3><p>Let’s look at how the final piece of our RAG application comes together. We will use a standard model (like OpenAI’s gpt-4o or Anthropic’s claude-3–5-sonnet) to handle the generation phase.</p><pre>from langchain_chroma import Chroma<br>from langchain_openai import OpenAIEmbeddings, ChatOpenAI<br>from langchain_core.prompts import ChatPromptTemplate<br># 1. Pull up our fully-stocked database pantry from Step 4<br>spice_blender = OpenAIEmbeddings(model=”text-embedding-3-small”)<br>pantry_db = Chroma(persist_directory=”./my_pantry_folder”, embedding_function=spice_blender)<br># 2. Take the live order and retrieve the top winning chunks<br>user_question = “How do I reset my server passcode?”<br>retrieved_docs = pantry_db.similarity_search(user_question, k=2)<br># Merge the text from our winning chunks into a single block of text<br>context_block = “\n\n”.join([doc.page_content for doc in retrieved_docs])<br># 3. Create the “Augmented” System Prompt Template<br>rag_prompt = ChatPromptTemplate.from_messages([<br>    (”system”, “You are a precise corporate assistant. Answer the user’s question using ONLY the following retrieved context. If the answer cannot be found in the context, respond honestly with ‘I do not have access to that information.’\n\nContext:\n{retrieved_context}”),<br>    (”human”, “{question}”)<br>])<br># 4. Initialize the Chef (The LLM Generator)<br>generator_llm = ChatOpenAI(model=”gpt-4o”, temperature=0.0) # Temperature 0 means “Stick strictly to the facts!”<br># 5. Connect the dots and run it!<br>final_formatted_prompt = rag_prompt.format_messages(<br>    retrieved_context=context_block,<br>    question=user_question<br>)<br>smart_answer = generator_llm.invoke(final_formatted_prompt)<br>print(f”✨ Smart RAG Answer:\n{smart_answer.content}”)</pre><h3>Why Setting temperature=0.0 is Crucial</h3><p>In creative writing AI apps, you want a higher temperature (like 0.7 or 0.9) so the AI can be poetic and imaginative. In RAG systems, imagination is our enemy. Setting the temperature to a flat 0.0 dials down the AI’s creativity, forcing it to be a strict, analytical reader that only echoes the provided text.</p><h3>The Ultimate Payoff</h3><p>You have just journeyed through the entire core architecture of a professional production RAG pipeline.</p><p>By separating your knowledge layer (the Vector Database) from your thinking layer (the LLM), you have created an AI system that is:</p><ol><li>Dynamic: Update your corporate text files, and the AI knows the new rules instantly without retraining.</li><li>Secure: It only knows what you show it during that specific fraction of a second.</li><li>Traceable: You can print out the exact winning_chunks to show users exactly <em>why</em> the AI gave that answer, adding total transparency to your application.</li></ol><p>Please let me know your thoughts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c28a196f73a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beauty of Kafka: Why Kafka Is Both Fast and Persistent]]></title>
            <link>https://medium.com/@sharpsanjay/beauty-of-kafka-why-kafka-is-both-fast-and-persistent-e4f90736d978?source=rss-f16a028be298------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4f90736d978</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[performance-optimization]]></category>
            <dc:creator><![CDATA[Sanjay Mishra]]></dc:creator>
            <pubDate>Sat, 04 Apr 2026 03:02:29 GMT</pubDate>
            <atom:updated>2026-04-04T03:02:29.910Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deep dive into kafka architecture.</h3><p>Imagine this, Uber tracking millions of rides in real time, Netflix processing billions of events daily and LinkedIn powering activity feeds across the globe. All of them rely heavily on Kafka.</p><p>Now here’s the strange part: Kafka <strong>writes everything to disk, </strong>And yet, it behaves like a <strong>high-speed streaming system</strong></p><p>That shouldn’t be possible. Traditionally:</p><blockquote><em>Disk → slow</em></blockquote><blockquote><em>Memory → fast</em></blockquote><p>But Kafka breaks that intuition.</p><p>So the real question is: <strong><em>How does Kafka achieve speed without sacrificing persistence?</em></strong></p><h3>The One Idea Behind Everything</h3><p>Kafka is not just a message queue.</p><blockquote><strong><em>Kafka is a distributed append-only log.</em></strong></blockquote><p>This sounds simple — almost too simple. But this is the idea that powers:</p><ul><li>Uber’s real-time pipelines</li><li>Netflix’s event streaming platform</li><li>LinkedIn’s activity and analytics systems</li></ul><h3>What this means</h3><p>Producers <strong>append data, </strong>Consumers <strong>read by offset and </strong>Data is <strong>not immediately deleted. </strong>This one decision simplifies everything.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*z27YQ4wiP7GDNmRe.png" /></figure><h3>Uber’s Problem (And Why Kafka Fits Perfectly)</h3><p>Think about Uber: drivers sending location updates every few seconds, riders requesting trips and pricing systems reacting instantly. That’s a <strong>constant stream of events</strong>.</p><p>Now imagine trying to: update records in place, maintain strict ordering globally and process everything synchronously. It would collapse under load.</p><p>Kafka’s model fits naturally: every event is <strong>just appended, </strong>nothing is mutated and multiple systems consume independently</p><p>Kafka doesn’t try to model state first. It models <strong>events first</strong>.</p><h3>Kafka Doesn’t Fight the Disk — It Aligns With It</h3><p>Here’s where Kafka becomes elegant. Disk is not slow.</p><p>» <strong>Random access is slow. Sequential access is fast.</strong></p><p>Kafka chooses: no updates, no deletes (in hot path) and only <strong>append</strong></p><blockquote>Traditional systems:</blockquote><blockquote>update A → update B → delete C</blockquote><blockquote>Kafka:</blockquote><blockquote>append A → append B → append C</blockquote><p>This turns disk into a <strong>streaming device</strong>, not a random-access store. That’s the first piece of Kafka’s performance story.</p><h3>Persistence That Feels Like Memory: Page Cache</h3><p>Kafka doesn’t try to outsmart the operating system. It uses it.</p><p>When Kafka writes data: Data goes to <strong>OS page cache (RAM) and </strong>OS flushes it to disk <strong>asynchronously.</strong></p><p>When Kafka reads: If data is in cache → <strong>memory speed and </strong>If data not in cache → disk → then cached.</p><h3>Why this is powerful</h3><p>You get:<strong>Fast writes (RAM-backed), Durability (disk-backed) and Fast reads (cache reuse)</strong></p><p>Kafka is fast not because it avoids disk — but because it uses the OS <strong>exactly how it was designed to be used</strong>.</p><h3>Batching: Small Messages, Big Efficiency</h3><p>Kafka doesn’t process one message at a time.It processes <strong>batches everywhere</strong>: producer → broker , broker → disk, broker → consumer</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*U_ZNtqnvyjQBz56u.png" /></figure><h3>Why batching matters</h3><p>Without batching: too many syscalls, tiny disk writes, network inefficiency</p><p>With batching: fewer syscalls, large sequential writes and efficient network usage</p><h3>Example (producer batching)</h3><p>kafka-console-producer.sh \</p><p>--bootstrap-server localhost:9092 \</p><p>--topic test \</p><p>--producer-property batch.size=16384 \</p><p>--producer-property linger.ms=5</p><p>This allows the producer to <strong>wait briefly and group messages</strong>. Small delay → huge throughput gain.</p><h3>Zero-Copy: Removing Useless Work:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UQCDyWk3h7sMweHs.png" /></figure><h3>Why this matters</h3><p>Fewer memory copies, lower CPU usage and higher throughput. Kafka doesn’t just write efficiently — it <strong>serves data efficiently</strong> too.</p><h3>Partitioning: Scaling Without Complexity</h3><p>Kafka splits topics into <strong>partitions</strong>.</p><p>Each partition is: an independent log, sequentially written and distributed across brokers.</p><h3>Create a partitioned topic:</h3><p>kafka-topics.sh \</p><p>--create \</p><p>--topic orders \</p><p>--partitions 3 \</p><p>--replication-factor 1 \</p><p>--bootstrap-server localhost:9092</p><h3>Why this is elegant</h3><p>ordering within partition → simple, multiple partitions → parallelism and scaling → horizontal. Kafka doesn’t try to globally order everything. It trades that for <strong>massive throughput and scalability</strong>.</p><h3>Persistence Made Real: Data on Disk</h3><p>Kafka is not “logically persistent.” It is physically persistent. You can literally see the data:</p><p>ls /var/lib/kafka/data/orders-0/</p><p>00000000000000000000.log</p><p>00000000000000000000.index</p><p>00000000000000000000.timeindex</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/0*GZ1r2tGzL3ydDoRd.png" /></figure><h3>What this tells you</h3><p>Kafka stores <strong>real file. </strong>Data is <strong>append-only and </strong>Segments make management easy</p><p>Restart the broker — data is still there. No magic. Just clean design.</p><h3>Replication and ISR: Durability You Can Tune</h3><p>Kafka uses:</p><ul><li><strong>leader</strong></li><li><strong>followers</strong></li><li><strong>ISR (in-sync replicas)</strong></li></ul><h3>Create a replicated topic</h3><p>kafka-topics.sh \</p><p>--create \</p><p>--topic payments \</p><p>--partitions 1 \</p><p>--replication-factor 3 \</p><p>--bootstrap-server localhost:9092</p><h3>Producer durability control</h3><p>kafka-console-producer.sh \</p><p>--topic payments \</p><p>--bootstrap-server localhost:9092 \</p><p>--producer-property acks=all</p><h3>What this means</h3><ul><li>acks=1 → fast, weaker durability</li><li>acks=all → stronger durability, may block if replicas lag</li></ul><p>Kafka doesn’t hide trade-offs.It exposes them clearly:</p><blockquote><strong><em>Consistency vs Availability — configurable.</em></strong></blockquote><p>That’s practical CAP.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eJHQvavZtYvDvnEH.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qoTKHxiAEy1YOb3v.png" /></figure><h3>Log Compaction: When Kafka Behaves Like a Database</h3><p>Kafka can retain only the <strong>latest value per key</strong>.</p><h3>Create compacted topic</h3><p>kafka-topics.sh \</p><p>--create \</p><p>--topic user-state \</p><p>--partitions 1 \</p><p>--replication-factor 1 \</p><p>--config cleanup.policy=compact \</p><p>--bootstrap-server localhost:9092</p><h3>Produce keyed data</h3><p>kafka-console-producer.sh \</p><p>--topic user-state \</p><p>--bootstrap-server localhost:9092 \</p><p>--property parse.key=true \</p><p>--property key.separator=:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*l1c-gfMl412sYAaA.png" /></figure><h3>Why this is beautiful</h3><p>Same log → becomes:</p><ul><li>event stream</li><li>state store</li><li>recovery mechanism</li></ul><h3>Consumers Don’t Delete — They Remember</h3><p>Kafka doesn’t track consumption globally. Consumers track their own <strong>offsets</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YflWp29w19pQBL_H.png" /></figure><h3>Consume from beginning</h3><p>kafka-console-consumer.sh \</p><p>--topic orders \</p><p>--from-beginning \</p><p>--bootstrap-server localhost:9092</p><h3>Reset offset:</h3><p>kafka-consumer-groups.sh \</p><p>--group my-group \</p><p>--topic orders \</p><p>--reset-offsets \</p><p>--to-earliest \</p><p>--execute \</p><p>--bootstrap-server localhost:9092</p><h3>Why this matters</h3><ul><li>replay data anytime</li><li>multiple consumers independently</li><li>rebuild state easily</li></ul><p>Kafka is not a queue.</p><p>It’s a <strong>time-traveling log</strong>.</p><h3>The Deep Insight</h3><p>Kafka is not fast <em>despite</em> persistence.</p><p>👉 Kafka is fast <strong>because of how it persists data</strong>.</p><p>It aligns:</p><ul><li>data model → append-only log</li><li>storage model → sequential disk</li><li>OS behavior → page cache + zero-copy</li></ul><p>Everything works <em>with</em> the system, not against it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/0*pc0DBlMheOOvF58q.png" /></figure><h3>Why Kafka Feels So Elegant</h3><p>Kafka’s beauty is not in individual features. It is in <strong>coherence</strong>.</p><p>One idea:</p><blockquote><em>append-only distributed log</em></blockquote><p>Leads to:</p><ul><li>fast writes</li><li>fast reads</li><li>durability</li><li>replay</li><li>replication</li><li>compaction</li><li>scalability</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hehAYH26N4vHRVe2.png" /></figure><h3>Final Thought</h3><p>Kafka doesn’t try to be clever in many places.</p><p>It is deeply clever in one place.</p><p>And that is enough.</p><blockquote><strong><em>When the core abstraction is right, the system becomes simple, fast, and powerful — all at once.</em></strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4f90736d978" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Kafka City]]></title>
            <link>https://medium.com/@sharpsanjay/the-kafka-city-649ce90976ef?source=rss-f16a028be298------2</link>
            <guid isPermaLink="false">https://medium.com/p/649ce90976ef</guid>
            <category><![CDATA[manager]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[kafka]]></category>
            <dc:creator><![CDATA[Sanjay Mishra]]></dc:creator>
            <pubDate>Thu, 26 Feb 2026 21:12:29 GMT</pubDate>
            <atom:updated>2026-02-26T21:12:29.630Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Living city that stores history.</strong></p><p>Before you visit the city, take a note on some important info:</p><h3>Kafka City — The Complete Reference Map</h3><p>A visual system to understand Kafka like a living city:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nSdODojuiKy5FmUaSpbGjw.png" /><figcaption>Kafka City Map</figcaption></figure><h3>Living Inside Kafka, Part 1: Why Systems Break (And Why Kafka City Exists)</h3><p>Most distributed systems don’t fail because of bad code. They fail because of coordination.</p><blockquote>And coordination is expensive.</blockquote><h3>Before Kafka City: The Growing Town Problem</h3><p>Imagine you’re building a ride-sharing or e-commerce platform. At the beginning, your architecture looks clean:</p><ul><li>API receives an order.</li><li>Database stores it.</li></ul><p>A background worker sends confirmation. Simple town. One road. One building. Few citizens.</p><p>But growth changes everything. Now more teams want “order data”:</p><ul><li>Payments wants to charge the card.</li><li>Fraud wants to score risk.</li><li>Notifications wants to send SMS.</li><li>Analytics wants historical tracking.</li><li>Data Science wants feature pipelines.</li><li>Support wants customer timelines.</li></ul><p>So you integrate.</p><h3>🧶 The Spaghetti Phase</h3><p>The Order Service starts calling everyone.</p><pre>Order → Payment<br>Order → Fraud<br>Order → Notification<br>Order → Analytics<br>Order → CRM<br>Order → Search<br>Order → Data Warehouse</pre><p>What started as a town becomes tangled wiring. The Order Service becomes a <strong>hidden platform</strong>.</p><blockquote>And platforms come with gravity.</blockquote><h3>What Actually Breaks:</h3><p>Let’s analyze this like engineers.</p><p><strong>Release Coupling</strong></p><p>Fraud needs a new field: ip_address. Analytics needs campaign_id. Now Order Service can’t deploy independently. Every change becomes cross-team negotiation.</p><p><strong>Runtime Coupling</strong></p><p>Payment is slow. Should Order:</p><ul><li>Block the user?</li><li>Retry and risk duplicates?</li><li>Drop the call?</li></ul><blockquote>Every integration becomes a reliability decision.</blockquote><p><strong>Scale Coupling</strong></p><p>Analytics launches a backfill job. Suddenly Order Service CPU spikes.</p><blockquote>Traffic increased… but not user traffic.</blockquote><p><strong>Incident Coupling</strong></p><p>An outage happens. Slack explodes:<em>“Is it us or you?” </em>No one knows.</p><blockquote>Because everything is connected.</blockquote><h3>Manager Insight — This Is an Org Problem</h3><p>As an engineering manager, this is the pattern you start recognizing:</p><ul><li>Teams want autonomy.</li><li>Teams want to deploy independently.</li><li>Teams want data without permission.</li><li>Teams want reliability without inheriting everyone else’s outages.</li></ul><p>But your architecture keeps forcing coordination. You can keep adding glue. Or you can change the shape of the system.</p><h4>Enter Kafka City</h4><p>Instead of services calling services… We build a city.</p><p>In Kafka City:</p><ul><li>Producers are factories.</li><li>Events are cars.</li><li>Topics are highways.</li><li>Partitions are traffic-controlled lanes.</li><li>Brokers are buildings storing road segments.</li><li>Consumers are delivery companies.</li><li>Consumer groups are fleets coordinating routes.</li><li>Factories don’t call delivery companies.</li></ul><p>They release cars onto highways. Delivery companies drive independently. Factories don’t care who is listening.</p><h4>The Shift From Calls to Facts:</h4><p>Instead of:</p><pre>Order Service → Payment API<br>Order Service → Fraud API<br>Order Service → Analytics API</pre><p>We move to:</p><pre>🏭 Order Service<br>        │<br>        ▼<br>      🛣 orders-topic<br>        │<br>   ├── 🚚 Payment<br>   ├── 🚚 Fraud<br>   ├── 🚚 Analytics<br>   ├── 🚚 Notifications<br>   └── 🚚 Future Teams (unknown today)</pre><p>The Order Service states a fact:</p><blockquote><em>“OrderCreated”</em></blockquote><p>It doesn’t ask permission. It doesn’t wait. It doesn’t coordinate.</p><h4>The Core Mental Model (Memorize This)</h4><p>Kafka is: <em>A distributed append-only log</em></p><p>Independent readers tracking their own position</p><p>That’s it.</p><p>Everything else — partitions, replication, rebalances — are consequences of that design.</p><h4>Why This Model Changes Everything</h4><p>Producers don’t know consumers exist. -&gt;Loose coupling by design.</p><p>Consumers can be added later -&gt; No code change in producers.</p><p>Consumers can replay history -&gt; Time travel is built-in.</p><p>Failures are survivable -&gt; Replication handles building collapse.</p><p>Teams gain autonomy -&gt; Org scalability improves.</p><p><strong>Tradeoff: Nothing Is Free</strong></p><p>Kafka City introduces its own complexity:</p><ul><li>Partition planning</li><li>Rebalance storms</li><li>Schema evolution</li><li>Retention decisions</li><li>Storage costs</li><li>Operational monitoring</li></ul><p>But it moves complexity from:</p><p>“Hidden coupling” To “Explicit distributed system design.”</p><p>That’s a better trade.</p><h3>Living Inside Kafka — Part 2</h3><h4>The Highways of Kafka City (Kafka Is Just a Log)</h4><p>In Kafka City, factories don’t make phone calls. They release cars onto highways. And those highways never forget. Today, we build the city and walk its roads.</p><h4>What Happens in Kafka City</h4><p>Let’s construct a simple version of the city. We create:</p><ul><li>Three buildings (brokers)</li><li>One highway (orders)</li><li>Three lanes (partitions)</li></ul><p>When a factory produces a car:</p><ul><li>The car enters a specific lane.</li><li>It gets a mile marker (offset).</li><li>It never moves backward.</li><li>It is never edited.</li><li>It is never deleted immediately.</li></ul><p>Highways in Kafka City are:</p><ul><li>Append-only</li><li>Ordered (per lane)</li><li>Durable</li><li>Replicated</li></ul><p>There is no database update. There is only forward motion.</p><h4><strong>What Actually Happens Technically</strong></h4><p>Let’s build this.</p><p><strong>Step 1 — Start Kafka City</strong></p><p>Using the 3-broker Docker Compose setup from Chapter 1:</p><pre>docker compose up -d</pre><p>You now have three brokers:</p><p>kafka1, kafka2, kafka3. Three buildings. One city.</p><p><strong>Step 2 — Create a Highway (Topic)</strong></p><pre>docker exec -it kafka1 kafka-topics.sh \<br>  --bootstrap-server localhost:9092 \<br>  --create \<br>  --topic orders \<br>  --partitions 3 \<br>  --replication-factor 3</pre><p>we just created:</p><pre>🛣 orders<br>   ├── 🚦 Partition 0<br>   ├── 🚦 Partition 1<br>   └── 🚦 Partition 2</pre><p>Each partition is:</p><ul><li>An ordered log</li><li>Stored on one leader broker</li><li>Replicated to two followers</li></ul><p><strong>Step 3 — Release Cars Onto the Highway (Python Producer)</strong></p><p>Install: pip install confluent-kafka</p><p>Producer:</p><pre>from confluent_kafka import Producer<br>import json<br><br>p = Producer({<br>    &#39;bootstrap.servers&#39;: &#39;localhost:9092&#39;,<br>    &#39;acks&#39;: &#39;all&#39;,<br>    &#39;enable.idempotence&#39;: True<br>})<br><br>for i in range(5):<br>    event = {&quot;order_id&quot;: i, &quot;amount&quot;: 100 + i}<br>    p.produce(&quot;orders&quot;, key=str(i), value=json.dumps(event))<br>    p.flush()</pre><p>What just happened?</p><ul><li>Producer sent records.</li><li>Kafka hashed each key.</li><li>Each record went to one partition.</li><li>Offset increased inside that partition.</li></ul><p>Each partition now contains a sequential log:</p><pre>Partition 0:<br>  Offset 0 → {order_id: 0}<br>  Offset 1 → {order_id: 3}<br><br>Partition 1:<br>  Offset 0 → {order_id: 1}<br><br>Partition 2:<br>  Offset 0 → {order_id: 2}<br>  Offset 1 → {order_id: 4}</pre><blockquote>Ordering is guaranteed only inside a partition. This is fundamental.</blockquote><p><strong>The X-Ray Moment — Walk Into the Road</strong></p><p>We look at the actual disk. Going inside broker 1:</p><pre>docker exec -it kafka1 bash<br>cd /tmp/kraft-combined-logs<br>ls<br><br>#And we are seeing:<br>orders-0<br>orders-1<br>orders-2<br>#Enter one:<br>cd orders-0<br>ls<br>#you will see:<br>00000000000000000000.log<br>00000000000000000000.index<br>00000000000000000000.timeindex</pre><p>That .log file is the physical append-only file. Kafka is not magic. It’s writing bytes sequentially to disk. Append-only logs are:</p><ul><li>Extremely fast</li><li>Disk-friendly</li><li>Crash-resilient</li><li>Easy to replicate</li></ul><p>This design choice is why Kafka scales.</p><p><strong>Why Append-Only Changes Everything</strong></p><p>Traditional databases:</p><ul><li>Update rows</li><li>Lock structures</li><li>Rewrite pages</li></ul><p>Kafka:</p><ul><li>Appends</li><li>Flushes</li><li>Moves forward</li></ul><blockquote>Immutability reduces corruption risk. Sequential I/O improves throughput. Replication becomes simpler. This is not accidental. It is intentional distributed systems design.</blockquote><h4>Configurations That Control the Highway</h4><p>These settings define behavior:</p><p><strong>partitions : </strong>Determines parallelism ceiling.</p><p><strong>replication.factor: </strong>Defines durability.</p><p><strong>acks</strong></p><ul><li>0 → fire and forget</li><li>1 → leader only</li><li>all → leader + ISR</li></ul><p><strong>min.insync.replicas : </strong>Minimum replicas required to acknowledge writes.</p><blockquote>Together, these define your reliability contract.</blockquote><p><strong>My experience:</strong></p><p>When you create a topic, you are making three long-term decisions:</p><ol><li>Parallelism Ceiling: Consumers scale only up to partition count.</li><li>Durability Level: Replication factor defines blast radius tolerance.</li><li>Cost Model: More partitions → more file handles, memory, network overhead.</li></ol><p>Changing these later is possible… but painful. Plan for 2–3 years, not 2–3 weeks.</p><h3>Production Checklist — Before Creating Any Topic</h3><p>Before running: kafka-topics.sh — create</p><p>Ask:</p><ul><li>What team owns this topic?</li><li>What is the expected throughput?</li><li>What is the retention requirement?</li><li>What happens if one broker dies?</li><li>Is schema evolution planned?</li></ul><blockquote>Kafka problems in production rarely start with brokers. They start with careless topic creation.</blockquote><h4>The Deeper Realization</h4><p>Kafka is not a queue. Queues remove messages. Kafka preserves history. Consumers don’t remove cars from the road. They just remember:</p><blockquote><em>“We’ve delivered up to mile marker 42.”</em></blockquote><p>That one design decision enables:</p><ul><li>Replay</li><li>Auditing</li><li>Backfills</li><li>New services without touching producers</li></ul><p>It is architectural leverage.</p><p>Kafka = Append-only log with Partitioned lane, Replication and Independent consumers. Everything else is built on top of that.</p><p>In Kafka City:</p><ul><li>Roads are permanent.</li><li>Cars are immutable.</li><li>Delivery companies are replaceable.</li><li>Buildings can fail.</li><li>The city survives.</li></ul><p>That is why Kafka scales technically. And why it scales organizationally.</p><h3>Living Inside Kafka — Part 3</h3><h3>Traffic Engineering — Partitions, Keys, and Permanent Traffic Jams</h3><p>In Kafka City, highways don’t magically balance traffic. They follow strict routing rules. And if you misunderstand those rules, you don’t get errors. You get traffic jams.</p><h4>What Happens in Kafka City</h4><p>We already built a highway:</p><pre>🛣 orders<br>   ├── 🚦 Lane 0<br>   ├── 🚦 Lane 1<br>   └── 🚦 Lane 2</pre><p>Now the question becomes:</p><blockquote><em>When a factory releases a car, which lane does it enter?</em></blockquote><p>The answer: Kafka computes:</p><pre>hash(key) % number_of_partitions</pre><p>Cars with the same license plate (key) always enter the same lane.</p><blockquote>Why? Because Kafka guarantees order <strong>within a partition</strong>. Not across the entire topic.</blockquote><h4>The Golden Rule of Kafka City</h4><p>Ordering exists only inside a lane. If you need strict ordering for:</p><ul><li>A user</li><li>A bank account</li><li>An order</li><li>A session</li></ul><p>All events for that entity must share the same key.</p><p>Otherwise… You break causality.</p><h4>What Actually Happens Technically</h4><p>Let’s demonstrate.</p><p><strong>Step 1 — Send Events With Same Key</strong></p><p>Modify your producer:</p><pre>from confluent_kafka import Producer<br>import json<br>p = Producer({&#39;bootstrap.servers&#39;: &#39;localhost:9092&#39;})<br>for i in range(5):<br>    event = {&quot;customer_id&quot;: &quot;123&quot;, &quot;step&quot;: i}<br>    p.produce(&quot;orders&quot;, key=&quot;123&quot;, value=json.dumps(event))<br>    p.flush()</pre><p>All messages go to the same partition.</p><p>Describe the topic:</p><pre>docker exec -it kafka1 kafka-topics.sh \<br>  --bootstrap-server localhost:9092 \<br>  --describe --topic orders</pre><p>Then consume and observe:</p><pre>Offset 0 → step 0<br>Offset 1 → step 1<br>Offset 2 → step 2<br>Offset 3 → step 3<br>Offset 4 → step 4</pre><p>Perfect ordering. Now remove the key.</p><pre>p.produce(&quot;orders&quot;, value=json.dumps(event))</pre><p>Now Kafka uses round-robin partitioning.</p><p>Events spread across partitions.</p><p>Ordering is gone globally.</p><h4><strong>What People Get Wrong</strong></h4><p>They assume:</p><p>Kafka guarantees ordering<em>. </em>It doesn’t.</p><blockquote>It guarantees ordering per partition. This is not a small nuance. This is architectural gravity.</blockquote><h3>Partition Count — Your Parallelism Ceiling</h3><p>Consumer groups scale up to the number of partitions.</p><p>If you have:</p><ul><li>3 partitions and 10 consumers</li></ul><p>Only 3 consumers will actively process.</p><p>7 will sit idle. Partition count = maximum parallelism.</p><p>You cannot exceed it without recreating the topic.</p><p>That’s why partition planning matters.</p><h3>🧨 The Hot Partition Problem</h3><p>Let’s simulate a bad key.</p><p>Imagine:</p><p>90% of traffic belongs to one customer. You key by customer_id.</p><p>What happens?</p><pre>🛣 orders<br>   ├── Lane 0 → 🚗🚗🚗🚗🚗🚗🚗🚗🚗🚗🚗🚗🚗🚗🚗 (traffic jam)<br>   ├── Lane 1 → 🚗<br>   └── Lane 2 → 🚗</pre><p>One partition becomes overloaded.</p><p>Symptoms:</p><ul><li>Increased consumer lag</li><li>Uneven CPU across brokers</li><li>Leader broker under heavy load</li><li>Throughput collapse</li></ul><p>And Kafka won’t warn you.</p><p>Because technically… everything is working.</p><h4>Why Hot Partitions Are Dangerous</h4><p>Hot partitions create:</p><ul><li>Uneven load</li><li>Slow processing</li><li>Rebalance instability</li><li>Broker pressure</li><li>Disk I/O skew</li></ul><blockquote>And scaling hardware doesn’t fix bad key design. This is a data distribution problem, not a CPU problem.</blockquote><h4>Configuration &amp; Design Decisions</h4><p><strong>Choosing the Right Key</strong></p><p>Ask: What requires ordering?</p><p>Examples:</p><p><strong>Use Case -&gt; Good Key</strong></p><p>Orders -&gt; order_id</p><p>Bank Transactions -&gt;account_id</p><p>User Activity -&gt; user_id</p><p>Ride Tracking → ride_id</p><p>Bad key choices:</p><ul><li>Constant string (everything in one partition)</li><li>Timestamp (no grouping)</li><li>Random UUID when ordering matters</li></ul><h4>Choosing Partition Count</h4><p>Guidelines (not rules):</p><ul><li>Estimate max throughput.</li><li>Estimate consumer parallelism.</li><li>Multiply expected growth.</li><li>Add buffer.</li></ul><p>Example:</p><p>If you expect:</p><p>6 consumers today, 12 next year. -&gt; Create at least 12–24 partitions.</p><blockquote>Partitions are cheap initially. Painful later.</blockquote><h4>Increasing Partitions Later</h4><p>You <em>can</em> increase partition count.</p><p>But:</p><ul><li>Existing keys won’t redistribute.</li><li>New messages will use new partition mapping.</li><li>Ordering across old and new partitions breaks.</li></ul><p>That’s why initial design matters.</p><h4>My Lesson — Traffic Engineering Is Leadership</h4><p>Partition strategy is not an engineering afterthought.</p><p>It impacts:</p><ul><li>Team scaling</li><li>Incident frequency</li><li>Cost</li><li>Throughput ceiling</li><li>Deployment stability</li></ul><blockquote>Partition planning is capacity planning. Capacity planning is business planning.</blockquote><h4>Production Checklist — Before Choosing Keys</h4><p>Before finalizing a key:</p><ul><li>What entity requires strict ordering?</li><li>Can traffic distribution be skewed?</li><li>What is worst-case traffic concentration?</li><li>Do we expect “celebrity users” or power customers?</li><li>Are we optimizing for throughput or strict causality?</li></ul><p>Tradeoffs must be explicit.</p><h4>A Realistic Scenario — Payment Processing</h4><p>Imagine: You process payments.</p><p>You key by customer_id.</p><p>One enterprise customer sends 50% of all payments.</p><p>You just created a permanent traffic jam.</p><p>Alternative:</p><p>Key by payment_id.</p><p>But then ordering per customer is lost.</p><p>Now you must decide:</p><blockquote>Throughput vs strict per-customer order. That’s not a Kafka decision. That’s a business decision.</blockquote><h4>The Deep Insight</h4><p>Partitioning is not about performance. It’s about data distribution guarantees. Keys define traffic shape. Traffic shape defines system stability.</p><p>Kafka does exactly what you tell it to do. Good systems require deliberate routing.</p><h4>Reflection</h4><p>In Kafka City:</p><ul><li>Lanes define parallelism.</li><li>Keys define traffic routing.</li><li>Traffic routing defines stability.</li><li>Stability defines sleep quality.</li></ul><blockquote>The biggest Kafka outages don’t come from broker crashes. They come from bad partition strategy.</blockquote><h3>Living Inside Kafka — Part 4</h3><h4>Consumer Groups &amp; The Rebalance Storm</h4><p>In Kafka City, factories produce cars. Highways store them forever. But someone has to deliver them. And delivery… requires coordination. Welcome to the most misunderstood part of Kafka:</p><p><strong>Consumer Groups.</strong></p><h4>What Happens in Kafka City</h4><p>Imagine a highway with 3 lanes:</p><pre>🛣 orders<br>   ├── 🚦 Lane 0<br>   ├── 🚦 Lane 1<br>   └── 🚦 Lane 2</pre><p>Now a delivery company arrives with one truck:</p><pre>👥 payment-group<br>   └── 🚚 Truck A</pre><p>Truck A handles all lanes. Now the company grows. They hire two more trucks.</p><pre>👥 payment-group<br>   ├── 🚚 Truck A<br>   ├── 🚚 Truck B<br>   └── 🚚 Truck C</pre><p>Kafka City must assign lanes.</p><p>Rule:</p><blockquote><em>Each partition can be consumed by only one consumer within a group.</em></blockquote><p>So Kafka distributes:</p><pre>Truck A → Lane 0<br>Truck B → Lane 1<br>Truck C → Lane 2</pre><p>Parallelism achieved.</p><p>But here’s where things get interesting.</p><h4>The City Election (Rebalance) if:</h4><ul><li>A truck joins</li><li>A truck leaves</li><li>A truck crashes</li><li>A new lane is added</li><li>A deployment restarts consumers</li></ul><p>Kafka triggers a <strong>rebalance</strong>.</p><p>What happens during rebalance?</p><ol><li>All trucks pause.</li><li>The coordinator reassigns lanes.</li><li>Trucks resume.</li></ol><p>Processing freezes temporarily. That’s the storm.</p><h4>What Actually Happens Technically</h4><p>Let’s observe it.</p><h4>Step 1 — Create a Consumer</h4><pre>from confluent_kafka import Consumer<br>c = Consumer({<br>    &#39;bootstrap.servers&#39;: &#39;localhost:9092&#39;,<br>    &#39;group.id&#39;: &#39;payment-group&#39;,<br>    &#39;auto.offset.reset&#39;: &#39;earliest&#39;<br>})<br>c.subscribe([&#39;orders&#39;])<br>while True:<br>    msg = c.poll(1.0)<br>    if msg:<br>        print(f&quot;Consumed from {msg.partition()}: {msg.value().decode()}&quot;)</pre><p>Start one instance.</p><p>It consumes all partitions.</p><h4>Step 2 — Start a Second Consumer</h4><p>Run the same script again in another terminal.</p><p>Observe logs.</p><p>You’ll see something like:</p><pre>% Rebalance triggered<br>Assigned partitions: [1]</pre><p>The partitions are redistributed.</p><p>Now:</p><p>Consumer 1 → Partition 0</p><p>Consumer 2 → Partition 1</p><p>(Partition 2 assigned depending on assignment strategy)</p><h4>Step 3 — Kill One Consumer</h4><p>Terminate one instance.</p><p>Watch the other. You’ll see:</p><pre>% Rebalance triggered<br>Assigned partitions: [0,1,2]</pre><p>During this time: Processing pauses. That pause is often milliseconds.</p><p>But under load or instability… It becomes seconds. Sometimes longer.</p><h4>Why Rebalances Exist</h4><p>Kafka must guarantee:</p><ul><li>No partition is processed by two consumers in the same group.</li><li>Offset ownership is clean.</li><li>Processing resumes safely.</li></ul><p>To achieve this:</p><p>Kafka uses a <strong>group coordinator</strong> (a broker).</p><p>The coordinator:</p><ul><li>Tracks group membership.</li><li>Assigns partitions.</li><li>Commits offsets.</li><li>Detects failed members.</li></ul><p>This is distributed coordination.</p><p>Not just streaming.</p><h4>🧨 The Rebalance Storm Problem</h4><p>In production, rebalances happen because:</p><ul><li>Rolling deployments restart pods.</li><li>Kubernetes reschedules containers.</li><li>GC pauses exceed session timeout.</li><li>Network blips cause heartbeats to fail.</li><li>Autoscaling adds/removes instances.</li></ul><p>If these happen frequently…</p><p>You get “<em>Rebalance Storm”</em></p><p>Symptoms:</p><ul><li>Consumer lag spikes</li><li>CPU idle time increases</li><li>Throughput drops</li><li>Logs flooded with assignment messages</li><li>SLA violations</li></ul><blockquote>Kafka is working correctly. Your deployment strategy isn’t.</blockquote><h4>Configurations That Control the Storm</h4><p>These configs matter deeply:</p><h4>session.timeout.ms</h4><p>How long the coordinator waits before declaring a consumer dead.</p><p>Lower value:</p><ul><li>Faster failure detection</li><li>More sensitive to blips</li></ul><p>Higher value:</p><ul><li>More stable</li><li>Slower recovery</li></ul><h4>heartbeat.interval.ms</h4><p>How often consumer sends heartbeat.</p><p>Too large → delayed failure detection</p><p>Too small → more network chatter</p><h4>max.poll.interval.ms</h4><p>If consumer doesn’t call poll within this time → removed from group.</p><p>Common failure mode:</p><ul><li>Heavy processing</li><li>No polling</li><li>Consumer kicked out</li><li>Rebalance triggered</li></ul><h4>Assignment Strategy</h4><p>Kafka supports:</p><ul><li>Range assignor</li><li>Round-robin assignor</li><li>Cooperative sticky assignor (modern, reduces stop-the-world)</li></ul><p>Cooperative rebalancing reduces disruption. Use it.</p><h4>My Lesson — Deployments Cause Elections</h4><blockquote>Rebalances are not Kafka failures. They are system coordination events.</blockquote><p>If your team:</p><ul><li>Deploys 10 pods at once</li><li>Uses aggressive liveness probes</li><li>Sets short timeouts</li><li>Has long processing per message</li></ul><p>You are creating instability.</p><h4>Better Deployment Strategy</h4><ul><li>Use rolling updates (one instance at a time).</li><li>Increase session timeout slightly.</li><li>Ensure poll loop is frequent.</li><li>Offload heavy processing to worker threads.</li><li>Use cooperative assignor.</li></ul><p>Operational maturity lives here.</p><h4>Production Checklist — Before Scaling Consumers</h4><p>Before increasing consumer replicas:</p><ul><li>How many partitions exist?</li><li>Is assignment strategy cooperative?</li><li>What is average rebalance duration?</li><li>Are timeouts tuned?</li><li>Is lag monitored?</li><li>Does processing block poll loop?</li></ul><p>Consumer group instability causes more outages than broker crashes.</p><h4>A Real Incident Story (Common Pattern)</h4><p>Team scales consumer from 3 → 10 replicas.</p><p>Partitions = 3.</p><p>Result:</p><ul><li>Only 3 active consumers.</li><li>7 idle.</li><li>Deployment restarts all at once.</li><li>Multiple rebalances.</li><li>Lag spikes.</li><li>Alerts trigger.</li><li>Team blames Kafka.</li></ul><p>Root cause? Mismatch between partition count and scaling strategy. Kafka behaved correctly. System design did not.</p><h4>Deep Insight</h4><p>Kafka is not just:</p><ul><li>Log storage</li><li>Partitioned scaling</li></ul><p>It is also:</p><ul><li>Distributed group coordination</li></ul><p>Consumer groups are mini distributed systems. They require operational discipline.</p><h4>End-of-Chapter Reflection</h4><p>In Kafka City:</p><ul><li>Trucks coordinate routes.</li><li>Elections pause traffic.</li><li>Too many elections cause gridlock.</li><li>Stability depends on timing and discipline.</li></ul><blockquote>Rebalances are not bugs. They are governance.</blockquote><p>This is where Kafka City becomes real infrastructure.</p><p>Up until now, we built highways and coordinated trucks.</p><p>Now we test whether the city survives when a building collapses.</p><p>Because in distributed systems:</p><blockquote><em>Failure is not an edge case.</em></blockquote><blockquote><em>It is a design requirement.</em></blockquote><p>Let’s build this properly.</p><h3>Living Inside Kafka — Part 5</h3><h3>Replication, Failures &amp; Surviving Building Collapse</h3><p>In Kafka City:</p><ul><li>Buildings store roads.</li><li>Traffic controllers manage lanes.</li><li>Cars keep moving.</li></ul><p>But buildings can burn down.</p><p>What matters is: Does the city survive?</p><h3>1️⃣ 🏙 What Happens in Kafka City</h3><p>When we created our topic:</p><pre>--replication-factor 3</pre><p>We told Kafka City:</p><blockquote><em>Every lane must exist in 3 buildings.</em></blockquote><p>For each partition:</p><ul><li>One broker is the <strong>Leader</strong> 🚦</li><li>Two brokers are <strong>Followers</strong> 🔁</li><li>All replicas that are fully caught up form the <strong>ISR</strong> (In-Sync Replicas)</li></ul><p>Example:</p><pre>🛣 orders – Partition 0<br>   Leader → 🏢 Broker 1<br>   Follower → 🏢 Broker 2<br>   Follower → 🏢 Broker 3</pre><p>All writes go to the leader.</p><p>Followers replicate the data.</p><p>If Broker 1 dies?</p><p>A follower becomes leader.</p><p>Traffic continues.</p><h4>What Actually Happens Technically</h4><p>Let’s see it.</p><p><strong>Step 1 — Describe the Topic</strong></p><pre>docker exec -it kafka1 kafka-topics.sh \<br>  --bootstrap-server localhost:9092 \<br>  --describe --topic orders</pre><p>You’ll see something like:</p><pre>Partition: 0<br>Leader: 1<br>Replicas: 1,2,3<br>ISR: 1,2,3</pre><p>Leader handles reads/writes.</p><p>ISR are eligible to become leader.</p><h4>Step 2 — Simulate Building Collapse</h4><p>Stop Broker 1:</p><pre>docker stop kafka1</pre><p>Wait a few seconds.</p><p>Now describe topic from another broker:</p><pre>docker exec -it kafka2 kafka-topics.sh \<br>  --bootstrap-server localhost:9094 \<br>  --describe --topic orders</pre><p>You’ll see leadership change:</p><pre>Partition: 0<br>Leader: 2<br>Replicas: 1,2,3<br>ISR: 2,3</pre><p>Broker 2 took over.</p><p>The city survived.</p><h4>🧠 How Leader Election Works</h4><p>When a broker fails:</p><ol><li>Controller detects failure.</li><li>For each affected partition: Pick a new leader from ISR.</li><li>Update metadata.</li><li>Producers/consumers reconnect automatically.</li></ol><p>Key rule:</p><blockquote><em>Only replicas in ISR can become leader.</em></blockquote><p>If ISR shrinks too much… You risk losing durability guarantees.</p><h4>🧨 When Things Go Wrong</h4><p>Now let’s simulate something more dangerous.</p><p>Suppose:</p><ul><li>Replication factor = 3</li><li>min.insync.replicas = 2</li><li>acks=all</li></ul><p>This means: A write succeeds only if:</p><ul><li>Leader</li><li>at least 1 follower</li></ul><p>Acknowledge the write. Now kill two brokers.</p><pre>docker stop kafka1<br>docker stop kafka2</pre><p>Only one broker remains. What happens? Producers start failing with errors like:</p><pre>NOT_ENOUGH_REPLICAS</pre><p>Why? Because Kafka refuses to accept writes that would violate durability policy.</p><p>This is not a bug. It’s your reliability contract being enforced.</p><h4>The Reliability Control Panel</h4><p>These four settings define your failure posture:</p><h4>Replication Factor</h4><p>How many copies exist.</p><ul><li>RF=1 → no redundancy</li><li>RF=3 → standard production</li><li>RF=5 → high durability environments</li></ul><h4>min.insync.replicas</h4><p>Minimum replicas that must acknowledge a write.</p><p>If set to 2 (with RF=3):</p><ul><li>One failure tolerated.</li><li>Two failures block writes.</li></ul><h4>acks</h4><p>Producer-side durability control:</p><ul><li>acks=0 → fire and forget</li><li>acks=1 → leader only</li><li>acks=all → wait for ISR</li></ul><p>Best practice in production:</p><pre>acks=&#39;all&#39;<br>enable.idempotence=True</pre><h4>Unclean Leader Election</h4><p>Kafka can allow:</p><ul><li>Non-ISR replicas to become leader.</li></ul><p>This improves availability.</p><p>But risks data loss. Default in modern Kafka: disabled. Good. Because silent data loss is worse than downtime.</p><h4>The Durability vs Availability Tradeoff</h4><p>This is the CAP tension in Kafka City.</p><p>If you prioritize availability:</p><ul><li>Lower min.insync.replicas</li><li>Allow unclean elections</li></ul><p>If you prioritize durability:</p><ul><li>Require ISR quorum</li><li>Block writes when unsafe</li></ul><p>Neither is universally correct.</p><p>It depends on the business.</p><h4>My Lesson — Define Your Failure Philosophy</h4><p>Ask leadership: If one building burns down:</p><ul><li>Should traffic continue at all cost?</li><li>Or should we block to prevent data loss?</li></ul><p>Examples:</p><p><strong>Use Case. -&gt; Tolerance</strong></p><p>Ad click events -&gt; Small loss acceptable</p><p>Financial transactions -&gt; Zero loss required</p><p>Audit logs -&gt; Zero loss required</p><p>Metrics aggregation -&gt; Some loss tolerable</p><blockquote>Infrastructure settings must align with business risk tolerance. Not engineer preference.</blockquote><h4>Production Checklist — Before Going Live</h4><p>Before running Kafka in production:</p><ul><li>Replication factor ≥ 3?</li><li>min.insync.replicas ≥ 2?</li><li>acks=all enforced?</li><li>Idempotent producer enabled?</li><li>Unclean leader election disabled?</li><li>Broker distribution across failure zones?</li><li>Disk monitoring in place?</li></ul><p>Broker failure is not rare. Disks fail. Nodes reboot. Cloud instances disappear.</p><p>Your system must expect collapse.</p><h4>A More Subtle Failure: ISR Shrinking</h4><p>Even without full broker death: If followers fall behind (network lag, slow disk): They drop out of ISR.</p><p>Now:</p><pre>ISR: 1,2</pre><p>If one more falls behind:</p><pre>ISR: 1</pre><p>Now writes with acks=all may fail. Monitoring ISR size is critical. Most teams forget this.</p><h4>The Deep Insight</h4><p>Replication is not about copying data.</p><p>It is about:</p><ul><li>Preserving ordering</li><li>Maintaining quorum</li><li>Enforcing durability contracts</li></ul><p>Kafka’s fault tolerance is built on:</p><p>Leader election + ISR quorum + strict append-only logs. This is why it works.</p><h4>End-of-Chapter Reflection</h4><p>In Kafka City:</p><ul><li>Buildings collapse.</li><li>Traffic controllers are replaced.</li><li>Roads remain.</li><li>Cars are preserved.</li><li>The city continues.</li></ul><blockquote>Unless you chose weak policies. Kafka doesn’t decide your reliability. You do.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=649ce90976ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TCP/IP: Timeless, the Silent Hero of Scalability]]></title>
            <link>https://medium.com/@sharpsanjay/tcp-ip-timeless-the-silent-hero-of-scalability-dbc68633de49?source=rss-f16a028be298------2</link>
            <guid isPermaLink="false">https://medium.com/p/dbc68633de49</guid>
            <category><![CDATA[tcp1p]]></category>
            <category><![CDATA[linux-kernel]]></category>
            <category><![CDATA[system-performance]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[scalability]]></category>
            <dc:creator><![CDATA[Sanjay Mishra]]></dc:creator>
            <pubDate>Sat, 06 Sep 2025 17:48:34 GMT</pubDate>
            <atom:updated>2025-09-06T17:48:34.834Z</atom:updated>
            <content:encoded><![CDATA[<p>We often debate the scalability of distributed systems — whether Kafka can handle millions of messages per second, how Cassandra scales across clusters, or how fast modern APIs can respond. But beneath all this engineering complexity, there’s a silent constant we rarely worry about: TCP/IP.</p><p>No matter how large the system, TCP is rarely the bottleneck. It’s quietly moving packets, reliably, securely, at a scale that dwarfs most application-layer concerns.</p><p>That’s remarkable when you realize TCP/IP was designed 40+ years ago. Unlike most software that gets rewritten every few years, TCP/IP has stood the test of time. It’s still the foundation of the internet today — and thanks to Linux, it’s faster and more reliable than ever.</p><h3>Robust, Simple, Extensible — the holy trinity of timeless design.</h3><p>Simplicity, TCP/IP is simple enough to be universally implemented, yet powerful enough to cover almost every networking use case.</p><p>Compatibility first, A packet from the 1980s could, in theory, still be understood today. Backward compatibility gave TCP/IP an unusually long lifespan.</p><p>Separation of concerns IP moves packets. TCP ensures reliable delivery, ordering, and retransmissions. This modularity made the system flexible and maintainable.</p><p>Extensibility: Features like congestion control were layered on top without rewriting the protocol.</p><h3>How Linux Gave TCP/IP Wings:</h3><p>Linux adopted TCP/IP early, and today over 90% of servers on the internet run Linux. But it’s not just adoption — Linux engineers have spent decades making the stack <em>blazingly fast</em>.</p><h3>1. The Ring Buffer</h3><p>Packets are received in a circular buffer in kernel memory. This avoids dynamic allocation on every packet and ensures constant-time access. A simple head and tail pointer decide where to put incoming data — no fragmentation, no chasing memory.</p><p>It’s literally just an array with two pointers:</p><ul><li>head → where the next packet (or byte) will be written</li><li>tail → where the next packet (or byte) will be read</li></ul><p>When the head reaches the end of the array, it wraps back to the beginning — hence “circular.”</p><pre>struct ring_buffer {<br>    char data[N];   // fixed-size array<br>    int head;       // next write position<br>    int tail;       // next read position<br>};</pre><p>Enqueueing is just:</p><pre>data[head] = value;<br>head = (head + 1) % N;</pre><p>Dequeueing is just:</p><pre>value = data[tail];<br>tail = (tail + 1) % N;</pre><p>That’s it. O(1) time, O(1) space overhead, lock-free in many cases.</p><h3>2. Zero-Copy Networking</h3><p>Normally, moving packets means lots of copying: NIC → kernel → user space. Linux avoids this with zero-copy, mapping kernel buffers directly into user space. This is how you get line-rate throughput with minimal CPU usage (e.g., sendfile()).</p><h3>3. NAPI (New API)</h3><p>Instead of interrupting the CPU on every packet, Linux uses polling under high load. This prevents “interrupt storms” at high packet rates, making networking scale better.</p><h3>4. io_uring &amp; XDP</h3><p>Modern additions like io_uring and eXpress Data Path (XDP) push the limits further, allowing applications to bypass parts of the kernel stack for ultra-low latency processing.</p><h3>Story of TCP is motivating:</h3><p>TCP/IP’s story is more than history — it’s a blueprint for building software that lasts decades. What can we learn?</p><ol><li>Keep it simple at the core</li><li>Prioritize compatibility</li><li>Separate concerns</li><li>Engineer for performance from day one</li></ol><p>TCP’s “three-way handshake” was proposed in 1974 — and is still how your browser connects today. Every time you run ssh, curl, or stream Netflix, you’re standing on 40-year-old engineering foundations. Google, Meta, and AWS still tweak TCP congestion control algorithms today — meaning TCP is still evolving, not obsolete.</p><p>When we talk about scalability, we often look at the shiny new tools — Kafka, Cassandra, Kubernetes. But the real hero is the protocol stack beneath them. TCP/IP is timeless — a rare example of software engineering excellence that has lasted generations.</p><p>And if there’s one lesson modern engineers should take from it: design your systems to be simple, compatible, and extensible. Do that well enough, and your software could still be running 40 years from now.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dbc68633de49" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Physics Class to Code Chaos: How the Second Law of Thermodynamics Applies to Software]]></title>
            <link>https://medium.com/@sharpsanjay/from-physics-class-to-code-chaos-how-the-second-law-of-thermodynamics-applies-to-software-c357838b0adb?source=rss-f16a028be298------2</link>
            <guid isPermaLink="false">https://medium.com/p/c357838b0adb</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[behappyinyourwork]]></category>
            <category><![CDATA[codefun]]></category>
            <category><![CDATA[engineering]]></category>
            <dc:creator><![CDATA[Sanjay Mishra]]></dc:creator>
            <pubDate>Wed, 09 Apr 2025 02:15:58 GMT</pubDate>
            <atom:updated>2025-04-09T02:15:58.299Z</atom:updated>
            <content:encoded><![CDATA[<p>I studied physics back in school, and one law has stuck with me ever since:</p><blockquote><strong><em>The Second Law of Thermodynamics</em></strong><em> — in any closed system, things tend toward disorder (entropy) over time.</em></blockquote><blockquote>Fast forward to today — I’m a software engineer. And guess what?<br> This law applies <em>everywhere</em> in tech too.</blockquote><p>Let me explain.</p><p><strong>What Is Entropy?</strong></p><p>In physics, entropy is a measure of disorder. Over time, systems break down unless you constantly put in energy to keep them organized.</p><ul><li>Ice melts.</li><li>Rooms get messy.</li><li>Toast doesn’t un-burn.</li></ul><p>And yes — <strong>codebases rot.</strong></p><h3>Software Has Its Own Flavor of Entropy</h3><p>Ever opened an old project and asked, “Who wrote this garbage?”<br> (Only to realize… it was you?)</p><p>That’s entropy in action. Here’s how it shows up in our work:</p><p>Physics World Software World Disorder increases over time Code becomes harder to maintain Energy needed to fight it Refactoring, testing, reviews Time flows one-way Git history, logs, backups</p><h3>What About Data?</h3><p>Same story</p><ul><li>Schemas drift</li><li>Data gets duplicated or lost</li><li>File names like final_final_v3.csv pop up</li><li>Pipelines become unmanageable</li></ul><p>Without attention, your nice data lake becomes a data swamp.</p><h3>️How We Fight Entropy</h3><p>We can’t stop entropy, but we can manage it:</p><p>Refactor regularly<br>Keep docs up to date<br>Write tests<br>Automate where possible<br>Monitor systems<br>Share knowledge</p><p>It’s like tidying up before the mess gets out of hand.</p><h3>My Realization</h3><p>I used to think thermodynamics was only for physicists.<br> Now I see it <strong>everywhere</strong> — in tech, in teams, in data.</p><p>Entropy explains why things break, why bugs show up, why legacy code becomes a nightmare.</p><p>So the next time your code feels like chaos, remember —</p><blockquote><em>It’s not (just) you. It’s physics. 😄</em></blockquote><blockquote>Thanks for reading! Let me know if you’ve seen entropy creeping into your projects too. I might explore how <strong>information theory</strong> connects to this next.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c357838b0adb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Python is the Best First Programming Language?]]></title>
            <link>https://medium.com/@sharpsanjay/why-python-is-the-best-first-programming-language-9abef1b3920e?source=rss-f16a028be298------2</link>
            <guid isPermaLink="false">https://medium.com/p/9abef1b3920e</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[learning-and-development]]></category>
            <dc:creator><![CDATA[Sanjay Mishra]]></dc:creator>
            <pubDate>Sat, 01 Feb 2025 17:27:47 GMT</pubDate>
            <atom:updated>2025-02-01T17:27:47.775Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why Even Learn to Code?</h3><p>Let’s be honest — learning to code can feel <strong>overwhelming</strong> at first. There are so many programming languages out there, each with its own rules and complexities. But what if I told you there’s one language that’s so easy that even kids can learn it, yet powerful enough to run apps at <strong>Google, Netflix, and NASA</strong>?</p><p>That language is <strong>Python</strong>!</p><p>Whether you want to <strong>build websites, analyze data, automate tasks, or even create AI</strong>, Python is the <strong>perfect</strong> place to start. In this post, I’ll break down why Python is the best first programming language, and by the end, you’ll be <strong>excited to start coding today!</strong></p><h3>1️. Python is Ridiculously Easy to Learn</h3><p>Ever looked at code and thought, <strong>“This looks like gibberish!”</strong>? Well, Python is different. It’s designed to be <strong>readable, beginner-friendly, and super intuitive</strong>.</p><p>Let’s compare Python with another popular language, Java.</p><h3>How to Print “Hello, World!” in Python vs. Java</h3><p><strong>Python:</strong></p><p>print(&quot;Hello, World!&quot;)</p><p><strong>Java</strong></p><p>public class HelloWorld {<br> public static void main(String[] args) {<br> System.out.println(&quot;Hello, World!&quot;);<br> }<br>}</p><p>Python’s version is <strong>one simple line</strong>, while Java’s version looks <strong>complicated for no reason</strong>. This is why so many beginners love Python — it just makes sense!</p><h3>2️. It Has a Massive Supportive Community</h3><p>One of the biggest struggles when learning to code is <strong>getting stuck</strong>. But the good news? <strong>Python has one of the largest programming communities in the world!</strong></p><p>&gt;Need help? Ask on <strong>Stack Overflow</strong> and get answers in minutes.<br>&gt;Tons of <strong>free Python courses on YouTube, Coursera, and Udemy</strong>.<br>&gt;Active Python groups on <strong>Reddit, Discord, and Twitter (X)</strong> where you can meet fellow learners.</p><p>Basically, if you ever hit a roadblock, you’re <strong>never alone!</strong></p><h3>3️. Python is Everywhere — Literally!</h3><p>You might be wondering, <strong>“Okay, Python is easy… but what can I actually do with it?”</strong></p><p>The answer? <strong>Almost anything!</strong> Python is used in:</p><p><strong>&gt; Web Development</strong> — Build sites with <strong>Django &amp; Flask</strong>.<br>&gt; <strong>Data Science</strong> — Analyze data with <strong>Pandas &amp; NumPy</strong>.<br>&gt;<strong>AI &amp; Machine Learning</strong> — Train models with <strong>Scikit-Learn &amp; TensorFlow</strong>.<br>&gt; <strong>App Development</strong> — Create apps with <strong>Kivy &amp; PyQt</strong>.<br>&gt; <strong>Game Development</strong> — Make games with <strong>Pygame</strong>.</p><p><strong>Fun Fact:</strong> Instagram, Spotify, Uber, and even NASA use Python in their systems!</p><h3>4️. You Can Automate Boring Tasks! 🤖</h3><p>Ever felt <strong>frustrated doing repetitive tasks</strong>? Python can help <strong>automate</strong> things and save <strong>hours</strong> of work!</p><p>&gt; Rename <strong>hundreds of files</strong> in seconds.<br>&gt; Scrape <strong>data from websites</strong> automatically.<br>&gt; Write a bot that <strong>auto-sends emails &amp; reminders</strong>.</p><p>Here’s a <strong>fun little Python script</strong> that lets you create a simple <strong>To-Do List App</strong>:</p><p>tasks = []<br>while True:<br> task = input(&quot;Enter a task (or type &#39;exit&#39; to stop): &quot;)<br> if task.lower() == &#39;exit&#39;:<br> break<br> tasks.append(task)</p><p>print(&quot;\nYour To-Do List:&quot;)<br>for i, task in enumerate(tasks, 1):<br> print(f&quot;{i}. {task}&quot;)</p><p>Try it out! You can <strong>modify</strong> it to mark tasks as “done” or save them in a file.</p><h3>5️. Python Can Land You a High-Paying Job</h3><p>Let’s talk career opportunities. Python isn’t just fun — it’s also one of the <strong>highest-paying skills</strong> in tech!</p><p>👨‍💻 <strong>Software Developer</strong> → $80K — $150K/year<br>📊 <strong>Data Scientist</strong> → $100K — $180K/year<br>🤖 <strong>AI/Machine Learning Engineer</strong> → $120K — $200K/year</p><p>And the best part? You don’t <strong>need a CS degree</strong> to get started! Many companies <strong>just want proof that you can code</strong>, so learning Python + building projects = <strong>job-ready skills!</strong></p><h3>How to Start Learning Python Today?</h3><p>Excited? Here’s what to do next:</p><p>1.️ <strong>Download Python</strong> <a href="https://www.python.org/">Python.org</a><br>2. <strong>Follow a Free Course</strong> <a href="https://automatetheboringstuff.com/">Automate the Boring Stuff</a><br>3. <strong>Build Fun Projects</strong> — Start small, then scale up!<br>4. <strong>Join a Python Community</strong> — Meet other learners on <strong>Reddit, Discord, and Twitter</strong>.</p><p>And if you’re looking for <strong>more beginner-friendly Python tutorials</strong>, I’ll be sharing <strong>more blogs and YouTube videos</strong> soon — so stay tuned!</p><h3>Final Thoughts: Why Python?</h3><p>✔ <strong>Easy to learn, but super powerful</strong><br>✔ <strong>Huge community &amp; endless learning resources</strong><br>✔ <strong>Used in Web Dev, AI, Data Science, and more</strong><br>✔ <strong>You can automate tasks &amp; build real-world projects</strong></p><p>So, what’s stopping you? <strong>Start learning Python today!</strong></p><p><strong>What excites you the most about Python? Drop a comment below!</strong></p><p>🚀 <strong>Follow me for more Python tutorials &amp; projects!</strong> 🎥📖</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9abef1b3920e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering C++ Threads: A Dive into std::hardware_concurrency()]]></title>
            <link>https://medium.com/@sharpsanjay/mastering-c-threads-a-dive-into-std-hardware-concurrency-27d9e091c3ea?source=rss-f16a028be298------2</link>
            <guid isPermaLink="false">https://medium.com/p/27d9e091c3ea</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Sanjay Mishra]]></dc:creator>
            <pubDate>Sat, 28 Dec 2024 20:18:18 GMT</pubDate>
            <atom:updated>2024-12-28T20:18:18.966Z</atom:updated>
            <content:encoded><![CDATA[<p>In the modern era of computing, multi-threading has become a cornerstone for building efficient and responsive applications. In this blog, we will explore C++ threads and focus on the practical use of std::hardware_concurrency(), a feature that helps you harness the full power of your system’s hardware.</p><h3>Introduction to C++ Threads</h3><p>C++ introduced threading support in C++11, making it possible to create and manage threads natively. Threads allow programs to perform multiple operations concurrently, which is essential for leveraging multi-core processors.</p><p>Here’s a simple example of using threads in C++:</p><pre>#include &lt;iostream&gt;<br>#include &lt;thread&gt;<br><br>void say_hello() {<br>    std::cout &lt;&lt; &quot;Hello from thread!&quot; &lt;&lt; std::endl;<br>}<br><br>int main() {<br>    std::thread t(say_hello); // Launch a thread<br>    t.join(); // Wait for the thread to finish<br>    return 0;<br>}</pre><p>In this example, a new thread is created to execute the say_hello function, while the main thread continues its execution. The t.join() ensures that the program waits for the thread to finish before exiting.</p><h3>Understanding std::hardware_concurrency()</h3><h3>What is std::hardware_concurrency()?</h3><p>The std::hardware_concurrency() function, part of the &lt;thread&gt; library, provides an estimate of the number of threads that can be run concurrently on the machine. This number typically corresponds to the number of CPU cores or hardware threads available.</p><h3>Why Use std::hardware_concurrency()?</h3><p>When designing multi-threaded applications, it’s essential to know the system’s hardware capabilities. Using more threads than the hardware can handle may lead to excessive context switching, reducing performance.</p><p>std::hardware_concurrency() helps you:</p><ol><li>Dynamically adapt your thread count based on hardware.</li><li>Optimize resource utilization.</li><li>Avoid overwhelming the system with too many threads.</li></ol><h3>Syntax</h3><pre>unsigned int std::thread::hardware_concurrency();</pre><p>This function returns the number of hardware threads available or 0 if the information is not available.</p><h3>Example: Using std::hardware_concurrency()</h3><p>Here’s a practical example of using std::hardware_concurrency() to control the number of threads:</p><pre>#include &lt;iostream&gt;<br>#include &lt;thread&gt;<br>#include &lt;vector&gt;<br><br>void perform_task(int thread_id) {<br>    std::cout &lt;&lt; &quot;Thread &quot; &lt;&lt; thread_id &lt;&lt; &quot; is working.&quot; &lt;&lt; std::endl;<br>}<br><br>int main() {<br>    unsigned int num_threads = std::thread::hardware_concurrency();<br>    if (num_threads == 0) {<br>        std::cout &lt;&lt; &quot;Unable to determine hardware concurrency. Defaulting to 2 threads.&quot; &lt;&lt; std::endl;<br>        num_threads = 2;<br>    }<br>    std::cout &lt;&lt; &quot;Number of hardware threads: &quot; &lt;&lt; num_threads &lt;&lt; std::endl;std::vector&lt;std::thread&gt; threads;<br>    for (unsigned int i = 0; i &lt; num_threads; ++i) {<br>        threads.emplace_back(perform_task, i);<br>    }<br>    for (auto&amp; t : threads) {<br>      t.join();<br>    }<br>    return 0;<br>}</pre><h3>Output</h3><p>On a machine with 4 cores, the output might look like this:</p><pre>Number of hardware threads: 4<br>Thread 0 is working.<br>Thread 1 is working.<br>Thread 2 is working.<br>Thread 3 is working.</pre><h3>Use Cases for std::hardware_concurrency()</h3><ol><li><strong>Thread Pool Design</strong>: Determine the optimal number of threads for a thread pool.</li><li><strong>Parallel Algorithms</strong>: Divide tasks based on the number of available threads.</li><li><strong>Resource Allocation</strong>: Allocate resources dynamically based on hardware capabilities.</li></ol><h3>Best Practices</h3><ol><li><strong>Fallback Mechanism</strong>: Always include a fallback mechanism in case std::hardware_concurrency() returns 0.</li><li><strong>Load Testing</strong>: Test your application on systems with varying hardware configurations.</li><li><strong>Avoid Over-Threading</strong>: Use thread count proportional to the hardware capabilities for optimal performance.</li></ol><h3>Conclusion</h3><p>Understanding and using std::hardware_concurrency() can significantly enhance the efficiency of your multi-threaded applications. By dynamically adapting to the system’s hardware, you can ensure that your application performs optimally across different environments.</p><p>Start incorporating std::hardware_concurrency() into your projects today, and unlock the full potential of your hardware!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27d9e091c3ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Power of C++ unordered_map: A Game-Changer for Competitive Programming]]></title>
            <link>https://medium.com/@sharpsanjay/the-power-of-c-unordered-map-a-game-changer-for-competitive-programming-3b8a0b65b24c?source=rss-f16a028be298------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b8a0b65b24c</guid>
            <category><![CDATA[coding-interviews]]></category>
            <category><![CDATA[c]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Sanjay Mishra]]></dc:creator>
            <pubDate>Sat, 07 Dec 2024 01:29:31 GMT</pubDate>
            <atom:updated>2024-12-07T01:29:31.189Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently, I experienced the remarkable power of the unordered_map in C++ while solving the classic <strong>Two Sum</strong> problem on LeetCode. This problem is a favorite among coding interviewers, and its solution often depends on how efficiently we can perform lookups. By simply switching from std::map to std::unordered_map, I witnessed a performance boost of over <strong>50%</strong>, propelling my submission into the <strong>top category</strong> on the leaderboard.</p><h3>Why is unordered_map so Powerful?</h3><p>The magic lies in its underlying data structure — a <strong>hash table</strong>. Unlike std::map, which uses a balanced binary search tree and guarantees O(log⁡n)O(\log n) for insertions and lookups, std::unordered_map delivers <strong>average O(1)O(1)</strong> performance for these operations. This makes it a perfect fit for problems where speed is paramount and the order of elements doesn’t matter.</p><p>In competitive programming or real-world scenarios, where datasets can grow large and require quick lookups, unordered_map becomes a natural choice. Its efficiency can often be the difference between a good solution and a top-performing one.</p><h3>Case Study: The Two Sum Problem</h3><p>Here’s a quick recap of the Two Sum problem:<br> <strong>Problem Statement:</strong> Given an array of integers nums and an integer target, return the indices of the two numbers that add up to target.</p><p>A brute-force solution would involve nested loops, resulting in O(n2)O(n²) time complexity. However, using a hash table like unordered_map, we can solve it in <strong>linear time O(n)O(n)</strong>. Below is the optimized code:</p><pre>class Solution {<br>public:<br>    vector&lt;int&gt; twoSum(vector&lt;int&gt;&amp; nums, int target) {<br>        vector&lt;int&gt; result;<br>        std::unordered_map&lt;int, int&gt; visited;<br>        <br>        // Store the first element<br>        visited.insert({nums[0], 0});<br>        int len = nums.size();<br>        <br>        for (int i = 1; i &lt; len; i++) {<br>            // Check if the complement exists in the map<br>            if (visited.find(target - nums[i]) != visited.end()) {<br>                return {visited[target - nums[i]], i};<br>            } else {<br>                // Store the current element and its index<br>                visited.insert({nums[i], i});<br>            }<br>        }<br>        return result; // Should never reach here for valid input<br>    }<br>};</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GbvQ10KdOtqbAy0DDP1B0g.png" /></figure><h3>Key Observations</h3><ol><li><strong>Performance Boost:</strong></li></ol><p>When switching from std::map to std::unordered_map, the performance improved dramatically. The hash-based lookup allowed us to avoid the O(log⁡n)O(\log n) tree traversal overhead inherent to std::map.</p><p>In the LeetCode submission results, this change alone cut execution time significantly, boosting the solution into the <strong>top 5% of submissions</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IjKKnzCX-AlbmTfCIvCJug.png" /></figure><p><strong>2. Space Complexity:</strong></p><p>While unordered_map uses slightly more memory than map (due to hash table overhead), the trade-off is usually acceptable for competitive programming.</p><p><strong>3. Simplicity of Code:</strong></p><p>The unordered_map abstraction hides the complexity of hash table implementation, enabling cleaner and more concise code.</p><h3>Conclusion</h3><p>The unordered_map is a prime example of how understanding and leveraging the right data structures can significantly enhance performance. For problems like Two Sum, where quick lookups are essential, its hash table-based implementation makes it a game-changer.</p><p>As I reflect on this experience, I am reminded of how crucial it is to choose the right tool for the job. The efficiency gains from switching to unordered_map demonstrate its power and utility—not just for coding challenges but for countless real-world applications as well.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b8a0b65b24c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Maintenance of your body and brain together]]></title>
            <link>https://medium.com/@sharpsanjay/maintenance-of-your-body-and-brain-together-3147dbc9e1a5?source=rss-f16a028be298------2</link>
            <guid isPermaLink="false">https://medium.com/p/3147dbc9e1a5</guid>
            <category><![CDATA[life]]></category>
            <category><![CDATA[lifestyle]]></category>
            <category><![CDATA[yoga]]></category>
            <category><![CDATA[health]]></category>
            <category><![CDATA[mindfulness]]></category>
            <dc:creator><![CDATA[Sanjay Mishra]]></dc:creator>
            <pubDate>Sat, 22 Apr 2023 16:01:58 GMT</pubDate>
            <atom:updated>2023-06-14T21:48:24.203Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Maintenance of your body and brain together</strong></p><p>The human body consists of bones, muscles, joints, neurons, and tissues. It&#39;s a beautiful creation that evolves and decays over time as well. Like any other structure, the human body also needs maintenance, care, and environment to grow and excel. Remember when we day the human body we cannot ignore the fact that the human mind is also part of the human body. When it comes to taking care of our bodies, why are we talking about physical exercise or going to the gym? Why are we not focusing on exercising the mind as well and both? Why we are scheduling the maintenance separately?</p><p>We can argue that most of the time in the day we are using our brain/mind at work or to earn or study at school, so it&#39;s already exercised throughout the day. And we derived the term exercising body only. But like running a car is not the same as maintaining or servicing the car, the human body and mind need separate maintenance. Of course, it&#39;s not easy sometimes to have time for that scheduled maintenance and we continue running a non-serviced body that in the end will face consequences. It may not perform when it should perform at its full capacity, When you need to win the race, you come with a poorly maintained body. Sometimes we don&#39;t realize the importance of the human body but think about a car with poor maintenance that is running fine now but is sacrificing something. It&#39;s not gonna win the race or climb the hill with confidence.</p><p>We need a system that can help with the maintenance of the full body (body+mind) every day. So that we can prepare ourselves for any situation in life. A system where you focus/relax/breathe and test the limit of your body as well. The more we exercise well, the more it will develop. That is why Yoga is so important. The word yoga is derived from the Sanskrit root <em>yuj</em>, meaning “to yoke,” or “to unite”. The practice aims to create a union between body and mind. Yoga is a way to live: why: because in way of life, you need maintenance and care while keep doing your duties.</p><p>Please take care of yourself and always think about maintaining your well-being.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3147dbc9e1a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>