<?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 Vamsi Munagala on Medium]]></title>
        <description><![CDATA[Stories by Vamsi Munagala on Medium]]></description>
        <link>https://medium.com/@vamsi.lakshman?source=rss-9a454943017f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*3y-bTuBfjW3bOtJ7uYUdPw.jpeg</url>
            <title>Stories by Vamsi Munagala on Medium</title>
            <link>https://medium.com/@vamsi.lakshman?source=rss-9a454943017f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 11:25:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vamsi.lakshman/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[Retrieval in RAG — A Practical Single Page Cheat Sheet for Search Techniques]]></title>
            <link>https://medium.com/@vamsi.lakshman/retrieval-in-rag-a-practical-single-page-cheat-sheet-for-search-techniques-bf20b2918846?source=rss-9a454943017f------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf20b2918846</guid>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[bm25]]></category>
            <category><![CDATA[vector-search]]></category>
            <category><![CDATA[tf-idf]]></category>
            <category><![CDATA[hnsw]]></category>
            <dc:creator><![CDATA[Vamsi Munagala]]></dc:creator>
            <pubDate>Wed, 03 Jun 2026 03:18:37 GMT</pubDate>
            <atom:updated>2026-06-03T03:18:37.233Z</atom:updated>
            <content:encoded><![CDATA[<p>Most people think Retrieval-Augmented Generation (RAG) is just “vector search.” In reality, modern retrieval systems combine <strong>multiple search strategies</strong> working together to improve relevance, accuracy, and response quality.</p><p>Here’s a simplified one-page breakdown of the core retrieval techniques commonly used in enterprise AI systems. (I have intentionally removed metadata filtering in this worksheet). This worksheet will help you to understand the inner workings of search techniques along with examples to understand how search algorithms work internally.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h-hnTrQ0dLQfNpuyuF9rug.png" /><figcaption>A one-pager reference worksheet to understand the Search techniques</figcaption></figure><h3>1. Keyword Search (Lexical Search)</h3><p>Keyword search works through <strong>literal word overlap</strong> between the query and documents.</p><h3>TF-IDF (Term Frequency — Inverse Document Frequency)</h3><p>TF-IDF scores documents based on:</p><ul><li><strong>How often</strong> a term appears in a document (TF)</li><li><strong>How rare</strong> that term is across all documents (IDF)</li></ul><p>It helps identify documents that strongly match important keywords.</p><h4>Best For</h4><ul><li>Exact matches</li><li>Product names</li><li>Error codes</li><li>Regulatory terms</li><li>Technical documentation</li></ul><h4>Limitation</h4><p>It struggles with semantic meaning.</p><p>Example:</p><ul><li>Query: “car”</li><li>Document contains: “automobile”</li></ul><p>TF-IDF may fail because the exact keyword is missing.</p><h3>BM25 (Modern Keyword Ranking)</h3><p>BM25 improves TF-IDF by adding:</p><ul><li><strong>Term saturation: </strong>Repeating the same word 50 times doesn’t make a document infinitely better.</li><li><strong>Document length normalization: </strong>Prevents longer documents from unfairly ranking higher.</li></ul><p>BM25 is still one of the strongest baseline retrieval algorithms in search systems today.</p><h4>Best For</h4><ul><li>Enterprise search</li><li>Documentation portals</li><li>Hybrid RAG systems</li><li>Precise keyword-heavy retrieval</li></ul><h3>2. Semantic Search (Vector Search)</h3><p>Semantic retrieval focuses on <strong>meaning instead of exact words</strong>.</p><p>Instead of comparing text directly:</p><ol><li>Documents are converted into <strong>embeddings (vectors)</strong></li><li>The query is converted into another vector</li><li>Similarity is calculated using vector distance (often cosine similarity)</li></ol><p>This enables systems to understand:</p><ul><li>synonyms</li><li>intent</li><li>contextual meaning</li></ul><p>Even without overlapping keywords, semantic search can still retrieve relevant content.</p><h3>3. KNN (K-Nearest Neighbors)</h3><p>KNN retrieves the <strong>closest vectors</strong> to the query vector.</p><p>Process:</p><ul><li>Convert query → embedding</li><li>Compare against every document vector</li><li>Return the top K closest matches</li></ul><h4>Advantage</h4><p>High accuracy.</p><h4>Limitation</h4><p>Very expensive at scale because every query compares against massive vector datasets.</p><h3>4. ANN (Approximate Nearest Neighbors)</h3><p>ANN solves the scaling problem of KNN.</p><p>Instead of checking every vector:</p><ul><li>It intelligently narrows the search space</li><li>Returns “good enough” nearest matches much faster</li></ul><p>This makes large-scale semantic search practical.</p><h4>Used In</h4><ul><li>Vector databases</li><li>Production RAG systems</li><li>Large enterprise AI platforms</li></ul><p>Examples:</p><ul><li>FAISS</li><li>Pinecone</li><li>Weaviate</li><li>Milvus</li><li>Chroma</li></ul><h3>5. NSW (Navigable Small World Graphs)</h3><p>NSW organizes vectors into a graph structure. Each document vector connects to nearby neighbors.</p><p>Search works by:</p><ul><li>Starting from one node</li><li>Traversing toward increasingly similar nodes</li><li>Gradually moving closer to the target vector</li></ul><p>This dramatically improves search efficiency.</p><p>Think of it like navigating roads between cities instead of scanning every building in the country.</p><h3>6. HNSW (Hierarchical Navigable Small World)</h3><p>HNSW is one of the most widely used ANN algorithms today.</p><p>It introduces <strong>multiple graph layers</strong>:</p><ul><li>Upper layers → broad long-range jumps</li><li>Lower layers → fine-grained local search</li></ul><p>This creates:</p><ul><li>Extremely fast retrieval</li><li>High recall accuracy</li><li>Efficient scaling for millions/billions of vectors</li></ul><h4>Why It Matters</h4><p>HNSW powers many modern vector databases and enterprise-grade RAG systems.</p><h3>Real-World RAG Architecture</h3><p>Most production-grade RAG pipelines combine:</p><ul><li>BM25 → precise keyword matching</li><li>Semantic Search → contextual understanding</li><li>ANN/HNSW → scalable vector retrieval</li><li>Re-ranking models → final relevance optimization</li></ul><p>This is commonly called:</p><h4>Hybrid Retrieval</h4><p>Because:</p><ul><li>Keyword search handles precision</li><li>Semantic search handles meaning</li><li>Hybrid systems balance both</li></ul><h3>Final Takeaway</h3><p>RAG quality is not just about the LLM.</p><p>The real intelligence often comes from the <strong>retrieval layer</strong>:</p><ul><li>how documents are indexed,</li><li>how relevance is scored,</li><li>how semantic meaning is captured,</li><li>and how retrieval scales efficiently.</li></ul><p>Better retrieval = better AI answers.</p><p>✔️ If you like my blog, you can <a href="https://buymeacoffee.com/vamsim"><strong><em>Buy Me a Coffee here</em></strong></a>.<br>✔️ Connect with me on <a href="https://www.linkedin.com/in/vamsilmunagala/"><strong><em>Linkedin</em></strong></a><strong><em>.<br></em></strong>✔️ Press and hold the 👏 button to give up to 50 claps to this article!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf20b2918846" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Speed, Precision, and Late Interaction: A Deep Dive into Bi-Encoders, Cross-Encoders, and ColBERT]]></title>
            <link>https://medium.com/@vamsi.lakshman/speed-precision-and-late-interaction-a-deep-dive-into-bi-encoders-cross-encoders-and-colbert-7d090f55700b?source=rss-9a454943017f------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d090f55700b</guid>
            <category><![CDATA[bi-encoder]]></category>
            <category><![CDATA[rankings]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[cross-encoder]]></category>
            <dc:creator><![CDATA[Vamsi Munagala]]></dc:creator>
            <pubDate>Sun, 08 Mar 2026 21:29:45 GMT</pubDate>
            <atom:updated>2026-03-08T21:29:45.737Z</atom:updated>
            <content:encoded><![CDATA[<p>To build a world-class RAG (Retrieval-Augmented Generation) system, you need to understand that “finding the right information” happens in stages. You can’t just throw a billion documents at a smart model — it would take forever.</p><p>Instead, we use a “funnel” approach. At the top of the funnel, we need <strong>speed</strong>; at the bottom, we need <strong>precision</strong>. Bi-Encoders, Cross-Encoders, and ColBERT are the engines that power different parts of this funnel.</p><h3>1. Bi-Encoders</h3><p><strong>What they are:</strong> Think of Bi-Encoders as a system where the Query and the Document never meet until the very last second. They are encoded into vectors (lists of numbers) completely independently.</p><p><strong>How it works:</strong></p><p>Imagine we have a document about a refund policy and a user query.</p><ul><li><strong>Document (D):</strong> “Refunds are processed within 30 days.”</li><li><strong>Query (Q):</strong> “How long for a refund?”</li></ul><p><strong>The Walkthrough:</strong></p><ol><li><strong>Independent Encoding:</strong> The model takes <strong>D </strong>and turns it into a single vector: <strong>V_d</strong> = [0.12, -0.45, 0.88]. This happens during “Ingestion” and is stored in a Vector Database.</li><li><strong>Query Encoding:</strong> When the user asks <strong>Q</strong>, the model turns it into <strong>V_q</strong> = [0.10, -0.40, 0.90].</li><li><strong>Similarity Check:</strong> The system performs a simple math operation (like Cosine Similarity) to see how close these two points are in space.</li></ol><ul><li><strong>Hypothetical Math:</strong> <strong><em>V_q . V_d ~ 0.95</em></strong> (High match!).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/334/0*2tOJcjMGFZsjnS_i" /></figure><ul><li><strong>Where to use in RAG:</strong> At the very top. This is your <strong>Retriever</strong>. It allows you to search through millions of documents in milliseconds because the document vectors are already pre-calculated.</li></ul><h3>2. Cross-Encoders (The Perfectionists)</h3><p><strong>What they are:</strong> Cross-Encoders are the opposite. They force the Query and the Document to “sit in the same room” and talk to each other token-by-token.</p><p><strong>How it works (Behind the scenes):</strong></p><p>A query and a document are glued together (e.g., [CLS] Query tokens [SEP] Document tokens) and fed into a Transformer (BERT) model. The model computes a single, holistic score for the pair. Because all tokens in the query interact with all tokens in the document <em>inside</em> the transformer layers, the model understands very complex, long-range, and nuanced dependencies.</p><p><strong>The Walkthrough:</strong></p><ol><li><strong>Input Construction:</strong> [CLS] How long for a refund? [SEP] Refunds are processed within 30 days. [SEP]</li><li><strong>Full Attention:</strong> Because they are in the same input, every word in the query can look at every word in the document. The word “long” can directly interact with “30 days.”</li><li><strong>The Score:</strong> The model looks at the [CLS] token (the special first token) and outputs a single <strong>Relevance Score</strong> (a scalar like 0.982).</li></ol><ul><li><strong>Pros:</strong> Extremely accurate because it understands nuance (like negation or complex logic).</li><li><strong>Cons:</strong> Extremely slow. You cannot pre-compute vectors. You have to run the model <em>every time</em> you compare a query to a document.</li><li><strong>Where to use in RAG:</strong> As a <strong>Reranker</strong>. After the Bi-Encoder pulls the top 100 candidates, the Cross-Encoder re-scores them to find the “True Top 5.”</li></ul><h3>3. ColBERT: Contextualized Late Interaction (The Best of Both Worlds)</h3><p><strong>What it is:</strong> ColBERT (Collaborative BERT) is a “Late Interaction” model. It’s a middle ground that provides the speed of a Bi-Encoder with nearly the precision of a Cross-Encoder.</p><p><strong>How it works (Behind the scenes):</strong></p><p>Unlike the Bi-Encoder (which creates <strong>one</strong> vector for the whole doc), ColBERT creates a <strong>separate vector for every single word (token)</strong> in the query and the document. In ColBERT, we don’t just ask “Is this document similar to this query?” Instead, we ask: <strong>“For every single word in my query, what is the best matching word in this document?”</strong></p><p>ColBERT encodes the document into a set of vectors (one per token) <em>independently</em> of the query. <strong>At query time (a.k.a late interaction)</strong>, it takes the query token vectors and compares them to the document token vectors using a “<strong>MaxSim</strong>” operator.</p><blockquote>Because document token vectors are <strong>pre-computed</strong> (like Bi-encoders), ColBERT is fast enough to perform large-scale retrieval while maintaining high accuracy.</blockquote><p>For each query token, ColBERT finds the <em>maximum</em> similarity with <em>any</em> document token, then sums those maximums. This acts like a “soft” keyword match that is context-aware. Let’s look at the below walkthrough:</p><p><strong>The Walkthrough:</strong></p><p>Let’s use a slightly more expanded example to see how the math actually “picks” the document.</p><ul><li><strong>Query (</strong><em>Q</em><strong>):</strong> “Refund processing time”</li><li><strong>Document (</strong><em>D</em><strong>):</strong> “Refunds take 30 days.”</li></ul><p>Imagine our model creates these 2D vectors for our tokens:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JMp4IivafGEH73fQEHs9-Q.png" /></figure><p><strong>The MaxSim Operation (Step-by-Step):</strong></p><p>We create a “Similarity Matrix” where we calculate the score (e.g., Dot Product) between <strong>every</strong> query word and <strong>every</strong> document word.</p><p><strong>Similarity Matrix (Calculated Scores):</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o4nclu9xuttCwg8bqaRxwA.png" /></figure><p><strong>The Final Relevance Score:</strong></p><p><em>Score</em>=0.95+0.42+0.88=<strong>2.25</strong></p><p><strong>Where to use in RAG:</strong></p><ul><li><strong>As a sophisticated Retriever:</strong> It is fast enough to replace a standard Bi-Encoder but much more accurate because it understands how specific words in the query align with specific words in the doc.</li><li><strong>Circumstances:</strong> Use ColBERT when you have short, technical queries where every word matters (e.g., “Python list append vs extend”).</li></ul><h3>Comparison Matrix</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lXwVR9-w42OpxoJcsHWCRA.png" /></figure><h3>Summary: Where do they fit in the RAG Architecture?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hXeitOhkgRv72vI9Yo2g4Q.png" /></figure><p>The industry-standard RAG pipeline follows a <strong>funnel architecture</strong>:</p><h4><strong>1 — The Ingestion (Pre-processing):</strong></h4><ul><li><strong>Bi-Encoder:</strong> You embed all your chunks and store them in a Vector DB (Pinecone, Weaviate, Milvus).</li></ul><h4><strong>2 — The Retrieval (Stage 1 — The Wide Net):</strong></h4><ul><li><strong>Bi-Encoder:</strong> User asks a question. The system pulls the top 100 chunks.</li><li><em>Result:</em> Fast, but maybe a bit noisy.</li></ul><h4><strong>3 — The Reranking (Stage 2 — The Refinement):</strong></h4><ul><li><strong>Cross-Encoder:</strong> Take those 100 chunks and the query. Pass them through the Cross-Encoder.</li><li><em>Result:</em> It re-orders them perfectly. The most relevant chunk moves from rank #45 to #1.</li><li><strong>Note:</strong> You could also use <strong>ColBERT</strong> here for a faster, more scalable reranking.</li></ul><h4><strong>4 — The Generation (Final Stage):</strong></h4><ul><li><strong>LLM:</strong> The Top 5 chunks are sent to the LLM (GPT-4o, Claude) to write the final answer</li></ul><p>✔️ If you like my blog, you can <a href="https://buymeacoffee.com/vamsim"><strong><em>Buy Me a Coffee here</em></strong></a>.<br>✔️ Connect with me on <a href="https://www.linkedin.com/in/vamsilmunagala/"><strong><em>Linkedin</em></strong></a><strong><em>.<br></em></strong>✔️ Press and hold the 👏 button to give up to 50 claps to this article!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d090f55700b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RAG Chunking Strategies: A Complete Guide for AI Architects]]></title>
            <link>https://medium.com/@vamsi.lakshman/rag-chunking-strategies-a-complete-guide-for-ai-architects-1853a6e59ad7?source=rss-9a454943017f------2</link>
            <guid isPermaLink="false">https://medium.com/p/1853a6e59ad7</guid>
            <dc:creator><![CDATA[Vamsi Munagala]]></dc:creator>
            <pubDate>Thu, 19 Feb 2026 04:05:04 GMT</pubDate>
            <atom:updated>2026-02-19T04:16:58.762Z</atom:updated>
            <content:encoded><![CDATA[<p>When Retrieval-Augmented Generation (RAG) systems fail, it’s rarely because the LLM isn’t powerful enough.</p><p>It’s because retrieval failed.</p><p>And retrieval fails most often due to one overlooked design decision:</p><blockquote>Chunking.</blockquote><p>Chunking is not preprocessing.<br> It is <strong>retrieval boundary design</strong>.</p><p>If you define knowledge boundaries poorly, your retriever will surface incomplete, diluted, or irrelevant context — even when the correct answer exists in your corpus.</p><p>This article is a complete architectural guide to RAG chunking strategies, including:</p><ul><li>Fixed-size and semantic chunking</li><li>Hierarchical (parent–child) retrieval</li><li>Layout-aware PDF parsing</li><li>Time-window chunking for logs and transcripts</li><li>Multimodal chunking</li><li>Late chunking (context-aware embeddings)</li></ul><h3>Why Chunking Is an Architectural Decision</h3><p>In a typical RAG pipeline:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NW5cj6gWMqrdbzvvg3m4GQ.png" /><figcaption>RAG pipeline</figcaption></figure><ul><li>Retrieval specificity</li><li>Context sufficiency</li><li>Storage footprint</li><li>ANN index performance</li><li>Prompt token efficiency</li><li>Hallucination risk</li></ul><p>Your research document correctly emphasizes that there is <strong>no universally optimal chunk size.</strong></p><p>The best strategy depends on:</p><ul><li>Embedding model limits</li><li>Semantic density of documents</li><li>Whether users need local facts or broad context</li><li>Update frequency and governance requirements</li></ul><p>The most reliable production pattern is:</p><blockquote>Start with a strong baseline → instrument retrieval metrics → upgrade only where the baseline breaks</blockquote><h3>Fixed Size Chunking</h3><p><strong>What it is:</strong> Split documents into equal-length segments (e.g., 200–600 tokens).</p><p><strong>Why it works:</strong><br>Simple, scalable, and historically used in large-scale RAG pipeline</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zJgJBEG_xt6TMpaGc8enlA.png" /><figcaption>Fixed Chunking</figcaption></figure><p><strong>Example:</strong></p><p>Input:</p><pre># Refund Policy<br>Customers can request a refund within 30 days.<br>A receipt is required.<br>Digital products are not refundable.<br>Submit a ticket to support@example.com.</pre><p>Output:</p><pre>CHUNK 1:<br>Customers can request a refund within 30 days.<br>A receipt is required.<br><br>CHUNK 2:<br>Digital products are not refundable.<br>Submit a ticket to support@example.com.</pre><p><strong>Best for:</strong></p><ul><li>Early PoCs</li><li>Large corpora with low structural consistency</li><li>Rapid ingestion</li></ul><p><strong>Failure mode:</strong></p><ul><li>Splits semantic units</li><li>Weak for multi-hop reasoning inside a single document</li></ul><p><strong>Architect recommendation:</strong><br> Start here, measure retrieval metrics, then upgrade selectively.</p><h3>Sliding Window (Overlap-Based)</h3><p><strong>What it is:</strong> Fixed-size chunks with overlap to mitigate boundary fragmentation. Overlap ensures that boundary phrases appear in at least one chunk.</p><p><strong>Example</strong>:</p><pre>Chunk 1:<br>A receipt is required.<br>Digital products are not refundable.<br><br>Chunk 2:<br>Digital products are not refundable.<br>Submit a ticket to support@example.com.</pre><p><strong>Best for:</strong></p><ul><li>Legal documents</li><li>Regulatory text</li><li>Long clauses</li></ul><p><strong>Trade-off:</strong></p><ul><li>Overlap increases redundancy and index size</li><li>Redundancy increases storage and ANN search cost.</li></ul><p>Use overlap as “boundary insurance,” not as your primary retrieval strategy.</p><h3>Sentence &amp; Paragraph Chunking</h3><p><strong>What it is:</strong> Natural linguistic boundaries.</p><p><strong>Research insight:</strong> Sentence-level chunking often underperforms stronger segmentation strategies in retrieval metrics</p><p><strong>Best for:</strong></p><ul><li>Factoid QA</li><li>Short-form corpora</li></ul><p><strong>Risk:</strong></p><ul><li>Too little context → hallucination risk</li><li>Too many vectors → storage blow-up</li></ul><h3>Semantic Chunking</h3><p><strong>What it is:</strong> Detect topic shifts via embedding similarity and segment accordingly. Instead of cutting at token limits, the system detects <strong>topic shifts</strong>. Prevents topic mixing inside chunks and improves retrieval precision.</p><p>Behind the scenes, it:</p><ul><li>Split text into sentences.</li><li>Embed each sentence.</li><li>Compute cosine similarity between adjacent embeddings.</li><li>Insert boundary when similarity drops below threshold.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gwO13Ng6_uVzPnl5CdHbzw.png" /><figcaption>Semantic Chunking</figcaption></figure><p><strong>Example:</strong></p><blockquote><em>Sentence 1: “A receipt is required.”<br> Sentence 2: “Digital products are not refundable.”<br> </em><strong><em>Similarity = 0.91 → NO CUT</em></strong></blockquote><blockquote><em>Sentence 3: “Submit a ticket to support@example.com.”<br> </em><strong><em>Similarity = 0.62 → CUT</em></strong></blockquote><p>Result:</p><pre>CHUNK 1:<br>- A receipt is required.<br>- Digital products are not refundable.<br><br>CHUNK 2:<br>- Submit a ticket to support@example.com.</pre><p><strong>Best for:</strong></p><ul><li>Strategy documents</li><li>Whitepapers</li><li>Mixed-topic long-form documents</li></ul><p><strong>Strength:</strong></p><ul><li>Topically coherent chunks</li><li>Improved precision</li></ul><p><strong>Weakness:</strong></p><ul><li>Ingestion cost increases</li><li>Sensitive to similarity thresholds</li></ul><h3>Hierarchical (Parent–Child) Chunking</h3><p><strong>What it is: </strong>This is one of the highest-leverage strategies for enterprise systems.</p><p>Embed small child chunks in a vector database for precision.<br>Return larger parent chunks for generation context. The parent document — often the whole section — is typically stored in a separate document store.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hdsuo9lJPsFzrJ9OTdK2_Q.png" /><figcaption>Parent-Child Chunking</figcaption></figure><p>Your document correctly identifies this as a strong production pattern.</p><p><strong>Example:</strong></p><p>Vector DB (Child):</p><pre>&quot;Digital products are not refundable.&quot;</pre><p>Doc Store (Parent):</p><pre>## Eligibility<br>Customers can request a refund within 30 days.<br>A receipt is required.<br>Digital products are not refundable.</pre><p>The retriever finds the child.<br> The generator reads the parent.</p><p>Precision + Context = Stability.</p><p><strong>Best for:</strong></p><ul><li>Legal corpora</li><li>Pharma safety reports</li><li>Technical manuals</li><li>Regulated domains</li></ul><p><strong>Architect insight:</strong><br> This balances retrieval specificity and context sufficiency — two competing objectives highlighted in your research summary</p><h3>Topic / Section-Aware Chunking</h3><p>Split by headings, Markdown structure, HTML headers, clauses.</p><p><strong>Best for:</strong></p><ul><li>Policy docs</li><li>Knowledge bases</li><li>API documentation</li></ul><p>This preserves logical document boundaries and improves interpretability.</p><p><strong>Architect tip:</strong><br> Store section_path, doc_id, version, and page as metadata for filtering.</p><h3>Layout-Aware Chunking</h3><p>Your document emphasizes layout-aware parsing for rich documents.</p><p>Flat text extraction from PDFs often destroys:</p><ul><li>Column structure</li><li>Tables</li><li>Footnotes</li><li>Captions</li></ul><p>The system uses a layout parser to identify bounding boxes for titles, tables, and paragraphs. It treats a table as a single “retrievable object” rather than a list of broken strings. This prevents “garbage chunks” where a table’s columns get mixed into the text paragraphs below them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6NiurtYm0Vv4RLQ-H4jF2g.png" /><figcaption>Layout-aware chunk (PDFs)</figcaption></figure><p><strong>Example:</strong></p><pre>[Header] Refund Policy<br>[Table] Hazard | Action | PPE<br>[Page Number] Page 3</pre><p><strong>Best for:</strong></p><ul><li>Financial reports</li><li>Clinical PDFs</li><li>Research papers</li><li>Investor decks</li></ul><p><strong>Layout-aware chunking treats:</strong></p><ul><li>Paragraph blocks</li><li>Tables</li><li>Images</li><li>Captions</li></ul><p>as distinct retrievable units.</p><p>This is not optional in serious enterprise RAG.</p><h3>Metadata- &amp; Time-Aware Chunking</h3><p><strong>What it is:</strong> Metadata- and time-aware chunking is a strategy that treats chunking and indexing as a joint design process. Instead of just focusing on the text content, you attach specific metadata to each chunk that enables powerful filtering, freshness handling, and version control at the time of retrieval.</p><p>In this approach, you can still use standard chunking methods (like fixed-size or semantic splitting) for the text, but the system enriches each segment with “tags”. For time-aware scenarios specifically, such as audio transcripts or system logs, the system uses timestamps as primary boundaries rather than just word counts.</p><p>RAG often supports continuously updated knowledge bases.</p><p><strong>Example:</strong></p><p>Imagine a policy document that has been updated multiple times. A standard chunker might just see text; a metadata-aware chunker sees a data object.</p><ul><li><strong>Raw Content</strong>: “Approved refunds are issued to the original payment method within 5–10 business days.”</li></ul><pre>{<br>   &quot;doc_id&quot;:&quot;refund_policy_v3&quot;,<br>   &quot;section&quot;:&quot;Process&quot;,<br>   &quot;last_updated&quot;:&quot;2025-11-01&quot;,<br>   &quot;product&quot;:&quot;Payments&quot;,<br>   &quot;tenant&quot;:&quot;acme&quot;,<br>   &quot;valid_from&quot;:&quot;2025-11-01&quot;,<br>   &quot;valid_to&quot;:&quot;9999-12-31&quot;<br>}</pre><p>For streaming audio, the system creates windows based on seconds (e.g., 30-second windows) with internal segmentation for speaker turns.</p><ul><li><strong>Window 1 (00:10–00:30)</strong>: Includes the transcript of what was said in those 20 seconds.</li><li><strong>Overlap</strong>: The next window might start at 00:20, ensuring no context is lost during speaker handovers.</li><li><strong>Metadata</strong>: Each window is tagged with its start/end times and the mix of speakers involved.</li></ul><p><strong>Best for:</strong></p><ul><li>Multi-tenant systems</li><li>Versioned policies</li><li>Streaming data</li></ul><p>Time-aware chunking is essential for:</p><ul><li>Logs</li><li>Incident analysis</li><li>ASR transcripts</li></ul><h3>Time-Window Chunking (Streaming &amp; Logs)</h3><p><strong>What it is:</strong> This method treats time as the primary boundary. Transcripts come with timestamps for every word. The system creates overlapping windows based on seconds (e.g., a 30-second window with a 10-second overlap).</p><p><strong>Example</strong>:</p><ul><li><strong>Chunk 1 (00:00–00:20)</strong>: “Thanks for calling… My refund hasn’t arrived…”</li><li><strong>Chunk 2 (00:10–00:30)</strong>: “My refund hasn’t arrived… I see your order…”</li></ul><p>This allows the AI to tell you exactly <em>when</em> something was said in a recording.</p><p><strong>Best for:</strong></p><ul><li>Observability</li><li>Security events</li><li>Call transcripts</li><li>Monitoring systems</li></ul><h3>Multimodal Chunking</h3><p><strong>What it is:</strong> Multimodal chunking treats a document as a collection of distinct “elements” (like images, tables, and text paragraphs) rather than a single stream of characters .</p><p>The system creates multi-vector representations:</p><ul><li><strong>Element Detection</strong>: Instead of ignoring visuals, a layout parser identifies bounding boxes for every non-text object.</li><li><strong>Summarization for Retrieval</strong>: Images and complex tables are often summarized into text descriptions (e.g., “Line chart showing revenue growth”) so they can be “found” by standard text-based search queries.</li><li><strong>Multi-Vector Pointers</strong>: The system stores a “child” vector of the summary in the database but keeps a pointer to the original “parent” high-resolution image or table.</li><li><strong>Dual-Path Generation</strong>: When a user asks a question, the system retrieves the text context <em>and</em> the raw visual artifact, passing both to a multimodal model to ensure the AI “sees” the same chart the user is asking about.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b42qavXTWk3QwZHSJykBBQ.png" /><figcaption>Multimodal Chunking</figcaption></figure><p><strong>Best for:</strong></p><ul><li>Engineering manuals with diagrams</li><li>Clinical reports with charts</li><li>Financial statements</li></ul><p><strong>Pros</strong>: Eliminates “text-only blind spots” where the AI misses critical evidence found only in charts or diagrams.</p><p><strong>Cons</strong>: Ingestion is significantly heavier and more expensive due to the need for OCR, layout parsing, and image-to-text summarization.</p><h3>Late Chunking: Context-Aware Embeddings</h3><p>Most RAG systems follow this pattern:</p><ol><li>Split document into chunks</li><li>Embed each chunk independently</li><li>Store vectors</li></ol><p>That’s called <strong>early chunking</strong>.</p><p><strong>Late chunking</strong> flips the order. Instead of embedding each chunk separately, the system:</p><ol><li>Processes a <em>larger document span</em> (up to 8k tokens or more) through the transformer in one go. During this pass, every word “sees” every other word in the document through the self-attention mechanism.</li><li>Generates contextual token representations — Instead of producing one single vector for the whole document, the model generates a sequence of “token vectors” — one for every single word or sub-word.</li><li>Only <em>after</em> the model has finished the embedding pass do you define your chunk boundaries. You then “pool” (average) the token vectors that fall within each boundary to create the final chunk embedding.</li></ol><p>The result: <strong>each chunk embedding “knows” about surrounding context.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w7P_vPXNyXJWuYu_RxUdEA.png" /></figure><p>This improves handling of references like:</p><blockquote><em>“It is not refundable.</em></blockquote><h4><strong>Example (step-by-step):</strong></h4><p><strong>Step 1: Tokenization (The Raw Input)</strong></p><p>The system takes your full text and breaks it into sub-word tokens.</p><ul><li><strong>Input:</strong> &quot;JWST launched. It orbits L2.&quot;</li><li><strong>Tokens:</strong> [JW, ST, launched, ., It, orbits, L2, .]</li><li><strong>Token IDs:</strong> [432, 891, 1205, 14, 25, 607, 42, 14]</li></ul><p><strong>Step 2: The Forward Pass (Global Attention)</strong></p><p>This is the most critical step. The tokens are fed into a Long-Context Transformer. Unlike standard chunking, we feed the <strong>entire document</strong> at once.</p><p>As the data passes through the layers, the <strong>Self-Attention mechanism</strong> calculates relationships. The word <strong>“It”</strong> looks back at the word <strong>“JWST”</strong>.</p><ul><li><strong>Mathematical Result:</strong> The model assigns a high “attention weight” between the token It and the tokens JW + ST.</li></ul><p><strong>Step 3: Token-Level Embeddings (The Hidden States)</strong></p><p>The model outputs a unique vector for <strong>every single token</strong>.</p><ul><li>Vector_JW = [0.12, -0.45, ...]</li><li>Vector_ST = [0.11, -0.44, ...]</li><li>Vector_It = [0.12, -0.42, ...] <strong>&lt;-- Note:</strong> This vector is now mathematically very similar to the JWST vectors because it has &quot;absorbed&quot; their context.</li></ul><p><strong>Step 4: The Boundary Cut (Late Segmentation)</strong></p><p>Only now do we decide where to split the document. We decide that everything after the first period belongs to “Chunk 2.”</p><ul><li><strong>Chunk 1 Range:</strong> Tokens 0 to 3 (JWST launched.)</li><li><strong>Chunk 2 Range:</strong> Tokens 4 to 7 (It orbits L2.)</li></ul><p><strong>Step 5: Pooling (The Vector Fusion)</strong></p><p>To create a single vector for the database, we “pool” (usually average) the token vectors within each range.</p><p><strong>For Chunk 2:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EweQE46NXyrsc0Ws-bQhCw.png" /></figure><p>Because Vector_It was already contextualized to mean &quot;JWST&quot; in Step 2, the <strong>Final Vector</strong> for Chunk 2 naturally contains the &quot;signal&quot; for the James Webb Space Telescope, even though that name never appears in the text of Chunk 2.</p><p><strong>When to Use It:</strong></p><ul><li>Dense prose</li><li>Legal text</li><li>Reference-heavy documents</li></ul><p><strong>Trade-Off:</strong></p><ul><li>Higher embedding compute cost.</li></ul><h3>Chunking Techniques Comparison</h3><p>Here is a comparison table of the major chunking strategies, their underlying logic, and their practical trade-offs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7gPz8dReVSxnxVBWE4vdhQ.png" /></figure><h3>Decision Framework for Chunking</h3><p>Chunking strategy should align with:</p><ul><li>Content type</li><li>Query pattern</li><li>Regulatory risk</li><li>Performance constraints</li></ul><p>Here’s a practical architectural decision tree:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BRTBMA9GJRYxbh0vK0Y6qA.png" /><figcaption>Chunking Strategy Selection — Decision Tree</figcaption></figure><h3>Summary</h3><h4>The 5 Core Principles of RAG Chunking Strategy</h4><h4>1️. Chunking Defines Retrieval Precision</h4><p>Your chunk size defines your retrieval resolution.</p><ul><li>Small chunks increase precision.</li><li>Large chunks increase context.</li><li>Hierarchical chunking balances both.</li><li>Late chunking improves semantic fidelity.</li></ul><p>Before tuning models, tune your segmentation.</p><h4>2️. Structure Beats Size</h4><p>The most common mistake in RAG systems isn’t “wrong chunk size.”</p><p>It’s ignoring document structure.</p><ul><li>PDFs require layout-aware parsing.</li><li>Logs require time-window chunking.</li><li>Documents with headings benefit from section-aware splitting.</li><li>Mixed media requires multimodal chunking.</li></ul><p>Preserve natural boundaries first. Optimize size second.</p><h4>3️. Overlap Is a Safety Net, Not a Strategy</h4><p>Sliding window overlap reduces boundary loss.</p><p>But it increases:</p><ul><li>Storage</li><li>Index size</li><li>Retrieval redundancy</li><li>Cost</li></ul><p>Use overlap intentionally — not automatically.</p><h4>4️. Separate Retrieval Precision from Generation Context</h4><p>If you remember only one advanced pattern, remember this:</p><blockquote><em>Retrieve small. Read large.</em></blockquote><p>Hierarchical (parent–child) chunking is often the most scalable enterprise strategy because it allows:</p><ul><li>Fine-grained vector matching</li><li>Full-context answer generation</li><li>Better grounding</li><li>Lower hallucination rates</li></ul><h4>5️. Match Chunking Strategy to Query Behavior</h4><p>The right chunking strategy depends on how users ask questions.</p><ul><li>Factoid queries → smaller chunks</li><li>Cross-referenced prose → late chunking</li><li>Time-based questions → time-window + metadata filtering</li><li>Compliance-heavy systems → hierarchical + structure-aware parsing</li><li>Image-heavy documents → multimodal chunking</li></ul><p>There is no universal best chunk size.</p><p>There is only the best fit for your retrieval behavior.</p><h3>Final Thought: The Maturity Curve of RAG Chunking</h3><p>Most RAG systems evolve like this:</p><ol><li>Fixed-size baseline</li><li>Add overlap</li><li>Move to section-aware splitting</li><li>Introduce hierarchical retrieval</li><li>Add metadata filtering</li><li>Upgrade to late or multimodal chunking where needed</li></ol><p>Mature RAG systems don’t rely on one chunking strategy.</p><p>They compose them.</p><p>And that’s the key architectural mindset:</p><blockquote><em>Chunking isn’t a single decision.<br> It’s a layered design space.</em></blockquote><p>If you architect chunking deliberately, your retrieval improves.<br> If retrieval improves, your LLM improves.<br> If your LLM improves, your system earns trust.</p><p>And in production AI systems, trust is the real metric.</p><p>✔️ If you like my blog, you can <a href="https://buymeacoffee.com/vamsim"><strong><em>Buy Me a Coffee here</em></strong></a>.<br>✔️ Connect with me on <a href="https://www.linkedin.com/in/vamsilmunagala/"><strong><em>Linkedin</em></strong></a><strong><em>.<br></em></strong>✔️ Press and hold the 👏 button to give up to 50 claps to this article!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1853a6e59ad7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying the Transformer (Part 1): A Plain-English Guide to Building the Encoder]]></title>
            <link>https://medium.com/@vamsi.lakshman/demystifying-the-transformer-part-1-a-plain-english-guide-to-building-the-encoder-d86cdf00b878?source=rss-9a454943017f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d86cdf00b878</guid>
            <category><![CDATA[bert]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[chatgpt]]></category>
            <dc:creator><![CDATA[Vamsi Munagala]]></dc:creator>
            <pubDate>Tue, 04 Feb 2025 02:32:00 GMT</pubDate>
            <atom:updated>2025-02-04T02:32:00.339Z</atom:updated>
            <content:encoded><![CDATA[<p>I’m excited to help you understand the <strong>Encoder</strong> in the <strong>Transformer Architecture</strong> in plain English! A huge thanks to the many authors and contributors on platforms like Medium, whose work has been instrumental in helping me grasp these concepts. Without their insights, this article wouldn’t have been possible.</p><p>If you’re an <strong>AI Architect</strong>, <strong>ML Engineer</strong>, or <strong>Data Scientist</strong>, understanding the Transformer architecture is essential. It’s the backbone of many state-of-the-art models like BERT, GPT, and more. In this article, I’ll break it down step by step so you can confidently navigate this powerful architecture.</p><p>To keep things concise, I’ll make a few assumptions:</p><ul><li>I won’t explain how <strong>backpropagation</strong> works or how weight matrices are trained (we’ll save that for another time).</li><li>I’ll skip the detailed drawbacks of <strong>RNNs</strong> (Recurrent Neural Networks) and why the shift to Transformers became necessary. Instead, we’ll dive straight into the Transformer model itself.</li><li>You’ll need <strong>basic knowledge of Python or PyTorch</strong> to follow the code snippets comfortably.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pcDzGOs6_WwNVmBAsCUVaQ.png" /><figcaption><a href="https://arxiv.org/abs/1706.03762">The Transformer Model Architecture</a></figcaption></figure><p>Reference: <a href="https://arxiv.org/abs/1706.03762">https://arxiv.org/abs/1706.03762</a></p><p>When I first looked at the Transformer architecture, I found it quite complex and even intimidating. But with time, practice, and hands-on coding, I’ve gained a solid understanding of its nuances. Now, it doesn’t seem as overwhelming — trust me, you’ll feel the same by the end of this article!</p><p>To truly grasp the inner workings of this architecture, I highly recommend practicing the code alongside reading this article. Hands-on experimentation was key to my learning process, and I believe it will help you too. I’ll walk you through the model step by step, explaining <strong>why</strong> we’re doing, what we’re doing and <strong>what</strong> we’re trying to accomplish.</p><p>To keep things simple, I’ll use a basic example and guide you through the implementation. Special thanks to <a href="https://sebastianraschka.com/">Sebastian Raschka</a> for providing the foundational code, but I’ll add my own twist to make it even more approachable.</p><p>The goal is to demonstrate how data flows through the encoder’s main components:</p><ol><li><strong>Tokenization &amp; Numericalization</strong></li><li><strong>Embeddings + (Optional) Positional Encodings</strong></li><li><strong>Multi-Head Self-Attention</strong></li><li><strong>Add &amp; Norm</strong> (Residual Connection and Layer Normalization)</li><li><strong>Feed-Forward Neural Network (FFNN)</strong></li><li><strong>Add &amp; Norm</strong> (Another Residual Connection and Layer Normalization)</li></ol><blockquote><strong><em>Note</em></strong><em>: The code is meant primarily for </em>illustration<em> and may omit details like actual training loops, advanced hyperparameters, or padding/masking for variable sequence lengths.</em></blockquote><p>Let’s get started!</p><h3>Encoder</h3><p>The <strong>Transformer Encoder</strong> is the left side of the overall Transformer architecture. It processes your input sentence and generates <strong>contextual embeddings</strong> (also called <strong>context vectors</strong>) that capture the <em>meaning</em> of each token in the context of the entire sentence.</p><h3>Step 1: Token Embeddings</h3><p>Let’s start with a simple sentence: <em>“My shoes are small, my feet are big.”</em></p><blockquote><strong>Note</strong>: I occasioanlly use “token” and “word” interchangeably in this post.</blockquote><h4>A. Tokenization &amp; Numericalization</h4><p>To process this sentence, we first break it into <strong>tokens</strong>. Think of tokens as individual words. In real-world applications, libraries like <strong>OpenAI’s </strong><strong>tiktoken</strong> or <strong>Hugging Face’s Tokenizers </strong>are often used to tokenize text. These tools split text into sub-words or even characters for better flexibility.</p><p>For simplicity, we’ll split the sentence into words using spaces as delimiters. Once we have the tokens, we assign an <strong>index</strong> to each unique word. These indices are referred to as <strong>token IDs</strong>.</p><p>For example:</p><ul><li>Sentence: <em>“My shoes are small, my feet are big.”</em></li><li>Tokens: [&quot;My&quot;, &quot;shoes&quot;, &quot;are&quot;, &quot;small,&quot;, &quot;my&quot;, &quot;feet&quot;, &quot;are&quot;, &quot;big&quot;]</li></ul><pre>sentence = &#39;My shoes are small, my feet are big.&#39;<br><br>dc = {s:i for i,s in enumerate(sorted(sentence.replace(&#39;,&#39;, &#39;&#39;).split()))}<br>print(dc)</pre><p>The output:</p><pre>{&#39;My&#39;: 0, &#39;are&#39;: 2, &#39;big.&#39;: 3, &#39;feet&#39;: 4, &#39;my&#39;: 5, &#39;shoes&#39;: 6, &#39;small&#39;: 7}</pre><blockquote><strong>Note</strong>: “My” and “my” end up as <strong>different</strong> tokens because Python’s string handling is case-sensitive. The token &quot;big.&quot; includes the period, which is another simplification in this example.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/177/0*xLiDYJ9oGU8fF-I6" /></figure><p>Next, we construct a <strong>tensor</strong> of token IDs for our sentence:</p><pre>import torch<br><br>sentence_int = torch.tensor([dc[s] for s in sentence.replace(&#39;,&#39;, &#39;&#39;).split()])<br>print(sentence_int)</pre><p>The output tensor is:</p><pre>tensor([0, 6, 2, 7, 5, 4, 2, 3])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bCjfjnK3X_PW6N9A" /><figcaption>Token IDs for each token</figcaption></figure><p>We are ignoring Positional Encoding to maintain the order in the above sequence. I will create another article for that.</p><h4>B. Creating Word Embeddings</h4><p>In <strong>Transformer</strong> models, words are typically converted to <strong>embeddings</strong>, which are learnable dense vectors. Although real models often use embedding sizes of 64, 128, or 768, we’ll keep it tiny here (2 dimensions) for demonstration.</p><pre>torch.manual_seed(123)  # For reproducibility<br><br>embed = torch.nn.Embedding(num_embeddings=8, embedding_dim=2)  <br># 8 unique tokens, each mapped to a 2D embedding<br><br>embedded_sentence = embed(sentence_int).detach()  <br>print(embedded_sentence)<br>print(embedded_sentence.shape)</pre><ul><li><strong>nn.Embedding</strong> takes the number of <strong>unique tokens</strong> (8) and the desired <strong>embedding dimension</strong> (2).</li><li>The call embed(sentence_int) returns a (sequence_length, embedding_dim) tensor of learned embeddings.</li><li>We use .detach() just to avoid any computational graph details here.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3uuArjMb5gMqnU7W" /><figcaption>Token or Word Embedding</figcaption></figure><h3>Step 2: Positional Encoding</h3><p>In a Transformer encoder, <strong>positional encoding</strong> is crucial for providing the model with information about the <strong>order</strong> of tokens in a sequence. Since self-attention layers treat all tokens in parallel, the model otherwise has no inherent sense of <em>which</em> token comes before or after another.</p><h4>A. Why We Need Positional Encoding</h4><ul><li><strong>Order Matters</strong>: Words like “small” and “big” can appear in different contexts, and the sequence order helps us interpret meaning (“My shoes are small” vs. “My small shoes are there”).</li><li><strong>Self-Attention Is Order-Agnostic</strong>: By design, attention alone does not encode positional signals — every token can attend to every other token <em>regardless</em> of position.</li><li><strong>Cue for the Model</strong>: Positional encodings inject a notion of <em>which token is first, second, third,</em> etc., so the encoder can differentiate, say, the subject from the object in a sentence.</li></ul><h4>B. Two Common Approaches</h4><p><strong>Sinusoidal Encodings (Original Paper)</strong></p><ul><li>Proposed in the “Attention Is All You Need” paper.</li><li>Each position <strong><em>p</em></strong> in the sequence receives a vector of sine and cosine values at different frequencies.</li><li>The formula ensures each position gets a unique pattern, allowing the model to learn relative and absolute positions.</li></ul><p><strong>Learned Positional Embeddings</strong></p><ul><li>Similar to a standard embedding table, but for positions.</li><li>Each position index (0, 1, 2, …) has a <strong>learnable</strong> vector.</li><li>Often used by models like GPT variants, letting them learn position-related patterns directly from data.</li></ul><h4>C. How the Sinusoidal Encoding Works</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*Wiimud0kBVM64FJMN6YnCg.png" /><figcaption>Positional Encoding uses Sine and Cosine functions</figcaption></figure><p>For a token at position <strong><em>p</em></strong>, and embedding dimension index <strong><em>i</em></strong>(split into even/odd), the encoding is:</p><ul><li>Even dimensions use <strong>sine</strong>; odd dimensions use <strong>cosine</strong>.</li><li>Different frequencies allow the model to learn about both <strong>local</strong> and <strong>global</strong> positional relationships.</li><li>Given the <strong>exponential scale</strong> in the frequencies, it’s incredibly unlikely for two different positions to yield the <em>same</em> set of sine/cosine values across all dimensions — particularly for non-trivial sequence lengths (e.g., up to 512 or 1024).</li></ul><h4>D. How to implement Positional Encoding?</h4><p>In our demo, we are using the Approach 2: Learned Positional Embeddings</p><pre>import torch<br>import torch.nn as nn<br><br>class LearnedPositionalEncoding(nn.Module):<br>    &quot;&quot;&quot;<br>    Learned positional encoding for a no-batch scenario,<br>    where x has shape (seq_len, d_model).<br>    &quot;&quot;&quot;<br>    def __init__(self, d_model, max_len=512):<br>        super().__init__()<br>        self.pos_embedding = nn.Embedding(num_embeddings=max_len, embedding_dim=d_model)<br><br>    def forward(self, x):<br>        &quot;&quot;&quot;<br>        x: Tensor of shape (seq_len, d_model), no batch dimension.<br>        Returns a tensor of the same shape (seq_len, d_model),<br>        but with added positional embeddings.<br>        &quot;&quot;&quot;<br>        seq_len = x.size(0)  # Number of tokens in sequence<br>        # Create a range of positions: 0,1,...,seq_len-1<br>        positions = torch.arange(seq_len, device=x.device)  # (seq_len,)<br>        # Embed these positions<br>        pos_enc = self.pos_embedding(positions)  # (seq_len, d_model)<br>        # Add to the input embeddings<br>        return x + pos_enc</pre><pre># Create our learned positional encoding<br>pos_encoder = LearnedPositionalEncoding(d_model=2, max_len=50)<br><br># Apply positional encoding<br>embedded_sentence = pos_encoder(embedded_sentence)<br>print(&quot;\nPositionally Encoded Sentence:\n&quot;, embedded_sentence)<br>print(&quot;Pos Encoded shape:&quot;, embedded_sentence.shape)</pre><h3>Step 3: Multi-Head Attention</h3><p>Token embeddings provide a <strong>static representation</strong> for each token. However, to truly capture the <strong>context</strong> or <strong>relationships</strong> between tokens in a sentence, we need <strong>dynamic embeddings</strong> that consider how each token relates to others. This is where the <strong>Multi-Head Attention</strong> mechanism in the Transformer architecture comes into play.</p><h3><em>A. Self-Attention</em></h3><p>Before diving into Multi-Head Attention, let’s first understand <strong>Self-Attention</strong>.</p><ul><li><strong>Self-Attention</strong> helps a model understand the context of each word or token by <strong>comparing </strong>it to every other token in the input sequence.</li><li>The result is a set of <strong>attention scores</strong>, which indicate <em>how strongly</em> a token is related to the others in the sentence.</li></ul><p><strong>Example:</strong></p><p>In the sentence, <em>“My shoes are small, my feet are big”</em>:</p><ul><li>The word “<strong>small</strong>” is more related to “<strong>shoes</strong>” than “<strong>feet</strong>.”</li><li>Similarly, the word “<strong>big</strong>” is more related to “<strong>feet</strong>” than “<strong>shoes</strong>.”</li></ul><p>Self-Attention captures these relationships by computing a <strong>context vector</strong> for each token — reflecting how much each token “attends to” every other token in the sequence.</p><h4>1) How Does Self-Attention Work?</h4><p>Each token embedding undergoes a series of <strong>linear transformations</strong>, which results in a <strong>context vector</strong> for each token. This vector represents the relationships between that token and all other tokens.</p><p>The process typically goes like this:</p><ol><li><strong>Each token embedding</strong> (e.g., “shoes”) is used to form <strong>Query (Q)</strong>, <strong>Key (K)</strong>, and <strong>Value (V)</strong> vectors via trainable weight matrices.</li><li>We <strong>compute attention scores</strong> between every query and every key.</li><li>These scores are turned into <strong>weights</strong> (via a softmax), which are then applied to the <strong>Value</strong> vectors.</li><li>The result is a <strong>contextualized vector</strong> for each token that reflects how strongly it relates to the others.</li></ol><p><strong>Example:</strong></p><p>For the token <strong>“shoes”</strong>, suppose the attention scores (purely illustrative!) come out as: [0.05, <strong>0.5</strong>, 0, <strong>0.3</strong>, 0.05, 0.06, 0, <strong>0.04</strong>]</p><p>This means:</p><ul><li>“shoes” is <strong>50%</strong> related to itself.</li><li><strong>30%</strong> related to “small.”</li><li><strong>4%</strong> related to “big.”</li></ul><p>This final distribution shows that <strong>“shoes”</strong> focuses mostly on itself and “small” but only slightly on “big.” The token’s <strong>context vector</strong> is then a weighted combination of <strong>Values</strong>, factoring in these scores.</p><h4>2) The Role of Key, Query, and Value</h4><p>The way tokens undergo <strong>linear transformations</strong> is via the <strong>Key (K)</strong>, <strong>Query (Q)</strong>, and <strong>Value (V)</strong> matrices which are at the heart of the attention mechanism. These matrices are learned during training through <strong>gradient-based optimization</strong> (e.g., using optimizers like Adam or AdamW). Here’s how they function:</p><ul><li><strong>Query (Q)</strong>: Represents the current token we’re focusing on (e.g., “shoes”).</li><li><strong>Key (K)</strong>: Represents the same set of tokens but from the perspective of “what’s relevant to queries?”</li><li><strong>Value (V)</strong>: Contains the actual content/embeddings that get combined according to the attention scores.</li></ul><h4>Analogy:</h4><p>Think of Q, K, and V as parts of a search engine:</p><ul><li><strong>Query</strong> = “What is your search phrase?”</li><li><strong>Key</strong> = “How does each document match that phrase?”</li><li><strong>Value</strong> = “The actual text/content of each document.”</li></ul><p>This is conceptually similar to how a <strong>search engine</strong> finds and ranks relevant web pages.</p><h4>3) Code: Generating Q, K, V (Untrained Weights)</h4><p>Below is a <strong>demo</strong> showing how we might produce Q, K, and V vectors from our embedded sentence using <strong>random (untrained) weight matrices</strong>. (In practice, these matrices are <strong>learned</strong> via backpropagation.)</p><pre>import torch<br><br># The embedded_sentence from our earlier step, shape: (8, 2)<br>print(embedded_sentence.shape)  # [8, 2]<br><br>d = embedded_sentence.shape[1]  # 2<br><br># We&#39;ll define the dimensions for Q, K, V:<br>d_q, d_k, d_v = 3, 3, 4  # for demonstration<br><br># Random weight matrices (untrained)  <br>torch.manual_seed(123)<br>W_query = torch.nn.Parameter(torch.rand(d_q, d))  # Shape: [3, 2]<br>W_key   = torch.nn.Parameter(torch.rand(d_k, d))  # Shape: [3, 2]<br>W_value = torch.nn.Parameter(torch.rand(d_v, d))  # Shape: [4, 2]<br><br># Compute Queries, Keys, and Values<br>queries = W_query.matmul(embedded_sentence.T).T  # =&gt; shape: (8, 3)<br>keys    = W_key.matmul(embedded_sentence.T).T    # =&gt; shape: (8, 3)<br>values  = W_value.matmul(embedded_sentence.T).T  # =&gt; shape: (8, 4)<br><br>print(&quot;Queries Shape:&quot;, queries.shape)  # [8, 3]<br>print(&quot;Keys Shape:&quot;,    keys.shape)     # [8, 3]<br>print(&quot;Values Shape:&quot;,  values.shape)   # [8, 4]</pre><p>Here’s the breakdown:</p><ul><li><strong>queries</strong>: A 2D vector (8,3), meaning each of the 8 tokens has a 3-dimensional query vector.</li><li><strong>keys</strong>: Same shape as queries.</li><li><strong>values</strong>: Slightly larger (8,4), meaning each token’s “value” is 4-dimensional.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2dxaeJzm_ZfM-haV" /><figcaption>Q/K/V Projections</figcaption></figure><h4>4) Attention Score</h4><p>Once we have <strong>Queries (Q)</strong> and <strong>Keys (K)</strong> for each token, we need to measure “how relevant” each token is to every other token. We do this by:</p><ul><li><strong>Taking the dot product</strong> between the query vector for a token (e.g., “shoes”) and the key vectors of all tokens.</li><li><strong>Scaling</strong> by <strong>√dₖ</strong> to keep values numerically stable (especially for large d_k).</li><li><strong>Applying a softmax</strong> so these scores sum to 1, making them interpretable as “attention weights.”</li></ul><h4><strong>Why Use Dot Product?</strong></h4><p>The dot product measures the <strong>similarity</strong> between two vectors. In this context, it helps determine how relevant a token (query) is to the other tokens (keys) in the sequence. In self-attention, a high dot product means the query token finds that particular key token more relevant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*5rK8z-vewz7J_E_5dDRmrw.png" /></figure><p><strong>Example: Single Token’s Attention (for query “shoes”)</strong></p><p>This results in scores for each token indicating their relevance to “shoes.”</p><pre># Attention Score<br>omega_2 = query_2.matmul(keys.T)  # Matmul Query2[1, 3] *  Keys.T[3, 8] = [1, 8]<br>print(omega_2) # Result matrix for query2, i.e. shoes  = [ 1 token, 8 dimensions]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*huycHAqy7NlpAPNt" /><figcaption>Attention Score (for token “shoes”)</figcaption></figure><p>The dot product values can grow large for longer sequences, so they are <strong>scaled</strong> (divided by the square root of the dimension of the key vectors) to stabilize gradients:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*hkTGwe049UVUq4R7EKFVtQ.png" /></figure><p>Finally, the attention scores are passed through a <strong>softmax</strong> function to normalize them into probabilities, ensuring they sum to 1, making it easier to interpret their relative importance.</p><pre>import torch.nn.functional as F<br><br># Compute attention scores for a specific token (e.g., &quot;shoes&quot;)<br>query_2 = queries[1].unsqueeze(0)  # Query for &quot;shoes&quot; (2nd token)<br>omega_2 = query_2.matmul(keys.T)   # Dot product between query and keys<br>print(&quot;Raw Attention Scores (Omega):\n&quot;, omega_2)<br><br># Scale and apply softmax<br>attention_weights_2 = F.softmax(omega_2 / d_k**0.5, dim=0)<br>print(attention_weights_2)</pre><pre>Raw Attention Scores (Omega):<br> tensor([[-0.0879,  4.3783,  1.7863,  1.0502, -2.4988, -1.9530,  1.7863, -1.0434]],<br>       grad_fn=&lt;MmBackward0&gt;)<br>Attention Weights (Softmax):<br> tensor([[0.0432, 0.5687, 0.1273, 0.0832, 0.0107, 0.0147, 0.1273, 0.0249]],<br>       grad_fn=&lt;SoftmaxBackward0&gt;)</pre><p>Here:</p><ul><li><strong>Raw attention scores</strong> can be positive or negative, indicating stronger or weaker relevance.</li><li><strong>Softmax</strong> converts them into probabilities that sum to 1, e.g., [0.5687, 0.1273, ...], meaning “shoes” mostly attends to itself (and possibly some other tokens, depending on the distribution).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*tNq8Uge91z8G9ZoE" /></figure><blockquote><strong>Note</strong>: We picked random weight matrices for Key, Value and Query — in other words, these are untrained weights. The context vector that is being produced will be different when you are using <strong>trained </strong>weight matrices.</blockquote><h4>5) Context Vector</h4><p>After determining <strong>“how much”</strong> attention to pay to each token, we also need <strong>“what information”</strong> to gather. That’s where the <strong>Value (V)</strong> vectors come in:</p><ol><li>The attention weights for each token (from softmax) indicate <strong>how much</strong> each value contributes.</li><li>We multiply the <strong>Value</strong> vectors by these <strong>attention weights</strong> and sum them up, yielding a <strong>context vector</strong> for the query token.</li></ol><p>By multiplying attention weights with values, the model combines <strong>“how much attention”</strong> (softmax weights) with <strong>“what information”</strong> (values), resulting in a meaningful <strong>context vector</strong> for the query token.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*igYke5tLn_w-idWyQeQdcw.png" /></figure><p>Tokens with higher attention weights contribute more of their <strong>value information</strong> to the context vector.</p><pre># Compute context vector for &quot;shoes&quot;<br>context_vector_2 = attention_weights_2.matmul(values) # # matmul = attention_weights_2[1, 8] * values[8, 4]<br>print(&quot;Context Vector Shape:&quot;, context_vector_2.shape)  # [1, 4]<br>print(&quot;Context Vector:\n&quot;, context_vector_2)  </pre><pre>Context Vector Shape: torch.Size([1, 4])<br>Context Vector:<br> tensor([[0.2593, 0.5718, 1.0390, 0.9041]], grad_fn=&lt;MmBackward0&gt;)</pre><ul><li>Each dimension in [0.2593, 0.5718, 1.0390, 0.9041] is influenced by how “shoes” attends to every other token’s value.</li><li>Higher attention weights on certain tokens mean more of their <strong>Value</strong> vectors contributed to “shoes”’s final context vector.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*M-h4_YJ6fCZWNNst" /><figcaption>Context Vector for “shoes”</figcaption></figure><h4><strong>What Does Each Value in the Context Vector Represent?</strong></h4><p>The context vector is a numerical representation that <strong>encodes</strong> the <strong>relationships</strong> or <strong>relevance</strong> of the query token (<strong>“shoes”</strong>) to all tokens in the sentence. These values are computed by blending the <strong>Value vectors</strong> of all tokens, weighted by their <strong>attention scores</strong>.</p><ul><li>Each dimension in the context vector is influenced by the token embeddings (values) and reflects specific aspects of the token’s relationships with other tokens.</li><li>The specific interpretation of each value depends on how the model learned to <strong>encode </strong>meaning during training.</li></ul><p>For example, suppose the context vector for “shoes” is [0.2593, 0.5718, 1.0390, 0.9041] :</p><ul><li><strong>1.0390</strong> might represent a relationship dimension related to <strong>descriptions</strong> or <strong>adjectives</strong> (e.g., <strong>“big”</strong>).</li><li><strong>0.9041</strong> might represent a relationship dimension related to <strong>actions</strong> or <strong>verbs</strong> (e.g., <strong>“are”</strong>).</li><li><strong>0.5718</strong> might capture associations with <strong>locations</strong>, <strong>objects</strong>, or <strong>nouns</strong> (e.g., <strong>“My”</strong>, <strong>“feet”</strong>).</li><li><strong>0.2593</strong> might encode <strong>general context</strong>, like <strong>“what the sentence is about.”</strong></li></ul><p>The absolute values themselves don’t directly map to specific words but emerge from how the attention weights are distributed among the <strong>Value vectors</strong>.</p><h4>Attention Scores and Context Vectors for All Tokens</h4><p>The attention mechanism generates <strong>attention scores</strong> and <strong>context vectors</strong> for <strong>every token</strong> in the input sequence. Since the <strong>weight matrices</strong> (Query: Wq​, Key: Wₖ, and Value: Wᵥ) are learned during the training process, these computations can be performed in <strong>parallel</strong>, making Transformers highly efficient. At the end of the process, each token has its own <strong>context vector</strong>, representing its relationships with all other tokens in the sequence.</p><h3>B. What is the Purpose of Multi-Head Attention?</h3><p>A single self-attention mechanism can capture <strong>relationships</strong> among tokens, but it may struggle to represent <strong>different types</strong> of relationships <em>all at once</em>. This is precisely where <strong>Multi-Head Attention</strong> shines: it allows the model to look at the input from <em>multiple</em> perspectives <strong>in parallel</strong>.</p><p>Multi-Head Attention consists of several <strong>self-attention mechanisms</strong> (or <strong>“heads”</strong>) running in parallel. Each head learns to focus on a <strong>different aspect</strong> or <strong>relationship</strong> within the input sequence.</p><h4>1) Why Multiple Heads?</h4><p>Each head can <strong>specialize</strong> in capturing certain patterns or relationships. For example:</p><ul><li><strong>Head #1</strong> might learn to focus on <strong>semantic</strong> relationships, such as “shoes” ↔ “small.”</li><li><strong>Head #2</strong> might track <strong>syntactic</strong> structures, like how “My” (a possessor) associates with “shoes.”</li><li><strong>Head #3</strong> might focus on <strong>positional</strong> or other nuanced aspects, such as adjacency in the sentence or specific grammatical roles.</li></ul><p>By combining the outputs from multiple heads, the Transformer gains a richer and more comprehensive understanding of the input sequence.</p><h4>2) How Multi-Head Attention Works</h4><ol><li><strong>Independent Self-Attentions</strong>:<br>- We run <strong>separate</strong> self-attention calculations (heads) using their own trainable weight matrices (Wq​, Wₖ, and Wᵥ​​).<br>- For instance, Head #1 might be better at picking up semantic cues, while Head #2 handles syntactic cues, etc.</li></ol><p><strong>2. Context Vectors for Each Token</strong>:</p><ul><li>Consider the the token <strong>“shoes”</strong>:<br>- <strong>Head 1’s context vector</strong> captures how “shoes” is <strong>semantically </strong>related to “small.”<br>- <strong>Head 2’s context vector</strong> captures how “shoes” is <strong>syntactically </strong>modified by “My.”<br>- <strong>Head 3’s context vector</strong> captures the <strong>positional </strong>relationship between “shoes” and “small.”</li></ul><p>Similarly, context vectors are computed for all tokens in the sentence.</p><p><strong>3. Concatenation and Final Transformation</strong>:</p><ul><li>The context vectors from all heads are <strong>concatenated</strong> to form a combined vector for each token.<br><strong>Concat(head₁, head₂, head₃, …, headₕ)</strong> where each head has the dimension of the value vector.<br>- <strong>For example</strong>: if there are 3 heads and the Value vector dimension is 4, then the concatenated dimensions will be [3, <strong>4</strong>]</li><li>This combined vector is then passed through a <strong>final linear transformation</strong> (a learnable weight matrix, <strong><em>W₀</em></strong>), to integrate the information from all heads. <strong>Outputₘₕₐ</strong>will have the <strong>same dimensions</strong> as the token embeddings.<br><strong>Outputₘₕₐ = Concat(head₁, head₂, head₃, …, headₕ). <em>W₀</em></strong></li></ul><p>By doing so, each token embedding now reflects <strong>multiple angles</strong> of context — semantic, syntactic, and beyond.</p><h4>3) How to implement Multi-Head Attention?</h4><p>In typical <strong>Transformer implementations</strong>, the steps go like this:</p><ol><li><strong>Compute Q, K, V Projections:<br></strong>From your input embeddings, i.e. <strong>X</strong>, you apply three linear transformations:<br><strong><em>Q = X . Wq</em>​<br><em>K = X . Wₖ</em> <br><em>V = X . Wᵥ<br></em></strong>Here, <br> — <strong><em>X</em></strong> is the (batch_size, seq_len, d_model) input. <br> — Each of <strong><em>Wq</em></strong>, <strong><em>Wₖ, Wᵥ </em></strong>is a learnable matrix of shape (d_model, d_model).<br> — Consequently <strong><em>Q</em></strong>, <strong><em>K</em></strong>, and <strong><em>V </em></strong>each end up with shape (batch_size, seq_len, d_model).</li><li><strong>Reshape into Heads</strong> <strong>(Splitting Q, K, V into each head dimensions)</strong><br> — Here, head_dim = d_model/num_heads<strong> </strong><br>— Example reshape in PyTorch:<br>Q = Q.view(batch_size, seq_len, num_heads, head_dim).transpose(1, 2)<br> — This transforms (batch_size, seq_len, d_model) into (batch_size,num_heads,seq_len,head_dim)<br> — Our example code has d_model=2 (2 is our token embedding size). Suppose <strong>num_heads = 2</strong>. Then each head gets <br><strong>head_dim = d_model/num_heads = 1<br></strong>So if our input <strong><em>X</em></strong> is (batch=1, seq_len=8, d_model=2), each head will produce <strong><em>Q, K, V</em></strong> of shape (1, 8, 1).<br> — Each “head” <em>internally</em> sees a chunk of size <strong>head_dim</strong>.</li><li><strong>Compute Scaled Dot-Product Attention (Per Head)<em><br> — </em></strong>Each head performs the standard dot-product attention using its <strong>head_dim</strong>-wide slice of <strong><em>Q</em></strong>, <strong><em>K</em></strong>, and <strong><em>V.</em></strong><br> — You get an output context vector for each head of shape (batch_size,seq_len,head_dim).</li><li><strong>Concatenate All Heads and Apply a Final Linear Projection<br> — </strong>After computing attention for all heads, concatenate along the embedding dimension → (batch_size, seq_len, num_heads * d_model)<br> — A final linear transform maps it back to (batch_size, seq_len, d_model).</li></ol><h4>4) Why Do We Reshape Q, K and V into Heads at All?</h4><blockquote><strong>Note</strong>: The “split” is happening <em>after</em> a learned <strong>linear transform</strong>. This means each head is <em>not</em> restricted to a naïve slice of “raw” dimensions; rather, it gets a learned mix of all the original embedding dimensions, i.e. Q, K, V.</blockquote><p><strong>1) Encouraging Diverse Focus</strong></p><ul><li><strong>Multiple heads</strong> each get a <strong>different subspace</strong> of the embedding.</li><li>If all heads used the <strong>full</strong> embedding dimension, they might learn <strong>overlapping</strong> features. Splitting forces <strong>specialization</strong> — one head might focus on semantic relations, another on syntax, etc.</li></ul><p><strong>2) Efficiency Considerations</strong></p><ul><li>With dimension splitting, each head uses smaller weight matrices (head_dim × head_dim) instead of (d_model​ × d_model​).</li><li>Matrix multiplication on smaller subspaces is <strong>faster</strong> and uses less memory. Thus, you can afford <strong>more heads</strong> without blowing up computation or parameter counts.</li></ul><p><strong>3) Do We Lose Expressiveness?</strong></p><ul><li>Even though each head sees a smaller dimensional slice, each head can still attend to <strong>all tokens</strong> in the sequence.</li><li>After attention, we <strong>concatenate</strong> all heads’ outputs, restoring the full <strong>d_model</strong> dimension. This merging step integrates the multiple subspace views into a richer representation.</li></ul><p><strong>4) Reduced Redundancy</strong></p><ul><li>If each head used the full dimension, they might attend to <strong>similar</strong> features. Splitting encourages heads to learn different, complementary patterns, often leading to better performance.</li></ul><p><strong>5) Empirical Evidence</strong></p><ul><li>The original <strong>Transformer</strong> paper and subsequent research found that <strong>different heads</strong> tend to learn <strong>different relationships</strong> (e.g., positional, syntactic, or long-distance dependencies). Splitting the embedding dimension helps enable this diversity without significantly increasing parameters.</li></ul><p><strong>6) Quick Analogy: “Colored Glasses” Example</strong></p><p>Think of each token embedding as <strong>light</strong> with 4 colors (RGB plus an extra channel).</p><ul><li>You have 2 “heads,” each wearing a special pair of tinted glasses.</li><li><strong>Head #1</strong> might highlight certain color mixes (e.g., mostly red and green) to glean “syntactic” signals.</li><li><strong>Head #2</strong> might highlight another color blend (e.g., mostly blue and the extra channel) to glean “semantic” signals.</li></ul><p>They both see <strong>some</strong> mixture of all 4 channels — but tinted differently. <strong>After</strong> each has observed the input, you <strong>combine</strong> their observations (concatenate + linear mix) into a final, multi-colored view.</p><pre>import torch<br>import torch.nn as nn<br>import torch.nn.functional as F<br><br>class MultiHeadSelfAttention(nn.Module):<br>    &quot;&quot;&quot;<br>    Multi-Head Self-Attention for a no-batch scenario:<br>    Input x: (seq_len, d_model)<br>    Output: (seq_len, d_model)<br>    &quot;&quot;&quot;<br>    def __init__(self, d_model=2, num_heads=2):<br>        super().__init__()<br>        assert d_model % num_heads == 0, &quot;d_model must be divisible by num_heads&quot;<br>        <br>        self.d_model = d_model<br>        self.num_heads = num_heads<br>        self.head_dim = d_model // num_heads<br><br>        # Linear projections for Q, K, V<br>        # Shape: (d_model, d_model) each<br>        self.W_Q = nn.Linear(d_model, d_model)<br>        self.W_K = nn.Linear(d_model, d_model)<br>        self.W_V = nn.Linear(d_model, d_model)<br><br>        # Final output projection<br>        self.out_proj = nn.Linear(d_model, d_model)<br><br>    def forward(self, x):<br>        &quot;&quot;&quot;<br>        x: (seq_len, d_model)<br>        Returns: (seq_len, d_model)<br>        &quot;&quot;&quot;<br>        seq_len, d_model = x.shape<br>        <br>        # 1) Compute Q, K, V =&gt; each (seq_len, d_model)<br>        Q = self.W_Q(x)  # (seq_len, d_model)<br>        K = self.W_K(x)<br>        V = self.W_V(x)<br><br>        # 2) Reshape for multi-head attention:<br>        #    from (seq_len, d_model) -&gt; (seq_len, num_heads, head_dim)<br>        #    then transpose -&gt; (num_heads, seq_len, head_dim)<br>        Q = Q.view(seq_len, self.num_heads, self.head_dim).transpose(0,1)<br>        K = K.view(seq_len, self.num_heads, self.head_dim).transpose(0,1)<br>        V = V.view(seq_len, self.num_heads, self.head_dim).transpose(0,1)<br>        # Now Q, K, V each have shape: (num_heads, seq_len, head_dim)<br><br>        # 3) Compute scaled dot-product attention for each head<br>        #    scores shape =&gt; (num_heads, seq_len, seq_len)<br>        scores = torch.matmul(Q, K.transpose(-1, -2)) / (self.head_dim ** 0.5)<br>        attn_weights = F.softmax(scores, dim=-1)  # softmax along seq_len of K<br><br>        # 4) Multiply attn_weights by V =&gt; shape (num_heads, seq_len, head_dim)<br>        context = torch.matmul(attn_weights, V)<br><br>        # 5) Reshape back to (seq_len, d_model)<br>        #    by transposing =&gt; (seq_len, num_heads, head_dim)<br>        #    then flattening num_heads*head_dim =&gt; d_model<br>        context = context.transpose(0,1).contiguous()  # (seq_len, num_heads, head_dim)<br>        context = context.view(seq_len, d_model)       # (seq_len, d_model)<br><br>        # 6) Final linear projection =&gt; (seq_len, d_model)<br>        out = self.out_proj(context)<br>        return out</pre><p>Now,</p><pre>mha = MultiHeadSelfAttention(d_model=2, num_heads=2)<br>mha_out = mha(embedded_sentence)  # =&gt; (8,2)</pre><h3>Step 4: Add &amp; Norm</h3><p>So far, we have talked about Input (Token) Embeddings and Multi-Head Attention. Let’s discuss the next layer in the Transformer architecture, “<strong>Add &amp; Norm</strong>”.</p><p>The <strong>Add &amp; Norm</strong> layer is a crucial component in the Transformer architecture that comes after the <strong>Multi-Head Attention</strong> and <strong>Feed-Forward Neural Network</strong> layers. It serves two main purposes:</p><ol><li><strong>Residual Connections</strong> (Add): To retain original information and prevent vanishing gradients.</li><li><strong>Layer Normalization</strong> (Norm): To stabilize and accelerate training by normalizing activations.</li></ol><h4>A. “Add” Residual Connections</h4><ol><li><strong>Residual Connections (Add)</strong>: Residual connections bypass the Multi-Head Attention or Feed-Forward Network layer by directly adding the input of the layer to its output.</li></ol><p>This allows the model to:</p><ul><li><strong>Retain Original Input Information</strong>: Ensures that the original embeddings (or previous layer outputs) aren’t lost or distorted beyond recognition by deeper transformations.</li><li><strong>Aid Gradient Flow</strong>: Helps prevent issues like <strong>vanishing gradients</strong> during backpropagation, especially in deep networks.</li></ul><p><strong>Mathematically</strong>: For the Multi-Head Attention layer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*HG_xZYA1IT6CPLGa54idvQ.png" /><figcaption>Residual Connection</figcaption></figure><p>The <strong>input to the MHA layer</strong> (e.g., token embeddings) is <strong>added directly</strong> to the MHA’s output, ensuring that the original information is preserved.</p><h4><strong>Analogy: Teamwork in a Project</strong></h4><p>Imagine a team working on a project where every team member is supposed to contribute something. Here’s how it relates:</p><ul><li><strong>Without Residual Connections</strong>:<br>If one team member (a layer) fails to contribute effectively, their lack of contribution might hurt the overall project because the team relies entirely on everyone doing their part. <br>(Information is lost or degraded when a layer doesn’t work well)</li><li><strong>With Residual Connections</strong>:<br>Even if that layer doesn’t do a great job, the “project leader” (the residual path) ensures the original info (previous layers’ contributions) is passed along, so the model can still make progress.<br>(The residual path allows useful information to bypass ineffective layers.)</li></ul><h4>B. “Norm” <strong>Layer Normalization</strong></h4><ul><li>The <strong>residual output</strong> is passed through a <strong>layer normalization</strong> process which standardizes theoutput to have a mean (μ) of 0 and a standard deviation of 1 (σ).</li><li>This improves <strong>numerical stability</strong> and reduces sensitivity to initialization, making training faster and more stable.</li></ul><p><strong>Analogy</strong>:<br>Think of <strong>LayerNorm</strong> as “smoothing out” the amplitude of each feature. Just like adjusting the volume levels in a music track ensures no single instrument dominates, LayerNorm keeps all features balanced.</p><p><strong>Mathematically</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cjCnvA2s_97V9-rD1N2Mmw.png" /></figure><ul><li>μ: Mean of the residual output.</li><li>σ: Standard deviation of the residual output.</li><li>γ, β: Learnable parameters to scale and shift the normalized output.</li></ul><h4>C. Detailed Example of “Add &amp; Norm”:</h4><p>Consider the sentence: <strong>“My shoes are small.”</strong></p><ul><li>Suppose the embedding for “shoes” is: <br><strong>Input = [0.5, 0.2, 0.3]</strong></li><li>The MHA computes a context vector for “shoes,” such as:<br><strong>Outputₘₕₐ = [0.8, 0.6, 0.4]</strong></li><li>The residual connection adds the input embedding directly to the MHA output: <br><strong>Residual Output = Input +</strong> <strong>Outputₘₕₐ = [0.5 + 0.8, 0.2 + 0.6, 0.3 + 0.4] = [1.3, 0.8, 0.7]</strong></li><li><strong>Normalize Operation</strong>: <br>- <em>Compute Mean (μ)</em>: <strong>(1.3 + 0.8 + 0.7)/3 = 0.93<br>- </strong><em>Compute Standard Deviation (σ)</em>: <strong>√[(1.3–0.93)² + (0.8–0.93)² + (0.7–0.93)²]/3</strong> <strong>= 0.25</strong><br>- <em>Normalize each element</em>: <strong>Norm(x) = x — μ/σ</strong>, where x are the elements in the residual output.<br><strong>[(1.3–0.93)/0.25, (0.8–0.93)/0.25, (0.7–0.93)/0.25] = [1.48, -0.52, -0.92].</strong></li><li>Hence, after <strong>Add &amp; Norm</strong>, the mean is near zero and the standard deviation is near one.</li></ul><h4>D. How to implement “Add &amp; Norm”?</h4><pre># Residual + Norm<br>residual_1 = embedded_sentence + mha_out<br>layer_norm_1 = nn.LayerNorm(normalized_shape=2)<br>normed_1 = layer_norm_1(residual_1)<br><br>print(&quot;\n-- After Multi-Head Self-Attention --&quot;)<br>print(&quot;MHA output shape:&quot;, mha_out.shape)<br>print(&quot;Add &amp; Norm shape:&quot;, normed_1.shape)</pre><h3>Step 5: Feed-Forward Neural Network (FFNN)</h3><p>After the <strong>Add &amp; Norm</strong> layer, the normalized output is passed to a <strong>position-wise (per-token)</strong> fully connected Feed-Forward Neural Network (FFNN). This network processes <strong>each token independently</strong>, applying <strong>non-linear transformations</strong> that enrich its representation.</p><h4>A. Why do we need FFNN?</h4><ul><li>The <strong>Multi-Head Attention (MHA)</strong> layer captures relationships between tokens in the input sequence, focusing on <strong>contextual dependencies</strong>. However, these operations are <strong>linear in nature</strong>, meaning they cannot capture more complex patterns or transformations.</li><li>The FFNN introduces <strong>non-linearity</strong> through activation functions such as <strong>ReLU</strong>, <strong>GELU</strong>, or <strong>tanh</strong>, enabling the model to learn intricate patterns in the data and represent richer features.</li></ul><blockquote><strong>Important Note</strong>: While the softmax function used in the attention mechanism introduces a form of non-linearity, the per-token transformation after aggregating the value vectors (V) is essentially a <strong>specialized linear weighting step</strong> followed by a final linear projection. This is why the FFNN is crucial for introducing true <strong>non-linear transformations</strong>.</blockquote><h4>B. Steps in the FFNN</h4><ol><li><strong>First Linear Layer (Expansion)</strong>:</li></ol><ul><li>The input dimension is expanded to a larger dimension (e.g., 512 → 2048) using a learned weight matrix (<strong>W₁</strong>​) and bias (<strong>b₁</strong>​):<br><strong>z = xW₁ + b₁</strong></li><li>This expansion provides the model with a higher capacity to learn richer representations.</li></ul><p><strong>2. Non-Linearity (Activation Function)</strong></p><ul><li>The intermediate representation <strong>z</strong> is passed through a <strong>non-linear activation function</strong> (e.g., <strong>ReLU</strong>) to introduce non-linearity:<br><strong>h` = ReLU(z)</strong></li><li><strong><em>ReLU </em></strong>operates element-wise, where we can do things like “squash” negative values to zero or re-scale magnitudes in a non-linear way.</li><li>The activation is often <strong>ReLU</strong>, but other functions like <strong>GELU</strong> or <strong>tanh</strong> can be used.</li><li>This step <strong>breaks</strong> the linearity — allowing the model to represent more complex, non-linear relationships.</li></ul><p><strong>3. Second Linear Layer (Compression)</strong>:</p><ul><li>The expanded representation (<strong>h`)</strong> is projected back to the original dimension using another learned weight matrix (<strong>W</strong>₂​) and bias (<strong>b</strong>₂):<br><strong>h = h`W</strong>₂<strong>+ b</strong>₂</li><li>This ensures compatibility with the residual connection and the rest of the architecture.</li></ul><p>Thus, the FFN transforms <strong>x</strong> into a new vector <strong>h</strong> using <strong>two</strong> linear layers with a non-linearity in between.</p><p>The intermediate <strong>ReLU activation</strong> introduces <strong>non-linearity</strong>, allowing the network to model complex, non-linear functions. This makes the FFNN essential for:</p><h4><strong>C. Why This Matters</strong></h4><ol><li><strong>Refining Token Representations</strong>:</li></ol><ul><li>The FFNN operates on each token independently, improving its contextual representation after the MHA layer.</li><li>Example: “<strong>shoes</strong>” becomes more strongly associated with “<strong>small</strong>” while suppressing irrelevant features.</li></ul><p><strong>2. Handling Complex Relationships</strong>:</p><ul><li>The non-linearity enables the model to capture relationships that cannot be expressed through linear transformations alone.</li></ul><p><strong>3. Balancing Dimensionality</strong>:</p><ul><li>The expansion-compression structure allows the model to work in a higher-dimensional space temporarily before returning to the original size for compatibility with residual connections.</li></ul><h4>D. How to implement Feed Forward Neural Network?</h4><pre>import torch<br>import torch.nn as nn<br><br>class FeedForward(nn.Module):<br>    def __init__(self, d_model=2, hidden_dim=4):<br>        super().__init__()<br>        self.linear1 = nn.Linear(d_model, hidden_dim)<br>        self.relu = nn.ReLU()<br>        self.linear2 = nn.Linear(hidden_dim, d_model)<br>        <br>    def forward(self, x):<br>        x = self.linear1(x)   # Expand from d_model -&gt; hidden_dim<br>        x = self.relu(x)      # Apply non-linearity<br>        x = self.linear2(x)   # Compress back to d_model<br>        return x<br><br># Example usage:<br>ffn = FeedForward(d_model=2, hidden_dim=4)<br>ffn_out = ffn(normed_1)  # =&gt; shape: (seq_len, 2)</pre><ul><li><strong>linear1</strong> expands the embedding dimension (e.g., 2 → 4).</li><li><strong>relu</strong> adds non-linearity.</li><li><strong>linear2</strong> projects back to the original dimension (4 → 2 in this toy case).</li></ul><p>In a real Transformer with d_model=512, you might use hidden_dim=2048 (often 4× or more). This simple MLP pattern is repeated for <strong>each token</strong> in the sequence—hence “position-wise” feed-forward network.</p><h3>Step 6: Add &amp; Norm (again)</h3><p>After the Feed-Forward Neural Network (FFNN), the <strong>Add &amp; Norm layer</strong> is applied to ensure stability and preserve important information. The idea is similar to the attention layer: each sublayer (attention and FFNN) needs its own residual connection and normalization to ensure that the network can learn incremental changes and keep the activations stable throughout the depth of the network. It performs the following key operations:</p><h4><strong>A. Residual Connection</strong></h4><ul><li>The residual connection adds the <strong>original input</strong> (output from the previous Add &amp; Norm layer) back to the <strong>FFNN output</strong>:<br><strong><em>z = x + FFNN(x) <br></em></strong>Where <br><strong><em>x</em></strong> : input to the FFNN.<br><strong><em>FFNN(x)</em></strong>: Output of the FFNN.</li></ul><p>The purpose of adding residual connection:</p><ul><li><strong>Preserves Original Information</strong>: Ensures we don’t lose the embeddings from previous layers if the FFNN transformations aren’t beneficial for certain tokens.</li><li><strong>Skip Connection</strong>: The model can effectively “skip” the FFNN if needed (e.g., if the FFNN’s contribution is small).</li><li><strong>Better Gradient Flow</strong>: Having a direct path from the input to the output helps avoid vanishing gradients in deep models.</li></ul><h4><strong>B. Layer Norm</strong></h4><ul><li>The <strong>LayerNorm</strong> step normalizes the combined output of the residual connection.<br><strong><em>Norm Output=LayerNorm(z)</em></strong></li><li>Ensures that the input to the next layer has a consistent scale (mean = 0, variance = 1), which helps stabilize training.</li><li>Prevents instability caused by exploding or vanishing gradients. Balances contributions from the <strong>residual input</strong> and the <strong>FFNN output</strong>, ensuring neither dominates the representation.</li></ul><pre>residual_2 = normed_1 + ffn_out<br>layer_norm_2 = nn.LayerNorm(normalized_shape=2)<br>encoder_out = layer_norm_2(residual_2)<br><br>print(&quot;\n-- After Feed-Forward --&quot;)<br>print(&quot;FFN output shape:&quot;, ffn_out.shape)<br>print(&quot;Final encoder output shape:&quot;, encoder_out.shape)</pre><ul><li><strong>residual_2</strong> adds the <strong>FFNN</strong> output to normed_1 (the previous Add &amp; Norm).</li><li><strong>layer_norm_2</strong> then normalizes the result, producing the <strong>encoder_out</strong>.</li></ul><p>At this point, each token embedding is again normalized, typically having <strong>per-dimension mean ~0</strong> and <strong>variance ~1</strong>. These final encoder outputs can be passed to subsequent encoder layers or to a decoder, depending on the Transformer’s overall design.</p><h3>Stacking the Encoder Nₓ</h3><p>In practical implementations, the <strong>Encoder</strong> block (consisting of <strong>Multi-Head Attention</strong>, <strong>Add &amp; Norm</strong>, <strong>Feed-Forward Network</strong>, and another <strong>Add &amp; Norm</strong>) doesn’t just occur <strong>once</strong>. Instead, we <strong>stack</strong> this block <strong><em>N</em></strong> times (e.g., 6 or 12 layers in many models).</p><h4>Why Repeated Layers?</h4><p><strong>Iterative Refinement</strong></p><ul><li><strong>Each</strong> encoder layer takes the token representations from the previous layer and <strong>further refines</strong> them.</li><li>Over multiple layers, the model can <strong>accumulate</strong> more nuanced insights — capturing a progressively richer hierarchy of syntactic and semantic relationships.</li></ul><p><strong>Deeper Representations</strong></p><ul><li>The first couple of layers might learn more <strong>local</strong> or <strong>surface-level</strong> features, while later layers capture <strong>long-range dependencies</strong> or high-level semantics.</li><li>Stacking layers allows the network to handle increasingly complex patterns.</li></ul><p><strong>Self-Attention at Multiple “Depths”</strong></p><ul><li>Each layer’s <strong>self-attention</strong> sees <em>all</em> tokens, but with the <strong>previous layer</strong> providing updated context.</li><li>This “re-attention” process can highlight different aspects of the sentence at each depth, improving overall embedding quality.</li></ul><h4><strong>Analogy: Building a Story</strong></h4><ul><li>Imagine rewriting a summary of a text multiple times. Each pass incorporates a deeper understanding, resulting in a richer, more cohesive version.</li><li>In the same way, each encoder layer “re-writes” the embeddings with more context, culminating in a comprehensive representation after <strong><em>N</em></strong> passes.</li></ul><p>Hence, <strong>stacking <em>N </em>encoder blocks</strong> is key for achieving the powerful context-aware embeddings we see in models like <strong>BERT</strong> and other Transformer-based architectures.</p><h3>Closing Thoughts: Context-Aware Embeddings and Beyond</h3><p>Modern Encoder-based models (such as <strong>BERT</strong>) excel at producing <strong>context-aware embeddings</strong> for each token. These embeddings capture:</p><ol><li><strong>Word Relationships</strong>: How each token (e.g., “shoes,” “small”) relates to others in the sentence.</li><li><strong>Positional Information</strong>: The relative ordering of tokens, ensuring the model understands sentence structure.</li></ol><p>Because these representations are <strong>semantically rich</strong>, they can:</p><ul><li><strong>Cluster Similar Sentences</strong>: Group together text segments that convey similar meaning or context.</li><li><strong>Cluster Similar Documents</strong>: Find broader thematic similarities across entire paragraphs or pages.</li></ul><h4>Foundations for Retrieval-Augmented Generation (RAG)</h4><p><strong>Retrieval-Augmented Generation</strong> leverages these context-aware embeddings to <strong>retrieve</strong> relevant passages from a knowledge base and <strong>augment</strong> a generative model’s input. Essentially, the encoder helps pinpoint <strong>which</strong> documents (or text chunks) are thematically similar or relevant, boosting the quality of generation by providing more accurate, domain-specific context.</p><p><strong>Example</strong>:</p><ul><li><strong>BERT</strong> or a similar encoder locates the most relevant sections in a large corpus based on learned embeddings.</li><li>A generative model (like GPT) then uses that retrieved text to craft more informed, context-rich responses.</li></ul><p>In this way, <strong>Transformer encoders</strong> aren’t just powerful for language tasks like classification or question answering; they’re also at the heart of modern techniques that fuse <strong>retrieval</strong> with <strong>generation</strong>, pushing the boundaries of what AI systems can understand and produce.</p><h3>Conclusion</h3><p>We’ve taken a <strong>step-by-step</strong> journey through the <strong>Transformer Encoder</strong> — covering token embeddings, positional encodings, multi-head self-attention, feed-forward networks, and the Add &amp; Norm layers. While this <strong>encoder</strong> alone can power many tasks (like BERT’s language understanding), there’s a whole other side to the Transformer known as the <strong>Decoder</strong>, crucial for sequence-to-sequence tasks such as translation and text generation.</p><blockquote><strong>For hands-on experimentation and the entire code, check out the notebook in my GitHub: </strong><a href="https://github.com/vmunagala0117/build_llm_from_scratch_v1/blob/main/simple_encoder_demo.ipynb"><strong>simple encoder</strong></a><strong>.</strong></blockquote><p><strong>Stay tuned for Part 2</strong>, where we’ll dive into the <strong>Decoder</strong> architecture in detail and see how it extends these ideas with cross-attention and other mechanisms.</p><p>If you found this article helpful, <strong>please clap</strong> and <strong>share your feedback</strong> — every clap and comment helps more folks discover these resources and join the discussion. Thank you for reading, and I look forward to continuing our deep dive into Transformers in the next installment!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d86cdf00b878" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Securing Azure Databricks Communication]]></title>
            <link>https://medium.com/@vamsi.lakshman/securing-azure-databricks-communication-73395d4a803f?source=rss-9a454943017f------2</link>
            <guid isPermaLink="false">https://medium.com/p/73395d4a803f</guid>
            <category><![CDATA[azure-databricks]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[networking]]></category>
            <dc:creator><![CDATA[Vamsi Munagala]]></dc:creator>
            <pubDate>Fri, 31 May 2024 16:44:07 GMT</pubDate>
            <atom:updated>2024-05-31T16:44:07.616Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s discuss securing the communication between Azure Databricks components: between the control plane and the data plane, and between users and the control plane. I highly recommend following the sections as I explain the various interactions from a networking perspective.</p><p>Before we delve into securing these communications, it’s crucial to understand the various components within the Azure Databricks architecture.</p><h3>Azure Databricks Architecture</h3><p>In the context of Azure Databricks, the service architecture is split into a control plane and a data plane (also referred to as a compute plane). Here’s a brief overview of each:</p><ol><li><strong>Control Plane</strong>: The control plane is where the Azure Databricks workspace resides, and it manages and controls the interactions and orchestration of your Databricks workloads. <strong>Azure Databricks workspace</strong> is the primary web interface through which users interact with the control plane. This includes workspace creation, notebook deployment, job scheduling, and cluster management. The control plane is hosted and managed by Microsoft Azure in a multi-tenant architecture which simplifies the management and reduces the operational overhead.</li><li><strong>Data Plane (Compute Plane)</strong>: The data plane, or compute plane, is where the actual data processing happens. It consists of Azure Databricks clusters, which run on Azure Virtual Machines in your own Azure subscription. When a job is launched, the control plane creates and manages the required resources in the data plane. The compute resources (like Spark clusters) are created in your Azure Virtual Network, and they process data from data sources like Azure Blob Storage, Azure Data Lake Store, etc. The data never leaves your Azure Virtual Network which ensures a high level of security and compliance.</li></ol><p>In terms of location, the control plane is hosted and managed by Databricks in the cloud, while the data plane (compute plane) gets created in your own Azure subscription, providing you control over your data and compute resources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/0*B772atror9HYO5yS" /><figcaption>Control Plane and Data Plane in Azure Databricks</figcaption></figure><h3>Securing Connectivity Between Control Plane and Data Plane</h3><p>By default, when you create a cluster, it gets provisioned in the data plane. A public IP address is created with which it interacts with the control plane.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/0*zozybyMkcT7ODNBV" /><figcaption>Public IP is used to interact with the control plane</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_48XmHHUEz-KyVNrvSgaDw.png" /><figcaption>Public IP is used to interact with the control plane</figcaption></figure><p>However, your company may have restrictions against the use of any public IP address, and Microsoft recommends using “<strong>Secured Cluster Connectivity (SCC)</strong>”, also known as <strong>No Public IP</strong>, which is a feature of Azure Databricks that enhances the security of your Databricks clusters. When enabled, it ensures that the clusters in your Databricks workspace do not have public IP addresses, and therefore, cannot be accessed directly from the internet.</p><p>Behind the scenes, when you create a Databricks workspace with No Public IP enabled, Databricks sets up a series of secure network connections that allow your clusters to communicate with the necessary Azure services without exposing them to the public internet.</p><p>By enabling this feature, Databricks uses <strong>Azure NAT Gateway</strong> for outbound connectivity from your clusters to necessary Azure services (like Azure Storage or Azure Key Vault) and to the internet for necessary updates. The key aspect here is that NAT Gateway does not open up any inbound pathways to your network. Any responses to the outbound requests are allowed back in, but unsolicited inbound traffic is not allowed. This means that while your Databricks clusters can reach out to the internet (for example, to fetch updates), the internet cannot reach in to access your clusters.</p><p>This setup ensures that all communication to and from your clusters goes through your Virtual Network, and that your clusters are not directly exposed to the public internet, enhancing the security of your Databricks environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/0*TEylY7vZdMvjDZR-" /><figcaption>Azure NAT Gateway outbound connection is used to interact with the control plane</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lmv8zaZ5tO0JBjjrFMBpgA.png" /><figcaption>Azure NAT Gateway is bound to the ‘worker-vnet’ subnets</figcaption></figure><h4><strong>VNET Injection</strong></h4><p>By default, when you create an Azure Databricks workspace, Databricks creates its own managed VNet (<strong>workers-vnet</strong>), with public and private subnets. However, with VNet injection, you can instead use your own VNet, giving you more control over your network configuration and enabling better integration with your existing network setup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*rSnAJv7R5KN-zf7_AMk65g.png" /></figure><ol><li><strong>Public Subnet</strong>: The public subnet is typically used for resources that need to communicate with the internet or other Azure services. In Azure Databricks, this subnet is used for <strong>driver nodes</strong> of the clusters that require outbound internet access for various reasons, such as downloading Maven packages.</li><li><strong>Private Subnet</strong>: The private subnet, on the other hand, is used for resources that do not need direct internet access. In Azure Databricks, this subnet is used for <strong>worker nodes</strong> of the clusters. They communicate with the driver nodes and other Azure services like Azure Blob storage or Azure Data Lake Storage, without needing a direct internet connection.</li></ol><blockquote>Please note that while VNet injection gives you more control, it also requires more network configuration on your part and may have additional considerations or limitations compared to using the default Databricks managed VNet.</blockquote><h4>Securing with Private Endpoints</h4><p>Before we talk about Private Endpoints, let’s look at the NSG rules that are provisioned by the databricks.</p><p>If you have set “<strong>Required NSG Rules</strong>” to “<strong>All Rules</strong>”; databricks will create a network security group associated with your worker VNET’s private and public subnets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-1g8ZD1m4vmbcTCnthtklw.png" /><figcaption>NSG Rules set to “All Rules”</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jGbFc5zmyKyJ4tFlrAhkmg.png" /><figcaption>NSG associated with public and private subnets</figcaption></figure><p>Databricks NSG creates a bunch of inbound and outbound rules, specifically, pay attention to one of the outbound rules, Microsoft.Databricks-workspaces_UseOnly_<strong>databricks-worker-to-databricks-webapp</strong>, where the interaction between the worker (data plane) to the databricks webapp (control plane) is allowed via port 443.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NWThO2_eKRc-dysldSfndg.png" /></figure><p>Now, let’s see what happens when you set the “<strong>Required NSG Rules</strong>” to “<strong>No Azure Databricks Rules</strong>”, the rule to allow communication with the control plane no longer exists. In other words, you will <strong>NOT</strong> be able to create a cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hDOPJlx9uBn3Xsf80rSzdg.png" /><figcaption>Required NSG Rules set to “No Azure Databricks Rules”</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zvYk-S6uKoYgBM3qhSRZcg.png" /><figcaption>Missing <strong>databricks-worker-to-databricks-webapp</strong> rule</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0VJkXPej8XUtJmyQN2do_w.png" /><figcaption>Cluster Creation failed, when Required NSG Rules is set to “No Azure Databricks Rules”</figcaption></figure><p>To resolve this, we need to create a private endpoint for the control plane in your workers’ virtual network. Assuming you already have a separate subnet for private endpoints, proceed to create a private endpoint for the ‘databricks_ui_api’ sub-resource. This ensures that all communication between the control plane and your clusters in the data plane occurs over a private network connection. This is often called as databricks backend-private endpoint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a5MpCptttRVeFDNzD9ISPQ.png" /><figcaption>Databricks backend-private endpoint: Creating Private endpoint b/w control plane and data plane</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*pqZyXF8-Uj6q374F" /><figcaption>Databricks backend private endpoint</figcaption></figure><p>Now, you should be able to create a cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TK4VsDGq5uzMYw-BTxl_TA.png" /></figure><h3>Securing Connectivity Between Users and Control Plane</h3><p>So far, we have successfully established a secure connection between the control plane and the data plane. Now, let’s look at how to secure communications between users and the control plane.</p><p>Although users are authenticated via Microsoft Entra ID, they can still access the Databricks workspace from the internet. The only way to prevent this is to <strong>disable </strong>“Allow Public Network Access.” Refer to the screenshot: if you disable public network access, you need to set “Required NSG Rules” to “<strong>No Databricks Rules</strong>”. In other words, you must configure a private endpoint connection between the control plane and the data plane.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ky5zBIksKkxKyfx5yzVsrw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xifkZrj0SCQyxxkNYDSvOg.png" /><figcaption>Disable Public Network Access: Requirements for NSG Rules</figcaption></figure><p>Once, you disable public network access, you cannot login into the Databricks workspace via the internet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KuZuuUwr9mDyeBBVn4R5uA.png" /><figcaption>Disable Public Network Access</figcaption></figure><p>Assume that users reside in their own VNET, let’s say “users-vnet” for example. We need to establish a private endpoint for users to access web app and databricks REST APIs. You need to create a new private DNS zone with ‘databricks_ui_api’ as the target sub-resource as a private endpoint in the users-vnet. This is also referred as frontend private endpoint.</p><blockquote><strong>Note</strong>: Make sure to create this private DNS zone in another resource group. Otherwise, it will override the settings with your backend private endpoint.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lbW2WD0NTt6OLM3Y" /><figcaption>Configure frontend private endpoint: Users &amp; Control plane</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*PyQHsVGKF90YPta5pELHGw.png" /><figcaption>Create frontend private endpoint</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zyvAA1gpkj6zBv00fV4oEw.png" /><figcaption>Frontend and backend private endpoints are created</figcaption></figure><p>Now, from your user’s workstation if you try to login, you will get this error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MvNcMqhKN_qn8QkHHO_brw.png" /></figure><p>To address this issue, you must add a browser_authentication private endpoint to support single sign-on (SSO) login callbacks to the Azure Databricks web application.</p><p>The “browser_authentication” workspace serves as a mediator, handling the communication between the user’s browser and Microsoft Entra ID.</p><blockquote>When you configure the “browser_authentication” target sub-resource for a workspace, this workspace acts as a secure intermediary for the SSO process for all workspaces in the same Azure region. This is applicable for all the other workspaces that share the same DNS zone.</blockquote><p>The private web auth workspace acts as a callback service for all workspaces in the region for user SSO during login, the private web auth workspace is unused until the next login. After login to your regular workspaces completes, Microsoft Entra ID will redirect users after login to the correct Azure Databricks control plane instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*han25OGCitNVqgSz4ErL1w.png" /><figcaption>Create web auth private endpoint</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rv3_EEvwGpRnjarqiK-oQg.png" /><figcaption>Web Authentication A records are added — based on the location of your databricks instance</figcaption></figure><p>Now, if you attempt to login, it will work now. The below screenshot also shows that you are able to create a cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XhjwC1sQLl2JEj-SZwZRLg.png" /><figcaption>User able to login after creation of web auth private endpoint</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*k7iScSArgVcRSxzv" /><figcaption>Final Architecture</figcaption></figure><h4>IP Access List</h4><p>Depending on your organization requirements, this feature allows you to define a list of trusted IP addresses from which users can access your Databricks workspace. Any attempt to access the workspace from an IP address not included in the list will be denied.</p><p>This is not part of our demo, but it is pretty self-explaintory from the below article.</p><p><a href="https://learn.microsoft.com/en-us/azure/databricks/security/network/front-end/ip-access-list-account">https://learn.microsoft.com/en-us/azure/databricks/security/network/front-end/ip-access-list-account</a></p><h3>References</h3><p><a href="https://learn.microsoft.com/en-us/azure/databricks/security/network/classic/private-link-standard">Enable Azure Private Link as a standard deployment - Azure Databricks</a></p><p>I hope this article provides a clear understanding of what happens behind the scenes and the step-by-step approach we took to configure private connectivity between users, the control plane, and the data plane. Please share your thoughts, and feel free to reach out — I am always here to help the community.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73395d4a803f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Azure Storage Encryption and Azure Disk Encryption]]></title>
            <link>https://medium.com/@vamsi.lakshman/azure-storage-encryption-and-azure-disk-encryption-af560f8708f3?source=rss-9a454943017f------2</link>
            <guid isPermaLink="false">https://medium.com/p/af560f8708f3</guid>
            <category><![CDATA[encryption]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[server-side-encryption]]></category>
            <category><![CDATA[azure-encryption-models]]></category>
            <category><![CDATA[disk-encryption]]></category>
            <dc:creator><![CDATA[Vamsi Munagala]]></dc:creator>
            <pubDate>Tue, 25 Apr 2023 16:30:02 GMT</pubDate>
            <atom:updated>2023-04-25T16:30:02.544Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we are going to talk about Azure Storage encryption and managed disk encryption models. Toward the end, I created an encryption flowchart that will help you decide on picking up the right encryption model based on your requirements. I am assuming that you understand the basics of what symmetric and asymmetric encryptions are. I highly recommend reading about the difference between Azure Disk Encryption and Server-Side Encryption on managed disks in this article, as most of them get confused between the two.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VyMKcMWPcM7Nt6PSFooKRA.png" /></figure><p>When we think of data, there are 3 places we can think of encrypting it:</p><p><strong>At Rest</strong>: Data is stored in Azure Managed disks or storage accounts.</p><p><strong>In Transit</strong>: Data is moving between different locations.</p><p><strong>In Use</strong>: Data being used by the server</p><p>So, let’s discuss the Encryption models in Azure in detail</p><h3>Server-Side Encryption (SSE)</h3><p>Let’s start talking about encrypting data in transit. Any communication between a client and an Azure storage account is encrypted via TLS. TLS encryption is enabled by “Secure transfer required”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8EWNRdzfKRbNz87M8Emqgw.png" /><figcaption>Azure storage account: Data-in-transit</figcaption></figure><p>We know the actual data resides in Microsoft’s data center infrastructure and by default, data in Azure Storage accounts are encrypted at rest by using a feature called “<strong>Azure Storage Encryption</strong>” or “<strong>Server Side Encryption (SSE)</strong>”. It uses a symmetric AES256 key called <strong>Data Encryption Key (DEK) </strong>to encrypt your data at rest. This feature — <strong>Server Side Encryption</strong> (SSE) generates a unique DEK for each blob, file, or queue message. It makes sense to encrypt large amounts of data using a symmetric key(s) because it takes less computation time to encrypt or decrypt data using the same key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dGQaQpQ7hloHRSjjf3wRuw.png" /><figcaption>Azure Storage: Server-Side Encryption</figcaption></figure><h4><em>Customer Managed Keys (CMK) and Platform Managed Keys (PMK)</em></h4><p>What if someone gets a handle on the Data Encryption Key (DEK)? We can take a step further in protecting DEK. Most cloud providers, including Azure, will protect DEK by encrypting with an asymmetric key called <strong>Key Encryption Key (KEK)</strong>. It is kind of a encryption wrapper around DEK, usually called envelope or <strong>encryption wrapping</strong>. You can bring your own key (<strong>Customer Managed Key — CMK</strong>) [OR] rely on the Microsoft platform to generate a key (<strong>Platform Managed Key — PMK </strong>) to encrypt DEK. Customer Managed Keys (CMK) are typically stored in Azure Key Vault where as PMK is stored in Microsoft Key Store which is not accessible to anyone.</p><blockquote><strong>Side Note</strong>: So when you hear about wrap key, unwrap key in Azure Key Vault, it is nothing but your KEK keys that are used to protect your DEK.</blockquote><p>Why do we have to protect DEK with an asymmetric key? By using asymmetric encryption, encrypted DEKs can be unencrypted only by those with access to the CMK or PMK, mitigating the key exchange problem of symmetric algorithms.</p><p>If you are using CMK, the customer is responsible for managing keys including the creation, rotation, and revocation of keys, whereas, for PMK, Microsoft manages the keys for you and you don’t need to worry about management tasks such as key rotation, backups or disaster recovery.</p><p>Typically, customers will use their own keys if they want to have an audit trail of when data is being encrypted and accessed and so on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xSRF3eugmMZCkmI-9eiVPQ.png" /><figcaption>Azure Storage: Customer Managed Key and Microsoft (Platform) Managed Key</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KlZFtNB7xZjt90XuOl0TmQ.png" /><figcaption>Customer Managed Key requires KeyVault</figcaption></figure><h4>Encryption Scopes</h4><p>So far we discussed that the Azure Storage account automatically encrypts your data at rest. But what if you want to manage encryption at the container or blob level? For example, you created a single storage account with different containers where each container belongs to one of your customers. As data in that Storage account belong to different customers, each customer wants to manage their own container with their own encryption keys. Under such scenarios, we create Encryption Scopes, and the customer can bring their own keys (CMK) OR can rely on the Microsoft platform (PMK) to protect data.</p><p><strong>NOTE</strong>: You can ONLY assign encryption scope for new containers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aPYXRabaEYvJRppqnP08fQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fpn9z0D_Rccs_Jz6nocFPw.png" /><figcaption>Azure Storage: Assigning Encryption Scope for a Container</figcaption></figure><h4>Double Encryption</h4><p>So far, the encryption of your storage account happens at the <strong>service </strong>level. If customers are looking for greater assurance of data, they can configure double encryption at the <strong>infrastructure</strong> level.</p><p>Infrastructure encryption can be enabled for the entire storage account, or for an encryption scope within an account. When infrastructure encryption is enabled for a storage account or an encryption scope, data is encrypted twice — once at the service level and once at the infrastructure level — with two different encryption algorithms and two different keys.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hrPpzadMrASveEyoETRR5Q.png" /><figcaption>Azure Storage: Double Encryption Scope</figcaption></figure><h4>Server Side Encryption (SSE) for Managed Disks</h4><p>Unless you are using Classic VMs, your VMs are using managed disks to store data. How do we encrypt them?</p><p>A managed disk is nothing but an abstraction of “<strong>storage account + page blob containing VHD</strong>”. Technically, it is still a storage account, so <strong>Server Side Encryption (SSE)</strong> is performed by the storage service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*cSMGvwMoxXJoHins8e_F3w.png" /><figcaption>A managed disk is nothing but a storage account with VHD behind the scenes</figcaption></figure><p>By default, managed disks are protected using <strong>Platform-Managed Keys (PMK).</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lJgeqbLweKQkWDWFYJdoNA.png" /><figcaption>Managed Disk: Platform Managed Key is enabled by default</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dvGlNpJIlTYJ8F8q9oK42g.png" /><figcaption>Server-Side Encryption for Managed Disks with PMK — Encryption at Rest</figcaption></figure><p>However, if you want to bring your own keys (CMK), then you have to create Disk Encryption Set(s) first as described in the next section.</p><h4><strong>Disk Encryption Set (DES)</strong></h4><p>If you want to use customer-managed keys then you have to create Disk Encryption Sets (<strong>DES</strong>) for managed disks and protect them with your keys. You create a DES for your managed disk and protect them with your keys. The cool thing about Disk Encryption Sets (<strong>DES</strong>) is, you can actually move existing or new disks to an existing DES and once they are in, they are automatically protected. To move an existing managed disk into DES, your VM must be deallocated first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9dJaNKg-iMJyztZ7h_EbyQ.png" /><figcaption>Managed Disk: 1. Creating a Disk Encryption Set with CMK</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NzKTfnLYUaDUSINdaTllPw.png" /><figcaption>Managed Disk: 2. Adding an existing managed disk to Disk Encryption Set</figcaption></figure><h4>Encryption at Host</h4><p><strong>Encryption at Host</strong> enables <strong>data encryption in transit</strong>. With (Disk Encryption Sets) DES, you will be able to encrypt managed disks but the data that gets transmitted and stored to its ephemeral disks such as Temporary disk and Cache are decrypted. If you are not aware, your temporary disk and cache are located <strong>on the host/physical server (the hypervisor, Hyper-V) where your Azure VM is hosted</strong>.</p><blockquote>A Temporary disk is <strong>not a managed disk</strong> and is not stored in Azure storage. So SSE or Azure Disk Encryption (ADE) cannot encrypt temporary disks.</blockquote><p>So when you enable <strong>Encryption at Host</strong>, the encryption <strong>starts and happens on data processed by the host VM</strong> <strong>(hypervisor)</strong> itself. The hypervisor intercepts any disk writes from the VM and encrypts before it is written to the physical storage. Similarly, when the data is read from the disk, the hypervisor decrypts the data before it is passed back to the Virtual machine.</p><p>The encrypted data is then sent back to the storage location — disk, table, blob — and is stored in its encrypted format. Therefore, the data processed and shared between the VM and its disks or other storage counterparts are encrypted, <strong>including in transit</strong>.</p><p>One thing to note is that since the encryption happens at the VM host, it is actually taking the physical host’s CPU cycles (and not the VM’s CPU) to perform encryption.</p><p>Note: You cannot enable Encryption at Host (EAH) if you have Azure Disk Encryption (ADE) enabled.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZmmrbrBEDQO_GEtU2PvliA.png" /><figcaption>Azure Encryption at Host</figcaption></figure><p>Let’s go a bit behind the scenes on how Encryption At Host (EAH) works:</p><ol><li>When you enable <strong>Azure Encryption at Host</strong>, the Azure Key Vault generates a new KEK (Key Encryption Key) and stores it securely.</li><li>The Hyper-V host generates a unique (Volume Encryption Key) VEK for each disk and stores it in the disk metadata.</li><li>The Hyper-V host requests KEK from the Key Vault and uses it to encrypt the VEK for each disk.</li><li>The encrypted VEK for each disk is stored in the disk metadata.</li><li>When the VM starts, the Hyper-V host retrieves the encrypted VEK for each disk from the disk metadata.</li><li>The Hyper-V host uses the KEK to decrypt the encrypted VEK for each disk.</li><li>When data is written to the data disk or OS disk, The Hyper-V host uses the decrypted VEK to encrypt data before it gets written to the disk.</li><li>When data is read from the data disk or OS disk, the Hyper-V host decrypts the data using VEK before it gets returned to the VM.</li></ol><p>When you have both Azure Encryption at Host (EAH) and Server Side Encryption (SSE), then your data will be encrypted twice. EAH will encrypt the data on the VM’s disks, and SSE will encrypt the data in the Azure Storage service.</p><h3>Azure Disk Encryption (ADE)</h3><p>Managed disks also support a second type of encryption which is <strong>Azure Disk Encryption (ADE)</strong>, which you can enable on the OS and data disks for your VMs or virtual machine scale sets. Windows and Linux operating systems come with built-in encryption features — Windows uses <a href="https://wikipedia.org/wiki/BitLocker">Bitlocker</a> and Linux uses <a href="https://wikipedia.org/wiki/Dm-crypt">DM-Crypt</a> to provide encryption for the OS disk and data disk.</p><p>When you enable ADE, your data is encrypted before it is sent to the storage account.</p><p>Please note that since these encryption features are native to OS, it actually utilizes the VM’s CPU cycles to perform encryption.</p><p>So, the keys that are used natively for encryption are stored in an Azure KeyVault via an extension. And for the KeyVault to support storing these keys, you need to enable Azure Disk Encryption for your KeyVault.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1oLhqvUGw4F4XrekyK6ihA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B5X5Ptnu4LrPe6JEaqb1TQ.png" /><figcaption>Enable ADE Encryption on OS and Data Disks</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T5BWn_XMsrufUn7sCNK4Hw.png" /><figcaption>Azure AD Extention is Installed after enabling ADE</figcaption></figure><ol><li>First, you need to create a new Azure Key Vault or use an existing one to store the encryption keys (KEK) that will be used to encrypt your VM’s data disks.</li><li>Once the Azure Key Vault is set up, you need to associate existing or new disks to enable Azure Disk Encryption (ADE).</li><li>This will install the Azure Disk Encryption (ADE) VM extension on your Windows VM. This extension is responsible for communicating with the Azure Key Vault to retrieve the encryption keys and manage the encryption process of your OS and Data disks on the VM.</li><li>ADE extension will create new Volume Encryption Keys (VEK) for each OS and data disk on the VM.</li><li>It will retrieve the KEK from Azure Key Vault and encrypts VEK and stores the encrypted VEK in the disk metadata.</li><li>The extension then encrypts the OS and data disks using BitLocker encryption and the encrypted VEK.</li><li>Once the encryption process is complete, you can verify that your VM’s data disks are encrypted by checking the BitLocker status of each disk in the Windows Disk Management tool. The disks should show as encrypted and locked.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2ele777mNyOqoPcENI4bTg.png" /><figcaption>BitLocker Turned ON</figcaption></figure><h3>Server-side Encryption (SSE) on Managed disks versus Azure Disk Encryption (ADE)</h3><p>SSE encrypts data on disks but it <strong>DOES NOT</strong> have access to the operating system and applications. So, when SSE enabled managed disk is created, the disk is encrypted with a disk encryption key (DEK) that is managed by Azure. The DEK encrypts all the data on the disk, but not the OS and the application files. So even though OS and application files are residing on an encrypted disk, they are not themselves encrypted by DEK.</p><blockquote><strong>Operating System files</strong> are boot loader, kernel, system libraries, configuration files, registry keys, etc. <strong>Application files</strong> are executables, libraries, configuration files, data files, etc. Examples include binaries and configuration files for web servers like IIS, and Apache, database engines like SQL, MySQL, and messaging services like Kafka or RabbitMQ.</blockquote><p>On the other hand, Azure Disk Encryption (ADE) enables encryption of the entire operating system and data disks for VMs, including temporary disks, and any additional disks. ADE uses a combination of BitLocker disk encryption and a customer-managed key stored in Azure KeyVault to encrypt and protect the data. This means that ADE can encrypt both the data at rest and the operating system and application files on the virtual machine.</p><p>You can use ADE and SSE together to provide end-to-end encryption for your data. When ADE and SSE are enabled together, the data is encrypted at the VM host level and then encrypted again at the storage account level. Together, it provides end-to-end encryption for your data and helps meet your compliance requirements.</p><p><a href="https://learn.microsoft.com/en-us/azure/security/fundamentals/encryption-models">Data encryption models in Microsoft Azure</a></p><h3>Encryption Decision Flow Chart</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rpXCctKsZayG8rDcxPPvpw.png" /></figure><p>Please post your comments if you have any questions related to Azure Encryption Models. A lot of research went into it and I would appreciate any feedback. Like and follow me if you are interested in learning more about Azure services as I typically try to go behind the scenes than what Microsoft documentation provides.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af560f8708f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Availability Sets in Azure]]></title>
            <link>https://medium.com/@vamsi.lakshman/availability-sets-in-azure-a5b6f2feb6c4?source=rss-9a454943017f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5b6f2feb6c4</guid>
            <category><![CDATA[proximity-placement-group]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[fault-tolerance]]></category>
            <category><![CDATA[availability-set]]></category>
            <category><![CDATA[fault-domains]]></category>
            <dc:creator><![CDATA[Vamsi Munagala]]></dc:creator>
            <pubDate>Fri, 06 Jan 2023 02:48:36 GMT</pubDate>
            <atom:updated>2023-01-06T02:48:36.147Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we will discuss what are availability sets while covering the basics of fault and update domains, a demo of availability sets, talk about a use case, and finally end the topic with an overview of proximity placement groups in conduction with availability sets.</p><h3>What are Availability Sets?</h3><p>As you may know, a physical data center location consists of several racks of servers. And each rack houses several servers with their own power supply and network switch.</p><h4>Fault Domain</h4><p>Each rack is called a fault domain because it shares a common power source and network switch and is subject to a single point of failure. For example, if the power supply or the network switch fails in a rack then only that rack of servers is affected while the remaining racks remain unaffected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sYaLXNucFmFBL_S5L96NNw.png" /><figcaption>Fault Domain 1 goes down due to switch failure</figcaption></figure><p>Obviously, you want your servers to be fault tolerant (or highly available), meaning you want to deploy servers in multiple racks so that they are not subjected to rack failures. And that is how Azure does when you set <strong>availability sets</strong> for your virtual machines. It makes sure that your servers are deployed in different fault domains.</p><blockquote>Availability Sets are about distributing your workload across racks within a single datacenter location, i.e. a single physical building.</blockquote><h4>Update Domain</h4><p>So, imagine I have to configure updates to my VMs (or maybe you rely on WSUS or Azure for patch management for that) — what do you think is the best way to do this? Obviously, it is not a great idea to apply updates on all VMs of your availability set as it might take down your entire application if those updates require a reboot.</p><p>So once you configure the availability set for your VMs, Azure also <strong>logically</strong> groups the VMs by assigning an <strong>Update Domain </strong>and so only those groups of machines are patched, updated, and rebooted together at the same time instead of updating VMs randomly.</p><blockquote>Each virtual machine in your availability set is assigned an update domain and a fault domain by the underlying Azure platform.</blockquote><p>Suppose, we want 5 instances of your VM and we set the availability set to have 2 fault domains (FD) and 3 update domains (UD). After you deploy your instances, your 5 instances are deployed in FD 0 and FD 1 racks respectively, and will logically assign an update domain for each of your VM in a sequential manner as seen in the below screenshot. Since we set 3 update domains, your fourth VM will logically be paired with the VM1 instance (i.e UD 0) and your fifth VM will be logically grouped with VM2 (i.e. UD 1).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XwvxGVceTFDZnIpr2Mztuw.png" /><figcaption>Availability Set example: 2 Fault Domains and 3 Update Domains</figcaption></figure><p>In the above scenario, UD 0 will go through planned maintenance first, which means that an upgrade and reboot happens to VM1 and VM4 machines only. After that, it moves to UD 1 where VM2 and VM5 will go through the upgrade process and so on. In this way, the users will not experience downtime.</p><h4>Demo</h4><p>For this demo, I am placing 5 instances of VMs in an availability set where the number of fault domains is set to 2 and update domains to 3.</p><pre># create resource group<br>az group create --name myResourceGroupAvailability --location eastus<br><br># create availability set with 2 fault domains and 3 update domains<br>az vm availability-set create \<br>    --resource-group myResourceGroupAvailability \<br>    --name myAvailabilitySet \<br>    --platform-fault-domain-count 2 \<br>    --platform-update-domain-count 3<br><br># Deploy 5 VMs within your availability set<br>for i in `seq 1 5`; do<br>   az vm create \<br>     --resource-group myResourceGroupAvailability \<br>     --name myVM$i \<br>     --availability-set myAvailabilitySet \<br>     --size Standard_DS1_v2  \<br>     --vnet-name myVnet \<br>     --subnet mySubnet \<br>     --image UbuntuLTS \<br>     --admin-username azureuser \<br>     --generate-ssh-keys<br>done</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R79s5WV1I6FfcGQ1bnqMTw.png" /></figure><p>As you can see these VMs are placed in 2 fault domains where VM1, VM3, and VM5 are placed in FD0, while VM2 and VM4 are in FD1.</p><p>As you have configured 3 update domains, VM1 is placed in UD0 first, VM2 in UD1, VM3 in UD2, then the process repeats itself — VM4 is placed in UD0, VM5 in UD1. You get the idea. This is the same representation of the diagram in the above-mentioned “Update Domain” section.</p><h4>Use Case</h4><p>Imagine that I have 3 tier web application, what is the best way to make it highly available and fault tolerant? Assume that your region only supports availability sets.</p><p>It would be a bad design if you have the 3-tier web application created under a single availability set because there is no guarantee that your order of your tiered VMs will distribute across different fault domains. For example, you may end up something like the below diagram. If FD 0 goes offline, the users will not able to see your site.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gTEGP3rUn3U2XcNCazl3RQ.png" /><figcaption>Availability Set: Bad Design</figcaption></figure><p>So it is advisable to assign an availability set for similar types of workload so that it gets distributed across multiple fault domains making your application fault tolerant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R0fG2ooCbv51N5UXV0RVUA.png" /><figcaption>Availability Set: Good Design</figcaption></figure><h3>Overview of Proximity Placement Group</h3><p>Now, what if latency becomes the most important criterion while the application availability is still important but takes a backseat?</p><p>In the above use case, there is no guarantee that your web, app, and DB tier availability set VMs are placed in a single data center location. It is likely that these each tiered availability sets might pick different data center locations within your region. For example, your web tier VMs may be placed in a data center location (say Alameda location) while your availability set for app tier VMs may select a different data center location (say Berkeley) and all these VMs are connected via Azure load balancers as seen in the above diagram.</p><p>If you have a high computing environment and want to see sub-millisecond latency, then you need to create a Proximity Placement Group.</p><p>Proximity Placement Group along with the availability set guarantees the placement of all your VMs in a single data center location.</p><h4>How does it work?</h4><p>Proximity Placement Group picks a data center location based on the VM’s size and capacity. It is a good practice to use an ARM template or Bicep or Terraform to provide a list of VMs capacities and SKUs beforehand to the proximity placement group so that the Azure control plane will select the best available data center location for you. Remember, not all data center locations provide the same size and capacity. So during the very first resource creation, the proximity placement group gets pinned to a data center location and the rest of the VMs belonging to the same proximity placement group will be deployed in that location.</p><h3>References</h3><p><a href="https://learn.microsoft.com/en-us/azure/virtual-machines/availability-set-overview">https://learn.microsoft.com/en-us/azure/virtual-machines/availability-set-overview</a></p><p>I hope you got an overall understanding of Availability Sets. In the next topic, I will discuss Availability zones.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5b6f2feb6c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What are Azure App Registration, Enterprise Apps, and Service Principals]]></title>
            <link>https://medium.com/@vamsi.lakshman/what-are-azure-app-registration-enterprise-apps-and-service-principals-9c3f0b15f9ec?source=rss-9a454943017f------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c3f0b15f9ec</guid>
            <category><![CDATA[multi-tenant]]></category>
            <category><![CDATA[enterprise-apps]]></category>
            <category><![CDATA[azure-active-directory]]></category>
            <category><![CDATA[azure-app-registration]]></category>
            <category><![CDATA[service-principal]]></category>
            <dc:creator><![CDATA[Vamsi Munagala]]></dc:creator>
            <pubDate>Fri, 16 Dec 2022 03:25:34 GMT</pubDate>
            <atom:updated>2022-12-16T22:40:31.630Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve often been asked this question several times, mainly about the relationship between Service Principals and App Objects.</p><p>So, let’s start with App Registration and why we need it.</p><p>If you are looking for a Microsoft Identity Platform (Azure AD) to provide authentication and authorization for your apps, it must go through the App Registration process. After successful registration, it enables trust between your app and your identity provider, which is Azure AD.</p><p>Now, a user who has access to register apps will create an identity or a representation of your app in the Azure Active Directory. This is nothing but an <strong>Application Registration</strong> process.</p><p>Login into Azure Portal, navigate to Azure Active Directory and see what happens after you <strong>Register an application</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CstD9VorbLXAPFOLnKYrpQ.png" /><figcaption>Azure App Registration</figcaption></figure><p>After successful registration of your app, you will notice the app is created in 2 places — “<a href="https://portal.azure.com/#view/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/~/RegisteredApps">App Registrations</a>” and “<a href="https://portal.azure.com/#view/Microsoft_AAD_IAM/StartboardApplicationsMenuBlade/~/AppAppsPreview">Enterprise applications</a>”. It created a <em>globally</em> unique identifier <strong>Application (client) ID </strong>in <strong>Application Registration</strong> and a <em>local </em><strong>Service Principal</strong> Object with the same name in the <strong>Enterprise Application</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5ELLOaaMrlR3s8MTw1EvOQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hqUa8hqXLRCvVXUvYvlOEA.png" /><figcaption>App Registration vs Enterprise Application</figcaption></figure><p>So why do we need a <em>local</em> and a <em>globally</em> unique identifier and what is the relationship between them?</p><h4>App Registrations</h4><p>Apps under “<strong>App Registrations</strong>” represent the actual application object. This is the place where you set the <strong>authentication and authorization requirements</strong> of your app. You are mainly focused on your application&#39;s needs and wants. For instance, under App Registration, you can set:</p><ol><li><strong>Define Scope</strong>: Which APIs should your app interact with (ex: Microsoft Graph)? What type of API permissions/scope does your app require (ex: User.ReadWrite.All, User.Read)?</li><li><strong>Application Permissions or Delegated Permissions</strong>: Can your application use its own permissions (app permissions) [OR] signed-in user permissions (delegated) to access Azure resources?</li><li><strong>Client Secrets or Certificates</strong>: Your app will pass credentials, i.e. either via a client secret or a certificate to Azure AD to prove its identity, and therefore request tokens</li></ol><p>As you may notice, in <strong>App Registrations</strong>, we configured authentication requirements such as client secret/certificates and authorization requirements such as defining scopes/API permissions.</p><h4>Enterprise Application</h4><p>For a single-tenant application, an Enterprise App with the same name is automatically created once you register an application. Keep tight, we will discuss Enterprise Apps for multi-tenant applications in the next section.</p><p>The configurations that you have set for your app under App Registrations are referenced by your <strong>Enterprise Application</strong>. Enterprise Apps is all about how your app should behave and work in your ‘<strong>local</strong>’ tenant. It is up to the administrator of your organization to control the settings of your app which should work within the constraints of your tenant.</p><p>Enterprise Apps mainly focuses on:</p><ol><li><strong>Consent tracking</strong>: When a client or user is trying to access Azure resources under the context of your registered app, it typically goes through an initial consent process. As an administrator for your tenant, you can track and control the consent process. For example, instead of regular users granting consent to an application, because of the sensitive nature of your organization, it may require that only admins can consent to it. Once administrator consent is recorded by Azure AD, your app can request tokens without having to request consent again.</li><li><strong>Scope/ API Permission management:</strong> Admins can review scope permissions that were set by your app under App Registration. Depending on the nature of your tenant, admins may restrict its scope or may allow users to consent to a subset of permissions rather than the entire set of permissions that your app is requesting for.</li><li><strong>Management</strong>: Set owners or groups to manage your app, configure SSO, and if required set any additional approval access before granting permissions, etc.</li></ol><h4>Service Principal</h4><p>So what are Service Principals? In simple terms, these are nothing but your “<strong>Enterprise Applications</strong>”. When you open this blade from your portal, you see the list of <strong>Service Principals</strong> of all your apps.</p><blockquote><em>Service Principal is </em><strong>local</strong> <em>to your tenant, whereas your Application/client ID is the </em>global <em>representation of your application and can be used across multiple tenants.</em></blockquote><p>As discussed earlier, once you register an app, Azure automatically creates a <strong>local</strong> representation of your app in the <strong>Enterprise App</strong>, which is nothing but your <strong>Service Principal</strong> object. This Service Principal is referring to your <strong>global </strong>application object. It inherits certain properties such as scope and permissions from that global application object and you can define what this app can actually do in <strong>your tenant</strong>, who can access the app, and what resources the app can access.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2iT3KJZEeRCd-35KHPJiCg.png" /><figcaption>Relationship b/w App Object and Service Principal</figcaption></figure><p>So, in summary, your global Application object is responsible for setting client secrets/certificates and defining scopes and API permissions, while your Service principal object reviews and controls consent tracking, modifies scopes in regulation with your tenant policies, and manages your app authorization in general.</p><p>But, what about applications that were registered outside your tenant?</p><h4>Multitenant apps</h4><p>In order to create an app that can be used across multiple tenants, you can select the below options depending on whether your app requires personal Microsoft accounts or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CedXXZVDF13e1OObIJCPdQ.png" /><figcaption>Multitenant App</figcaption></figure><p>Let’s walk through the below example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2drOlAtkhmm-xKnKds4sYw.png" /><figcaption>Multitenant Application</figcaption></figure><p>Let’s assume that you created and registered a multitenant app called demo-app in your home Tenant A. As part of the registration process, it creates a global application object (under App Registration) and a local Service Principal object (under Enterprise Apps).</p><p>Tenant B and Tenant C want to consume your demo-app. After providing the valid demo-app application link to these consumers, it will go through the consent process. The scope permissions that were set on demo-app’s definition will be displayed on the consent prompt requesting admin to grant permissions on specific resources. This provides consumer admins with enough information to determine if they can trust the client application or not.</p><blockquote><strong>Side Note:</strong> The app could be configured/designed to allow consent by users for individual use. If the app is configured to allow admin consent, it is mainly designed with an intent for the entire tenant.</blockquote><p>Once the consent is approved, only the Service Principal Object is created in the consumer’s tenant and <strong>NOT the application object</strong>.</p><blockquote><strong>Note</strong>: Service Principal is created either upon registration or consent (for multitenant OR SaaS applications)</blockquote><p>There will be ONLY one application object which lives in Tenant A. The Service Principal objects created in Tenant B and Tenant C are nothing but a local representation of your globally unique Tenant A’s application object and are referenced via the Application (client) ID.</p><h4>References</h4><p><a href="https://learn.microsoft.com/en-us/azure/active-directory/develop/app-objects-and-service-principals">https://learn.microsoft.com/en-us/azure/active-directory/develop/app-objects-and-service-principals</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c3f0b15f9ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Azure Kubernetes Networking: Services and Ingress Controllers]]></title>
            <link>https://medium.com/@vamsi.lakshman/azure-kubernetes-networking-services-and-ingress-controllers-c2ef16bbdd91?source=rss-9a454943017f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2ef16bbdd91</guid>
            <category><![CDATA[azure-kubernetes-service]]></category>
            <category><![CDATA[azure-application-gateway]]></category>
            <category><![CDATA[kubernetes-networking]]></category>
            <category><![CDATA[kubernetes-service]]></category>
            <category><![CDATA[nginx-ingress-controller]]></category>
            <dc:creator><![CDATA[Vamsi Munagala]]></dc:creator>
            <pubDate>Wed, 16 Nov 2022 17:03:14 GMT</pubDate>
            <atom:updated>2022-11-16T17:10:52.364Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I will explain AKS Services and Load Balancers in a simple and straightforward manner. If you want to have a background on AKS networking models, please read this <a href="https://medium.com/@vamsi.lakshman/overview-of-azure-kubernetes-services-networking-models-e3ca0591aebe">article</a>.</p><p>The topics I am going to cover here are why Services are needed, the purpose of having different types of Services, and how ingress controllers such as Nginx and Application Gateway are deployed.</p><h3>Services</h3><p>We all know that Pods are <strong>ephemeral</strong>, which implies that they can die or restart from failures. In such cases, they will acquire new IP addresses and it is often impractical to keep track of IP address changes or even design applications that rely on Pod IPs.</p><p>So, what can we do?</p><p>To address this very problem, Kubernetes came up with a concept called “<strong>Services</strong>”. You create a Service(s) and its associated Pods running behind it. A Service is nothing but a reliable “<strong>static” IP address</strong> that will point to Pod’s endpoints and when a request comes in, it will send to one of the pods in a round-robin manner. The word “<strong>static</strong>” is important here, meaning, the IP address on a Service will not change and you can rely on a Service rather than Pods for communication.</p><p><strong>How does a Service get its IP address?</strong></p><p>Similar to how Pods get their IP addresses from Pod CIDR, Services get their IP addresses from Service CIDR separate from your existing virtual network. It doesn’t matter which plugin you choose (Kubenet or Azure CNI), you will get a separate non-overlapping IP address for Services that <strong>exist ONLY within your cluster</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/342/1*vu6KLD2_xZewBSc_wpy46g.png" /><figcaption>Service CIDR</figcaption></figure><p><strong>How do Services communicate with Pods?</strong></p><p>The Pods are identified via labels which are nothing but a <em>key: value</em> pair defined in its metadata section. Typically, you would group similar pods as members to a Service, so in your Service deployment template, you provide a selector to match <strong>ALL</strong> labelsof a pod as seen in the below screenshot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iatO_qVDf2mA24sxMTESCQ.png" /><figcaption>Services: Pod ‘selector’</figcaption></figure><h4>LoadBalancer</h4><p>If Services exist only within your cluster, how can we access them from outside?</p><p>You can rely on <strong>Azure Load Balancer</strong> to communicate with your Services. <em>Hmm, but how? Azure Load Balancer cannot route to Services IP addresses as it has no knowledge of the Service CIDR range and it is only known inside the cluster</em>. You are right! Azure Load Balancer can only reach your worker nodes as they are part of your virtual network. This is where kube-proxy will play an important role. You configure your Azure Load Balancer’s backend pool to your worker nodes. And when a request comes to your worker node, kube-proxy does the job of mapping Azure Load Balancer’s Front End IP to the Service IP.</p><p>So this type of Service where we are using an external standard load balancer is called <strong>LoadBalancer</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pH0-Ywwzz0QVKQylu5IFMQ.png" /><figcaption>LoadBalancer Service</figcaption></figure><p>What happens when you create a public load balancer service in AKS?</p><p>Let’s go a bit behind the scenes to check the effects of deploying a Loadbalancer service type in AKS. I am using the below code for deploying simple nginx web app containers running behind a Loadbalancer.</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  labels:<br>    app: main-app<br>  name: main-app<br>spec:<br>  replicas: 2<br>  selector:<br>    matchLabels:<br>      app: main-app<br>  template:<br>    metadata:<br>      labels:<br>        app: main-app<br>    spec:<br>      containers:<br>      - image: nginx:latest<br>        name: nginx<br>        ports:<br>        - containerPort: 80<br>          name: nginx<br>---<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: main-svc<br>spec:<br>  type: LoadBalancer<br>  selector:<br>    app: main-app<br>  ports:<br>  - port: 80</pre><p>Once you deploy the above file, per the below screenshot, you will notice that it created our “main-svc” LoadBalancer with an EXTERNAL-IP. And the Port (80) that it needs to listen on and the health probe port (30360) that is being mapped to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eXEfPXL1VyHzvGttZSH_2A.png" /><figcaption>LoadBalancer Service</figcaption></figure><p>Once you browse the http://EXTERNAL-IP&gt; , you will notice that it launches your nginx default web page.</p><p>Let’s take a sneak peek behind the scenes in Azure. It created your service’s (EXTERNAL-IP) public IP address resource and added it to the frontend IP of your “kubenetes” load balancer.</p><blockquote>“kubernetes” is a default load balancer (ClusterIP) that is created when you provisioned your AKS cluster.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cMi0dkz4dvSBeT_fKU2rnA.png" /><figcaption>kubernetes: Frontend IP</figcaption></figure><p>If you take a look at the below load balancing rule, you will understand the association of your Services (EXTERNAL-IP) frontend IP with your backend pool (worker nodes). The configured backend port is your service port and the health probe is the one that your service port (80) is being mapped to (30360).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lp31uLcs9G3uySJD_GGEGA.png" /><figcaption>Azure Load Balancer: kubernetes: Load balancing rule</figcaption></figure><p>By default, all worker nodes’ NICs are associated with a single network security group. A new inbound rule is also added which signifies that when traffic originates from the internet must be destined to your load balancer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZALHQVxvepQuxXW4434Y_g.png" /><figcaption>Network Security Group: Worker Nodes</figcaption></figure><p>So what are other types of Services we have?</p><p>You may ask what the reason behind having these different types of Services is. Well, every type of Service serves a different purpose just like what <strong>Loadbalancer</strong> provides. Let’s look at the other type of Services:</p><h4><strong>ClusterIP</strong></h4><p>This is the most commonly used default Service type.</p><p>We have seen how Services have configured its pod endpoints (via selector), but if pods have multiple container applications, how can Services reach a particular app?</p><p>Remember, in a multi-container pod scenario, the apps communicate with each other via localhost:&lt;port&gt;. (<em>Please refer to the ‘</em><a href="https://medium.com/@vamsi.lakshman/overview-of-azure-kubernetes-services-networking-models-e3ca0591aebe"><strong><em>Container to Container communication in the same Pod</em></strong></a><strong><em>’</em></strong><em> section for more information</em>)</p><p>Let’s say you have a Service accessible on port 2000, so when a request comes to this Service via that port, it is sent to one of its member pods based on theselector . The way your Service forwards its request to your desired container app is by looking at its targetPort. Note that every container app listens on a port (containerPort). <strong>The Service </strong><strong>targetPort must match the Pod’s </strong><strong>containerPort</strong>. In the below example, I want my Service to reach the <em>main-app</em> container which is listening on the port (containerPort) 3000. In this case, we would set the Service targetPort to 3000 which points to your <em>main-app</em> container.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZS8wkd3mR1cv91WwxtwBHQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*834I_6_MPvflauM4oUa2Ug.png" /><figcaption>ClusterIP Service (Default)</figcaption></figure><h4>Multi-Port</h4><p>In the above example, we have seen multi-container pods running behind a single Service listening on a single port. But you may run into a scenario where you may need multiple ports to a service. When you configure multiple ports on a Service, you call it a <strong>Multi-Port Service</strong>.</p><p>Let’s pick a use case for it. Say, that you have a multi-container pod, one container serving up the main application while the other container is a node exporter scraping metrics from the main app continuously. Now, we configured a Service with 2 ports, one of them pointing to the main app container port while the other one is pointing to the node exporter port. The clients from outside may hit the service port configured to serve up the main application container, whereas your internal Prometheus server is communicating with the other service port to pull the metrics from the node exporter container app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*SB6aue4Ms1fKl4BTLEKtng.png" /><figcaption>Multi-Port Service</figcaption></figure><h4>Headless</h4><p>So far we have seen that Service selects a Pod in a round-robin fashion. Suppose you have stateful applications and want to direct your traffic to a particular Pod, then relying on a <strong>Headless</strong> Service will benefit you.</p><p>For example, let’s say that you have database pods running behind a Service. A frontend pod must ONLY contact the master database to perform database operations and not with its secondary database pod its sole purpose is read-only and performs replication with its master.</p><blockquote>Headless Service will not act as a Load Balancer. It just returns its member Pods.</blockquote><p>How can the <em>main-app</em> pod communicate with the <em>master-db</em> pod?</p><p>The <em>main-app</em> pod must know the IP address of the <em>master-db</em> pod in advance to establish communication. And as you may recall from the intro, it is very inefficient as Pods are ephemeral.</p><p>Why do we need a headless service in the first place, if a client app has to know Pod IPs ? :). This is where your headless service plays a role. The client app can rely on your headless service to do a <strong>DNS lookup (nslookup) </strong>and it returns the set of Pod IPs. The client app can then pick the right Pod IP from the DNS lookup result and start communicating with it.</p><blockquote>If you perform a DNS lookup on ClusterIP Service it will return the IP address of your Service because your ClusterIP Service acts as a true load balancer whereas when you perform a DNS lookup on your headless service, it simply returns its member pod IPs.</blockquote><p>In the below example, the main-app pod performs a DNS lookup on your headless service and it returns back with the Pod IP addresses. The <em>main-app</em> will pick the <em>master-db</em> IP address and performs database operations on it directly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*JVoqgkPj1LzElvkgeBatcQ.png" /><figcaption>Headless Service</figcaption></figure><h4>NodePort</h4><p>In addition to creating a default Service (ClusterIP) for your member pods, NodePort Service also adds a <strong>static </strong>port to your <strong>worker nodes. </strong>The reason behind it is to gain direct access to your containers running inside your cluster.</p><p>Opening up node ports on your worker nodes introduces security loopholes and unnecessary access to other resources running in your cluster, hence it is not recommended in production environments. However, this option works fine if you want to quickly test your external application and its interaction with app containers.</p><p>Let’s take the below example, you want to access your main-app container externally from a browser. So, you enter http://&lt;node_ip:node_port&gt; in your browser and the following happens:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*TTE3lFI6k9mhZJRz9cIOxw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_gTrXK5L8_bFtnqpkEy9GA.png" /><figcaption>NodePort Service</figcaption></figure><ol><li>The request comes to the desired worker node</li><li>The request is then forwarded to your default Service port 2000. But how? Take a look at the Service (kubectl get svc), you will notice that port mapping is established between the worker-node’s NodePort and Service port.</li><li>The Service, acting as a load balancer, will forward your request to one of the member Pods and launches the container app that is listening on the containerPort.</li></ol><h3>Layer 7 Load Balancers / Ingress Controllers</h3><p>So far we have seen how Azure Load Balancer can communicate with Services from outside your cluster. It is a Layer 4 load balancer that understands only IP addresses and ports (i.e. supports only TCP and UDP protocols), whereas, Layer 7 load balancers such as <strong>nginx </strong>and <strong>Application Gateway</strong> understands application-level HTTP and HTTPS protocols. Layer 7 load balancers have several advantages as they support path-level routing, SSL offloading, etc. (I will cover them in great detail about different types of Load Balancers in my upcoming article).</p><p>You have to pay a bit more attention to how different L7 load balancers behave in our AKS architecture.</p><h4>Nginx</h4><p>Let’s consider Nginx webserver. So, Nginx controllers are deployed as pods and now instead of having Service talking to Pod endpoints, it will talk to Nginx. Nginx controllers will act as a proxy and based on its routing rules (ex: path-based routing) will direct the traffic to its target application pods.</p><p>The flow is going to be as follows:</p><p>Azure Load Balancer → Worker nodes → Service → Nginx → Pods</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R06LjkuXibgK_aCtZVc9Kw.png" /></figure><ol><li>So, you still have your Azure Load Balancer serving external traffic and its backend pools are AKS worker nodes.</li><li>Azure Load Balancer will direct the traffic to one of its worker nodes.</li><li>kube-proxy will map Azure Load Balancer’s Front-end IP to the Service IP.</li><li>The Service will perform a round-robin and will hit one of the Nginx controllers.</li><li>Nginx controller will carry out Layer 7 type of activities, for example, if you have a path-based routing configured, it will reach your target application pod if a rule is matched.</li></ol><h4>Azure Application Gateway Ingress Controller</h4><p>Now, let’s talk about Azure Application Gateway. Its architecture is different from the Nginx ingress controller. Nginx controllers are called “<strong>Ingress Controllers</strong>” because they are deployed inside your cluster whereas Azure Application Gateway Ingress Controller is deployed differently. Let’s see how:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/0*VI_Hn1C9q8DH_WYS.png" /><figcaption>Application Gateway Ingress Controller (AGIC)</figcaption></figure><ol><li>You deploy an Application Gateway Ingress Controller (AGIC) as a pod in your cluster.</li><li>AGIC will instruct Azure Resource Manager (ARM) to deploy Azure Application Gateway based on the rules specified in its manifest file.</li><li>Azure Resource Manager (ARM) will deploy Azure Application Gateway and configures its backend pools to Pod IP addresses.</li><li>AGIC continuously monitors the state of its AKS cluster and reports any pod changes to ARM. ARM will update the Application Gateway to reflect those changes.</li></ol><p>Since Application Gateway’s backend pools are AKS Pod IPs, we can infer that only <strong>Azure CNI</strong> is supported, for obvious reasons, that Pod IPs get real IP addresses from its Azure Virtual Network subnet.</p><p>However, recently it started supporting <strong>Kubenet</strong> too and the way it does is it <strong>copies the Route Table associated with the worker node subnet to the application gateway subnet</strong>. So Application Gateway knows how to reach its destination pods by referencing its azure route table.</p><p>Thank you so much for reading my blog. I hope it helps you understand Services and Ingress Controllers. I’d appreciate any feedback for improvement. Please leave a comment if there are any topics that you would like me to cover.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2ef16bbdd91" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Overview of Azure Kubernetes Services Networking Models]]></title>
            <link>https://medium.com/@vamsi.lakshman/overview-of-azure-kubernetes-services-networking-models-e3ca0591aebe?source=rss-9a454943017f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3ca0591aebe</guid>
            <category><![CDATA[azure-kubernetes-service]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[azure-networking]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Vamsi Munagala]]></dc:creator>
            <pubDate>Thu, 03 Nov 2022 18:23:14 GMT</pubDate>
            <atom:updated>2022-11-03T18:23:14.796Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I would like to discuss AKS Networking models, specifically <strong>Kubenet </strong>and <strong>Azure CNI</strong>. I aim to explain the basics in simple language and help you understand the difference between these models.</p><p>It is not mandatory but will be helpful if you have a basic understanding of Azure networking, an overview of AKS cluster components, and Linux network namespaces.</p><h3>AKS Cluster Architecture</h3><p>Before diving in, let’s understand AKS Cluster’s control and worker nodes plane management:</p><p>Azure manages the <strong><em>Control plane</em></strong> components such as <em>kube-apiserver, etcd, kube-scheduler, </em>and <em>kube-controller-manager.</em> In other words, you do not have direct access to the control plane and the entire orchestration and its control-level operations are handled by Microsoft.</p><p>Whereas, you (or the customer) are going to manage <strong><em>worker-nodes</em></strong> where you create pods to run your microservices or applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*K3ob7NaisQXfk2K7A5Q7nw.png" /><figcaption>Azure Kubernetes Cluster Architecture</figcaption></figure><h3>AKS Networking Models</h3><p>Kubernetes should abide by some networking rules as mentioned below:</p><ul><li>All pods can communicate with each other on all worker nodes.</li><li>Agents or applications running in a node must be able to communicate with all pods on that node. For instance, <em>kubectl </em>or <em>kube-proxy</em> running on the nodes should be able to contact pods.</li><li>All pods within a cluster can communicate with the other pods, and all nodes can communicate with all pods in the cluster without using NAT (Network Address Translation).</li></ul><p>There are 2 main networking plugins that I want to talk about, which are, <em>Kubenet </em>and <em>Azure CNI</em>. There are 3rd party CNI plugins such as Calico, Flannel that are not covered in this article.</p><blockquote>One fundamental difference between these networking plugins is the ways they adopt different IP addressing schemes for their pod assignment.</blockquote><p>Nodes can either be your virtual machines or virtual machine scale sets and they typically get their IP addresses from your existing virtual network.</p><p>As discussed above, one of the networking rules is there is <strong>NO Network Address Translation (NAT)</strong> requirement for pods which means that every pod has a <strong>unique</strong> IP address and can communicate with other pods in its cluster using the Pod’s IP address.</p><h3>Kubenet</h3><p>With the <em>kubenet</em> plugin, the nodes will get their IP addresses from your virtual network’s subnet whereas your pods will get their IP addresses from a separate unique <strong>Pod CIDR </strong>range (a separate subnet actually) that must not overlap with your nodes&#39; subnet or on-premises network.</p><blockquote>In other words, your pods <strong>DO NOT</strong> get IP addresses from your virtual network’s subnet.</blockquote><p>Let us assume that we want an AKS cluster with 4 nodes using an existing VNET, say we have a Node subnet with its address prefix 192.168.1.0/24.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mNjlcgLO0Hc8pNpCiaXJNg.png" /><figcaption>Node IP Assignment</figcaption></figure><p>After provisioning your AKS cluster with Kubenet plugin, you will see that Azure created a separate non-overlapping Pod CIDR for pods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*Vk2HB9QZaTrLfz7DrYy_IQ.png" /><figcaption>Kubenet Plugin: Pod CIDR</figcaption></figure><p>Azure carves out /24 address space from the <strong>Pod CIDR</strong> to each of its nodes for Pod assignment which means around 251 IP addresses of pods can be created but the limit set by Kubenet is <strong>110 pods</strong> per node. So why do we need extra IP addresses for? Because it needs room for pod upgrades or scaling.</p><p>As you can see in the below diagram, Pods per node gets unique /24 of its <strong>Pod CIDR</strong> addresses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oF1Lyz-f8FWdYtygD1PsnA.png" /><figcaption>Kubenet: Pod CIDR Assignment</figcaption></figure><p>Let us cover different connectivity scenarios. Before we do that, you must have a basic understanding of how Linux network namespaces work. For example, every pod gets an isolated network namespace (has its own networking stack, firewall, routing table, etc.) independent from its host’s (node) root network namespace.</p><h4>Pod-to-Pod Communication in the same Node</h4><p>Once pods are created in the host node, the following happens:</p><ol><li>As soon as a pod is created, container runtime (<em>containerd</em>) creates a network namespace, and a special hidden container called a “pause” container that holds the network namespace and enables any new containers to join the network.</li><li><em>Kubenet </em>handles the rest of the network management of its pod i.e. it creates a local interface (eth0), assigns an IP address for the pod, and attaches the pod’s local network (eth0) to the root network namespace (veth).</li><li><em>Kubelet </em>takes care of creating virtual interfaces (veth0, veth1, …) in the node’s root namespace which gets paired up with its respective pod’s local network interface (eth0) establishing connectivity between the local pods and their host node.</li><li>A layer 2 virtual ethernet bridge (cbr0) in the node’s root namespace connects all these virtual interfaces (veth0<em>, </em>veth1<em>, …</em>) to facilitate communication between the pods. In the below screenshot, you will see that all veth’s are connected to the cbr0 bridge</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*meGq3RwNiUeJUyqOdUn55w.png" /><figcaption>Kubenet: cbr0 bridge</figcaption></figure><p>Say, a Pod1 needs to communicate with Pod2 within the same node.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*ivRZshmB-_oMSopxqavV2A.png" /><figcaption>Pod-to-Pod communication on the same node</figcaption></figure><ol><li>Since Pod2 is on the same network (10.244.0.0/24) as Pod1, Pod1 sends the packet to its default eth0. This interface is paired with its Node1’s veth0 and serves as a tunnel. And the packets are sent to the root namespace on the node.</li><li>The ethernet bridge (cbr0), acting as an L2 virtual switch, checks its cached lookup table for the destination pod’s address. If it is not found, it broadcasts an ARP request on all connected devices. Pod2 responds back with its MAC address, and the bridge will update its ARP cache entries.</li><li>The cbr0 bridge will do a lookup in the table, finds Pod2&#39;s MAC address, and sends it to the correct endpoint which is Pod2’s veth1.</li><li>The packet reaches Pod2’s eth0<em> </em>interface inside its namespace.</li></ol><h4><strong>Container to Container communication in the same Pod</strong></h4><p>Multi-container apps (such as sidecar or init containers) run on the same pod along with other containers. Since these containers are local to a pod, they all share the same network namespace of its pod. In other words, containers running in a pod will share the network and other resources available to a pod. Thus these containers communicate with each other using <em>localhost:&lt;port&gt;</em> (or <em>&lt;pod-ip-address&gt;:&lt;port&gt;</em>) endpoints exposed by them.</p><h4>Pod-to-Pod Communication in a different Node</h4><p>Let’s consider a use case where Node 1’s Pod1 needs to communicate with Node 2’s Pod2 within the same node.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eJeObiMg3leeVOs_femXxg.png" /><figcaption>Pod-to-Pod communication on different nodes</figcaption></figure><ul><li>Pod1 sends the packet to its default eth0. This interface is paired with its Node1’s veth0 and serves as a tunnel. And the packets are sent to the root namespace on the node.</li><li>Since Pod2 is on a different network (10.244.<strong>1</strong>.0/24) than Pod1 (10.244.<strong>0</strong>.0/24), the ethernet bridge (cbr0), simply forwards (IP forwarding) the request to the default eth0<em> </em>without broadcasting any ARP request. [Note that IP forwarding is enabled on every node].</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MwA9832i9gCMa69IrZu9Eg.png" /><figcaption>IP Forwarding enabled on each node</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ql-2jX_KErI9sMQQP2Wr7g.png" /><figcaption>Node’s route information</figcaption></figure><ul><li>Node 1’s Pod1 can now reach the Azure virtual network subnet but it still cannot reach Node 2’s Pod2 because the Azure virtual network <strong>is unaware of Pod’s subnet (Pod CIDR)</strong>. So where else does it need to look for Pod information? <strong>Azure Route table to the rescue</strong>. This route table (UDR) is attached to the Node subnet and has defined route information on every assigned <strong>Pod CIDR</strong> prefix. As you can see in the below screenshot, the next hop for 10.244.<strong>1</strong>.0/24 is Node 2’s IP address 192.168.1.5.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vx6dfiSjhjNsAnnY5T5baA.png" /><figcaption>Kubenet: Azure Route Table</figcaption></figure><ul><li>The packet is routed to Node 2’s default interface which is eth0.</li><li>Everything goes in the reverse order from here, the packet reaches the (cbr0) bridge which issue an ARP request, identifies Pod2’s MAC address, and sends the packet to the destined endpoint which is Pod2’s eth0.</li></ul><h4>A bit deeper into SNAT</h4><p>Let’s take a look at when Network Address Translation (Pod IP → Node IP) happens. For that, we have to take a look at the iptables. It includes <em>PREROUTING </em>(for altering packets as soon as they come in), <em>OUTPUT </em>(for altering locally-generated packets before routing), and <strong><em>POSTROUTING </em>(for altering packets as they are about to go out)</strong>. Let’s look at the <em>POSTROUTING </em>chain on one of our nodes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*medReLJOWeIK6QHascpiIA.png" /></figure><p>So, if any incoming source (0.0.0.0/0) is trying to reach the Pods (10.244.0.0/16), the traffic should go to the RETURN chain which basically means that it should just go out as is. <strong>That means that when a pod sends traffic to another pod, it retains its Pod IP</strong>.</p><p>However, if the traffic is not destined for the Pods in the cluster, it should go to the MASQUERADE chain, which means that it allows all outgoing connections to go through Source NAT (SNAT), i.e. it sets the source IP to the node IP address. So if a pod has to access other resources in the Azure virtual network, it gets NAT’ed to its Node IP address.</p><h3>Azure CNI</h3><p>CNI (Container Network Interface) is nothing but a standard <a href="https://github.com/containernetworking/cni/blob/main/SPEC.md">specification</a> template with a defined set of rules in order to create a programmable plugin for creating and configuring networking namespace for containers.</p><p>The plugin uses a group of libraries and specifications (usually written in Go) that is responsible for defining an interface for configuring the network, provisioning IP addresses, and maintaining connectivity with multiple hosts.</p><p>Using the <a href="https://github.com/Azure/azure-container-networking/blob/master/docs/cni.md">Azure CNI plugin</a>, all pods will get <strong>real IP addresses</strong> from the node’s subnet itself. So it is very important to plan IP addresses for your cluster beforehand as you may exhaust all your IP addresses if more pods are required in the future or if the demand for your application grows.</p><p>Just as with Kubenet, Azure CNI is responsible for creating the veth pair, linking veth to the container network namespace, and assigning the IP address to the Pod (eth0).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IQJ7WG03rlujFpRMAgF-DQ.png" /><figcaption>Azure CNI: Pod IP addresses from the Node subnet</figcaption></figure><p>As you can see in the below image, there is <strong>NO Pod CIDR</strong> address for pod assignment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*egTGX8KVy1GE2moEdR8Vxw.png" /><figcaption>Azure CNI: Networking</figcaption></figure><p>By default, we can have 30 pods per node but you can extend the limit to 250 with the help of the new dynamic IP allocation capability in Azure CNI.</p><p>These actual POD IP addresses will get placed on the <strong>NIC</strong> of the VM of the container host. In the below screenshot, you can see that 1 IP is assigned for the host, and the remaining 30 IPs are reserved for pods in that node.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y3nb34_tsoEf5pHBzwVk1w.png" /><figcaption>Azure CNI: Node and Pod NICs</figcaption></figure><p>Since all the nodes and pods are directly connected to Azure VNET, there is no need for any packet translation and all packets are sent as is.</p><h4>What happened to the Azure CNI (azure0) bridge network?</h4><p>As you may have seen with kubenet, all the host-side pod veth pair interfaces are connected to thecbr0<em> </em>bridge. So Pod-Pod intra VM communication and the remaining traffic goes through this bridge.</p><p>Let’s take a look at our Azure CNI plugin. Let’s run thebrctl show command to get all the interfaces that are attached to the node’s software bridge. There are none.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PuuXZ5tKSD17pPw1FVxG_w.png" /><figcaption>Command to show bridge information</figcaption></figure><p>Starting with version 1.2.0, Azure CNI sets Transparent mode as default for single tenancy Azure CNI Linux deployments. <strong>Transparent mode is replacing bridge mode</strong>.</p><p>So all host-side pod veth pair interfaces are directly added to the host network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KPYC8WN5oGPmoyim4im_sg.png" /><figcaption>Azure CNI: Getting all IP Addresses on the node</figcaption></figure><p>So any Pod-to-Pod communication is dictated by your IP routes table which your Azure CNI takes care of. In other words, Pod-to-Pod communication is happening over <strong>layer 3 routing rules</strong>. As the traffic comes with a destination Pod IP address, it will be sent directly to the Pod’s host side veth pair interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MJ4knt-HLZA9RwrEzwlXUw.png" /><figcaption>Azure CNI: Transparent Mode: Node Route Table</figcaption></figure><p>This is actually good news as Transparent mode reduces a lot of network complexity that you find with your bridge network. It performs better in Intra Pod-to-Pod communication in terms of throughput and latency.</p><p>I hope you enjoyed this article. In the next article, I will talk about Services and Load Balancers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3ca0591aebe" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>