<?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 Osamaazhar on Medium]]></title>
        <description><![CDATA[Stories by Osamaazhar on Medium]]></description>
        <link>https://medium.com/@osamaazhar591?source=rss-7fd53afe0b6c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*s6vdr7ivLyu-u0-Y</url>
            <title>Stories by Osamaazhar on Medium</title>
            <link>https://medium.com/@osamaazhar591?source=rss-7fd53afe0b6c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 12:55:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@osamaazhar591/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[Understanding Transformers from Scratch — Part 2 From Self-Attention to Full Transformer Blocks]]></title>
            <link>https://medium.com/@osamaazhar591/understanding-transformers-from-scratch-part-2-from-self-attention-to-full-transformer-blocks-3d0a6f9a1578?source=rss-7fd53afe0b6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d0a6f9a1578</guid>
            <dc:creator><![CDATA[Osamaazhar]]></dc:creator>
            <pubDate>Thu, 14 May 2026 11:56:47 GMT</pubDate>
            <atom:updated>2026-05-14T11:56:47.042Z</atom:updated>
            <content:encoded><![CDATA[<p>If you haven’t read <strong>Part 1</strong> yet, pause right here and go check it out first. I took a silly YouTube search like “Pakistan vs Bangladesh cricket highlights” and used it to understand embeddings, positional encoding, QKV, and how self-attention makes every word gossip with every other word.</p><p>By the end of that, “highlights” finally realized it was about a cricket match and not, say, festival highlights. Pretty cool, right?</p><p>But here’s the thing — that whole attention magic we covered? That was only <strong>half</strong> of one Transformer layer. The model still has more work to do before it can move to the next layer. Let’s continue the journey.</p><h3>Quick Recap: Where We Are Now</h3><p>After self-attention, each token (each word) now holds a richer vector. It has collected useful context from the rest of the sentence.</p><p>“Highlights” has now picked up strong signals from “cricket”, “Pakistan”, and “Bangladesh”. Nice.</p><p>But the model doesn’t just forward this and call it a day. It does two more important things inside every layer:</p><ol><li>Residual Connections + Layer Normalization</li><li>Feed Forward Network (FFN)</li></ol><p>These steps look simple, but they’re the reason deep models like GPT don’t collapse during training.</p><h3>Step : Residual Connections — The Smart Shortcut</h3><p>Imagine you’re learning a new skill — let’s say driving. Every lesson you learn something new, but you don’t want to forget how to use the mirrors or change gears. You build on what you already know.</p><p>That’s exactly what <strong>residual connections</strong> do.</p><p>After self-attention finishes its job, the model takes its output and <strong>adds the original input back</strong> to it:</p><blockquote><em>New Output = Self-Attention(Output) + Original Input</em></blockquote><p><strong>Why is this such a big deal?</strong></p><ul><li>It creates a direct highway so important information doesn’t get lost in deep layers.</li><li>The model can still remember the original meaning easily.</li><li>It makes training super deep networks (GPT has many layers) way more stable.</li></ul><p>I love this trick. It’s like the model saying, “I’ll learn new stuff, but I’m keeping my old notes too.”</p><h3>Step : Layer Normalization — The Chill Pill</h3><p>After adding the original input back, the numbers in the vectors can go a bit crazy — some become huge, others tiny. That chaos makes training difficult and slow.</p><p><strong>Layer Normalization</strong> jumps in like a calm friend who says, “Relax buddy, let me fix these numbers.”</p><p>It adjusts and scales everything so the values stay balanced. Think of it as the model taking a quick deep breath and resetting before the next step.</p><p>Tiny change. Massive difference in training speed and stability. The researchers who added this must have thrown a party when they saw how well it worked.</p><h3>Step : Feed Forward Network (FFN) — Private Thinking Time</h3><p>Self-attention is all about words talking to each other — like a group discussion.</p><p>Now comes the <strong>Feed Forward Network</strong>. This part gives each token some alone time to think deeply about what it just learned.</p><p>It’s basically a small neural network (two linear layers with an activation function like GELU in between) that processes each token separately.</p><p><strong>Simple way to remember it:</strong></p><ul><li>Attention = Group discussion</li><li>Feed Forward = “Okay, now go sit alone and reflect on everything”</li></ul><p>This step adds non-linearity and helps the model learn more complicated patterns. It’s where the real individual “thinking” happens.</p><h3>The Complete Transformer Block (This is What Actually Matters)</h3><p>Here’s how one full <strong>Transformer Decoder Block</strong> works in practice:</p><ol><li>Input arrives (embeddings + position)</li><li>Self-Attention (words talk to each other)</li><li>Residual Add + Layer Norm</li><li>Feed Forward Network (individual thinking)</li><li>Another Residual Add + Layer Norm</li><li>Output heads to the next block</li></ol><p>This same block gets repeated many times.</p><p>Here’s a clean diagram to help you visualize it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i5-Nk3WEL6xHnLNbVlp_4A.jpeg" /></figure><h3>Why Stack So Many Blocks? (GPT’s Real Power)</h3><p>One block is decent. But stacking <strong>many</strong> of them (12, 24, 48, even 96+ layers in big models) is where the magic explodes.</p><p>Each layer learns something different:</p><ul><li><strong>Early layers</strong>: Basic stuff — grammar, nearby word connections</li><li><strong>Middle layers</strong>: Overall sentence meaning and logic</li><li><strong>Higher layers</strong>: Complex reasoning, knowledge, and coherent thinking</li></ul><p>This layered learning is exactly why GPT can write essays, crack jokes, and code better than many humans.</p><h3>The Big Picture: Decoder-Only Architecture (The GPT Way)</h3><p>Just a reminder — the original 2017 “Attention Is All You Need” paper had both an Encoder and a Decoder.</p><p>Modern GPT models dropped the Encoder and only use the <strong>Decoder</strong> part. That’s why they’re called decoder-only models.</p><p>What makes them special:</p><ul><li><strong>Causal (Masked) Attention</strong>: Words can only look at previous words, never future ones. This is crucial for generating text one word at a time.</li><li><strong>Autoregressive</strong>: They keep predicting the next word again and again.</li><li><strong>Huge scale</strong>: Billions (sometimes trillions) of parameters.</li></ul><p>This simple but powerful design is why GPT feels so natural when it continues your sentences.</p><p><strong>Final Thought</strong></p><p>The real genius of Transformers isn’t just the fancy attention mechanism. It’s the beautiful teamwork between:</p><ul><li>Attention (collective understanding)</li><li>Residuals (safe information flow)</li><li>Layer Norm (keeps everything stable)</li><li>Feed Forward (deep individual thinking)</li></ul><p>Four simple ideas. Together they created something revolutionary.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d0a6f9a1578" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Transformers from Scratch]]></title>
            <link>https://medium.com/@osamaazhar591/understanding-transformers-from-scratch-8e7d3004165d?source=rss-7fd53afe0b6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e7d3004165d</guid>
            <dc:creator><![CDATA[Osamaazhar]]></dc:creator>
            <pubDate>Tue, 12 May 2026 13:50:13 GMT</pubDate>
            <atom:updated>2026-05-12T13:50:13.415Z</atom:updated>
            <content:encoded><![CDATA[<p>I still remember the first time I tried reading Google’s famous “Attention Is All You Need” paper. I could follow the math on paper, but I had zero real intuition. It all felt like random matrix multiplication soup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*oIanWp8cHWP-tfyluqiKCw.gif" /></figure><p>So I decided to rebuild everything in my head using super simple ideas. One day I used this search query as my example: <strong>“Pakistan vs Bangladesh cricket highlights”</strong>.</p><p>In this Part 1, we are going to walk through the core concepts together — no heavy math, just clear human intuition.</p><p>We will cover:</p><ul><li>Tokenization</li><li>Embeddings</li><li>Positional Encoding</li><li>Queries, Keys &amp; Values</li><li>Self-Attention</li><li>The Attention Matrix</li></ul><p>Let’s dive in.</p><h3>Step 1: Tokenization — Chopping Sentences into Pieces</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/246/1*lkwa82HoJ5sRCM0CwGWVlA.png" /></figure><p>The very first thing a Transformer does is break your sentence into <strong>tokens</strong>:</p><blockquote><em>[Pakistan] [vs] [Bangladesh] [cricket] [highlights]</em></blockquote><p>Each token is like a little Lego block. Simple enough.</p><p>But here’s the thing: computers don’t understand words. They only understand numbers. So we need to turn these tokens into something the model can actually work with.</p><h3>Step 2: Word Embeddings — Giving Words a Numerical Personality</h3><p>Every token gets converted into a dense vector (a list of numbers). Think of it as the word’s “meaning vector.”</p><p>Here’s a ridiculously simplified example:</p><ul><li><strong>Pakistan</strong> → [1.2, 0.8, 0.5]</li><li><strong>cricket</strong> → [0.9, 1.5, 1.1]</li><li><strong>highlights</strong> → [0.7, 1.8, 1.3]</li></ul><p>The cool part? Words that are related end up with similar vectors. “Cricket” and “highlights” will be closer to each other than “cricket” and “vs”.</p><p>But there’s a big problem here: <strong>Embeddings don’t know the order of words.</strong></p><h3>Step 3: Positional Encoding — Teaching the Model “Where” Words Are</h3><p>Unlike humans, Transformers look at all words at the same time (parallel processing). That’s fast, but they completely lose track of sequence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*GnJlcJHuwq6qG2oWIMwSOw.png" /></figure><p>To fix this, we add <strong>positional encoding</strong> — a special pattern that tells each word its position in the sentence.</p><p><strong>Final input for each token = Embedding + Positional Encoding</strong></p><p>Now every vector knows two things:</p><ol><li>What the word means</li><li>Where it sits in the sentence</li></ol><p><strong>Real-life analogy:</strong> Imagine a cricket stadium full of players.</p><ul><li>The embedding = the player’s identity (who they are)</li><li>The positional encoding = their seat number</li></ul><p>Without seat numbers, you’d have total chaos.</p><h3>Step 4: The Input Matrix (X)</h3><p>After combining everything, we now have a nice matrix where each row is a token’s full vector that is meaning + position. Let us call this <strong>X</strong>.</p><p>We are finally ready for the magic.</p><p>so for every token there will be X vector</p><p>X1 = Pakistan vector<br>X2 = vs vector<br>X3 = bangladesh vector<br>X4 = cricket vector<br>X5 = highlights vector</p><h3>Step 5: Self-Attention — Making Words Talk to Each Other</h3><p>This is the heart of the Transformer.</p><p>Every word now starts asking: <strong>“Which other words in this sentence are important for understanding me?”</strong></p><p>For the word “highlights”, it should pay strong attention to “cricket”, “Pakistan”, and “Bangladesh”, and mostly ignore “vs”.</p><p>This is what makes the model <strong>context-aware</strong>.</p><h3>Step 6: Q, K, V — The Secret Sauce</h3><p>For each token, we create three new vectors from its input vector X:</p><ul><li><strong>Query (Q)</strong>: “What am I looking for?”</li><li><strong>Key (K)</strong>: “What do I contain?” (like a label)</li><li><strong>Value (V)</strong>: “What actual information do I carry?”</li></ul><p>We get these by multiplying X with three learnable matrices (Wq, Wk, Wv). The model learns the best values for these matrices during training.</p><p><strong>Simple intuition:</strong></p><ul><li>Query = your search question</li><li>Key = the video titles on YouTube</li><li>Value = the actual video content</li></ul><p>lets take an example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/316/1*yZ7ac-ciNWSWevrjuMuSTQ.png" /></figure><p>Its a learnable metrix for, <br>Wq =<br>[<br> [0.1,0.7],<br> [0.4,0.2]<br>]</p><p>Wk =<br>[<br> [0,1],<br> [1,0],<br> [1,1]<br>]</p><p>Wv = <br>[<br> [1,1],<br> [0,1],<br> [1,0]<br>]</p><p><strong>Create Query Vector</strong></p><p>Q=XWq</p><p>After Multiplication:<br>[1.1,2.1,3.1]<br>×<br>[<br> [1,0],<br> [0,1],<br> [1,1]<br>]</p><p>Result:<br>Q_pakistan =<br>[<br> (1.1×1)+(2.1×0)+(3.1×1),<br> (1.1×0)+(2.1×1)+(3.1×1)<br>]</p><p>Q_pakistan = [4.2 , 5.2]</p><p>Same will happen for Key and Value …</p><p><strong>Key Vector:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q5y4XmccqDa_WWIBbDOswQ.png" /></figure><p>In this way there will be 3 new vectors created from a X-tokens e.g Pakistan</p><h3>Step 7 &amp; 8: Calculating Attention Scores</h3><p>Now Self attention will compare the Q of token with Ks of other tokens using a dot product, <br><strong>score=Q⋅K</strong></p><p>Example:</p><p>Lets take it up for Pakistan<br>[8,3] · [5,2]<br>=<br>(8×5)+(3×2)<br>=<br>40+6<br>=<br>46</p><p>Q_highlights -&gt; will be compared to K_pakistan<br>K_vs<br>K_cricket<br>…</p><p>This will create the Attention Matrix..</p><p>Higher score = higher relevance.</p><p>So, lets suppose that it creates a final Score for Token Pakistan as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*grfF8oGQhHGgDgBrBDPvHw.png" /></figure><p>Then we scale the scores and apply <strong>softmax</strong> to turn them into probabilities (weights that add up to 1). its called Attention weights</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/158/1*Aoor7ppGBssgFHpocxtYFA.png" /></figure><p>Now “highlights” knows exactly how much attention to give each word.</p><h3>Step 9: The Attention Matrix — Who’s Looking at Whom?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N1Vuq36TlsmkmhC0qsSOpA.png" /></figure><p>Once we get this, we now do Value mixing (remember that V of Q,K,V)</p><p>Suppose after Softmax, Attention Weight come as :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*evxn2ANd2sRAXxtNiHzsRQ.png" /></figure><p>And Value Vector from Q,K,V came as like,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TLTtxeHbwmbsTb91RMHV2w.png" /></figure><p>Output=∑attention×Value</p><p>Actual Calculation:<br><strong>Pakistan = 0.18 × [1,2]<br>=<br>[0.18,0.36]</strong></p><p><strong>vs = 0.01 × [0,1]<br>=<br>[0,0.01]<br>…</strong></p><p>Add Everything : <br>Result : [3.33 , 3.52] <br>This is the <strong>NEW CONTEXT-AWARE VECTOR </strong>for that particular Token :-)</p><p>When we do this for every token, we get a beautiful matrix that shows the relationships:</p><p>It tells us, for every word, how much it cares about every other word. The brighter the connection, the stronger the attention.</p><h3>Step 10: How It All Flows Together</h3><p>Here’s the complete picture in simple terms:</p><ol><li>Input sentence → Tokens</li><li>Tokens → Embeddings</li><li>Add Positional Encoding</li><li>Create Q, K, V</li><li>Self-Attention (calculate who should talk to whom)</li><li>Output = context-rich representations</li></ol><p>Every word has now “talked” to every other word and updated its understanding based on context.</p><p><strong>Before attention:</strong> Words are lonely and isolated. <strong>After attention:</strong> “highlights” now understands it’s about a cricket match between Pakistan and Bangladesh.</p><h3>The Big Idea of Part 1</h3><p>Transformers don’t read left to right like we do. Instead, <strong>every word talks to every other word at once</strong> and figures out the relationships dynamically. That’s why they’re so powerful.</p><p>This is just the beginning.</p><p>In <strong>Part 2</strong>, we’ll go deeper: how we actually combine the information (weighted sum), why we add residual connections, layer normalization, the feed-forward network, and how everything stacks up in real Transformer blocks.</p><p><strong>Final thought:</strong> Transformers aren’t really about memorizing grammar rules. They’re about learning one powerful thing:</p><blockquote>“Which words should listen to which other words — and how much?”</blockquote><p>That simple idea changed everything in AI.</p><p>See you in Part 2!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e7d3004165d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Semantic Chunking Actually Matters]]></title>
            <link>https://medium.com/@osamaazhar591/why-semantic-chunking-actually-matters-8ba90539ba36?source=rss-7fd53afe0b6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ba90539ba36</guid>
            <dc:creator><![CDATA[Osamaazhar]]></dc:creator>
            <pubDate>Sat, 02 May 2026 15:44:06 GMT</pubDate>
            <atom:updated>2026-05-02T15:44:06.657Z</atom:updated>
            <content:encoded><![CDATA[<p>A simple, practical take on something that looks small… but actually changes everything when you build real systems.</p><h3>✦ The problem most RAG systems quietly have</h3><p>RAG sounds very clean when you first hear it:</p><blockquote><em>“Connect your data to an LLM and get better answers.”</em></blockquote><p>Nice. Makes sense.</p><p>But once you actually build something — especially in a parcel or logistics support system — things start to feel off.<br> Not broken… just not reliable.</p><h3>Problem 1: the model sounds confident… but it’s guessing</h3><p>You ask:</p><blockquote><em>“Where is my parcel?”</em></blockquote><p>And the answer <em>sounds</em> right.</p><p>But if you look closely… it didn’t check your tracking system.<br> It didn’t read real data.</p><p>It just generated something that <em>feels correct</em>.</p><p>That’s a problem.</p><h3>Problem 2: your data exists… but it doesn’t help</h3><p>You’ve done everything “right”:</p><ul><li>documents indexed</li><li>embeddings created</li><li>vector DB set up</li></ul><p>Still, results come back like:</p><ul><li>half policy</li><li>half tracking explanation</li><li>random mixed sentences</li></ul><p>So the model gets confused. And then it gives a confident but slightly wrong answer.</p><h3>So what’s actually wrong?</h3><p>It’s not the model.<br> It’s not even RAG.</p><p>It’s… how you split your data.</p><h3>✦ Simple chunking vs semantic chunking</h3><p>This part is usually ignored. But it matters more than people think.</p><h3>1. Simple chunking (what most of us start with)</h3><p>You take text and split it like:</p><ul><li>every 500 tokens</li><li>maybe 50 tokens overlap</li><li>sometimes based on headings</li></ul><p>It works. It’s easy.</p><p>But here’s the issue.</p><h4>Example</h4><p>Chunk 1:<br> Refund policy + half delivery delay explanation</p><p>Chunk 2:<br> Rest of delay explanation + random FAQ</p><p>Now imagine the user asks:</p><blockquote><em>“Why is my delivery delayed?”</em></blockquote><p>The retriever finds the word <em>delay</em>…<br> but also pulls unrelated stuff from the same chunk.</p><p>Now the model has messy context.</p><p>And messy context → messy answers.</p><h3>What goes wrong here?</h3><ul><li>you cut in the middle of meaning</li><li>one chunk contains multiple ideas</li><li>embeddings become unclear</li></ul><p>So retrieval becomes noisy.</p><h3>2. Semantic chunking (what actually helps)</h3><p>Instead of splitting by size…</p><p>You split based on meaning.</p><p>The idea is simple:</p><ul><li>turn sentences into embeddings</li><li>compare nearby sentences</li><li>if similarity drops → split</li></ul><p>That’s it.</p><p>In plain words:</p><ul><li>if topic continues → keep it together</li><li>if topic changes → split</li></ul><h3>Why this works better</h3><p>Now each chunk is focused.</p><ul><li>one chunk = one idea</li><li>retrieval becomes cleaner</li><li>answers become more grounded</li></ul><p>If I had to summarize this in one line:</p><blockquote><em>Don’t chunk by size… chunk by meaning.</em></blockquote><h3>✦ How a real RAG system should look (high-level)</h3><p>Let’s zoom out a bit.</p><p>A proper parcel support assistant is not just “LLM + documents”.<br> It’s a combination of multiple parts working together.</p><h3>High-level flow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*ZEw2tZMlziplPv_bqSMgtw.gif" /></figure><h3>✦ Two types of data (this is important)</h3><p>A lot of confusion goes away when you separate data properly.</p><h3>Unstructured data (policies, FAQs)</h3><p>Things like:</p><ul><li>refund policy</li><li>delay explanation</li><li>customer communication rules</li></ul><p>This is where RAG fits.<br> And this is where semantic chunking really helps.</p><h3>Structured data (shipments)</h3><p>Things like:</p><ul><li>tracking_id</li><li>status</li><li>timestamps</li></ul><p>This should not go through RAG.<br> This should come from tools or APIs.</p><h3>Simple rule to remember</h3><p>RAG is for knowledge<br> Tools are for facts</p><h3>✦ Real-world scenario (like PostNord)</h3><p>Think of a company like PostNord</p><p>They deal with:</p><ul><li>millions of parcels</li><li>constant support queries</li><li>strict policies</li></ul><p>So if you build an assistant for this kind of system, it must:</p><ul><li>give real tracking info (not guesses)</li><li>follow policy correctly</li><li>explain delays properly</li><li>be transparent</li></ul><p>This is not just a chatbot anymore.<br> It’s a proper system.</p><h3>✦ What this project actually does</h3><p>Instead of just explaining concepts, this setup tries to put things together in a realistic way.</p><h3>1. Startup pipeline</h3><p>When the system starts:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*Wr-jQihfSnJk7--1ODn6ug.gif" /></figure><h3>2. Request flow (runtime)</h3><p>For every user query:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/1*yz8ASr5qmXbrzTv2YGxZBg.gif" /></figure><h3>3. Example (end-to-end)</h3><p>User:</p><blockquote><em>Where is my parcel PN123?</em></blockquote><p>System:</p><ul><li>fetches tracking data</li><li>retrieves delay policy</li><li>combines both</li></ul><p>Final answer:</p><blockquote><em>Your parcel is in transit from Stockholm.<br> Delivery may be delayed due to weather.<br> Expected arrival: May 2.</em></blockquote><p>Notice something?</p><ul><li>no guessing</li><li>no random info</li><li>everything grounded</li></ul><h3>✦ Why semantic chunking makes such a difference</h3><p>Without it:</p><ul><li>chunks are messy</li><li>retrieval is weak</li><li>answers are confusing</li></ul><p>With it:</p><ul><li>chunks are clean</li><li>retrieval is precise</li><li>answers feel reliable</li></ul><p>It’s a small change in code.<br> But a big change in output.</p><h3>✦ What developers should really take from this</h3><p>Let’s be honest.</p><p>Most tutorials stop at:</p><ul><li>“this is RAG”</li><li>“this is embeddings”</li></ul><p>That’s fine for learning.</p><p>But real systems need more:</p><ul><li>proper data separation</li><li>good chunking strategy</li><li>tools integration</li><li>some level of observability</li></ul><p>If I simplify the whole stack:</p><pre>RAG + Tools + Agent + Observability</pre><h3>✦ Final thoughts</h3><p>If you’re coming from a backend background, this part is important.</p><p>Don’t just connect an LLM to documents and call it done.<br> Think about:</p><ul><li>how data flows</li><li>what gets retrieved</li><li>what gets computed</li></ul><p>Because in the end:</p><blockquote><em>The quality of your retrieval decides the quality of your AI.</em></blockquote><p>And honestly…</p><p>semantic chunking is one of those small decisions<br> that quietly makes everything better.</p><h3>✦ Projects</h3><p>If you want to explore the implementation in detail:</p><ul><li>GitHub Repository:<br> <a href="https://github.com/OsamaAzhar101/PostNode-AI-Semantic.git">https://github.com/OsamaAzhar101/PostNode-AI-Semantic.git</a></li><li>Portfolio:<br> <a href="https://osamaazhar.com/">https://osamaazhar.com</a></li></ul><p>If you go through the code, try to focus on:</p><ul><li>how chunking is implemented</li><li>how retrieval is structured</li><li>how tools and RAG are combined</li></ul><p>That’s where most of the real learning is.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ba90539ba36" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Semantic Search over Reviews: LangChain4j, Embeddings, and Spring Boot]]></title>
            <link>https://medium.com/@osamaazhar591/semantic-search-over-reviews-langchain4j-embeddings-and-spring-boot-cf9ba012ee4a?source=rss-7fd53afe0b6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf9ba012ee4a</guid>
            <dc:creator><![CDATA[Osamaazhar]]></dc:creator>
            <pubDate>Tue, 21 Apr 2026 20:49:47 GMT</pubDate>
            <atom:updated>2026-04-21T20:49:47.464Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This article is a follow-up to </em>Understanding RAG (Retrieval-Augmented Generation) — A Practical Guide for Developers<em> where we unpacked what RAG is and walked through a Spring Boot chatbot that retrieves FAQ context and calls an LLM. Here we zoom in on the </em><strong><em>retrieval layer</em></strong><em> using </em><strong><em>LangChain4j</em></strong><em>, the Java ecosystem’s answer to LangChain.</em></p><p>Dear readers,</p><p>In my previous article, I tried to answer a question many backend engineers ask when they first touch AI systems:</p><p><strong>How do we connect our own data to a model — without retraining — and make answers more reliable?</strong></p><p>That piece introduced <strong>RAG</strong> in plain terms: <strong>retrieve</strong> relevant snippets, <strong>augment</strong> the prompt, then let the <strong>LLM generate</strong>. I also described a project where that full loop runs in <strong>Spring Boot</strong>: language detection, embeddings, cosine similarity over stored FAQ vectors, prompt construction, and finally <strong>generation</strong> via an LLM.</p><p>That implementation was <strong>intentionally “hand-wired”</strong> in places — you can see the glue code in services that orchestrate embeddings, search, and OpenAI. It works, and it teaches you <em>what</em> each step does.</p><p>This time I wanted to go one step further on the <strong>engineering</strong> side:</p><p><strong>What if we use a framework that already encodes the RAG <em>patterns</em> — documents, chunking, embedding stores, ingestion — so we spend less time on plumbing and more on data and product behavior?</strong></p><p>That led me to <strong>LangChain4j</strong> and a new project focused on <strong>retrieval over real review text</strong>, using the same mental model as the LangChain world, but on the <strong>JVM</strong>.</p><h3>Why a second project — and how it connects to the first</h3><p>This project (Common Complaint Analyzer)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X7maaCXKTldEKeO1vUCCvQ.png" /></figure><p><strong>Goal</strong></p><p>End-to-end RAG with <strong>G</strong> (generation)</p><p>Deep dive into <strong>R</strong> (retrieval) + framework ergonomics</p><p><strong>Stack</strong></p><p>Spring Boot + custom retrieval + LLM</p><p>Spring Boot + <strong>LangChain4j</strong></p><p><strong>Data</strong></p><p>FAQ / KB style</p><p>Amazon-style <strong>reviews CSV</strong> (messy, long text)</p><p><strong>Embeddings</strong></p><p>API-based (as in that design)</p><p><strong>Local ONNX</strong> MiniLM — no API key for vectors</p><p>LLM produces natural language</p><p>Ranked <strong>chunks + metadata</strong> (LLM optional add-on)</p><p>Nothing here contradicts the first article. It <strong>extends</strong> it:</p><ul><li>Same <strong>idea</strong>: query → embedding → vector search → relevant context.</li><li>Different <strong>emphasis</strong>: <em>framework-native</em> ingestion and retrieval, and a dataset where <strong>chunking</strong> matters because reviews are not short FAQ pairs.</li></ul><p>If the first piece was “what RAG is and how I wired it in Java,” this one is “how I’d structure <strong>retrieval</strong> when I want maintainable, LangChain-style building blocks in <strong>Spring Boot</strong>.”</p><h3>What is LangChain4j ?</h3><p><strong>LangChain4j</strong> is not an LLM. It is a <strong>library for building LLM-powered applications in Java</strong>: abstractions for documents, splitting, embeddings, vector stores, and (when you need it) chaining and AI services.</p><p>If you’ve read LangChain docs in Python, the vocabulary transfers:</p><ul><li><strong>Document</strong> + <strong>Metadata</strong></li><li><strong>DocumentSplitter</strong> (chunking)</li><li><strong>EmbeddingModel</strong></li><li><strong>EmbeddingStore</strong> and <strong>EmbeddingStoreIngestor</strong></li><li>Search via <strong>EmbeddingSearchRequest</strong></li></ul><p>You still run <strong>Spring Boot</strong> as your container; LangChain4j sits <strong>inside</strong> your services as the RAG toolkit.</p><h3>The problem this demo solves</h3><p>Customer <strong>complaints</strong> live in unstructured text: titles, bodies, ratings, countries, dates. Keyword search helps, but <strong>semantic search</strong> helps more when users ask in natural language — <em>“What are people saying about delivery or account verification?”</em></p><p>The app <strong>does not</strong> try to replace a data warehouse for <em>“count complaints by country.”</em> That’s aggregation. It <strong>does</strong> try to <strong>surface the most relevant review fragments</strong> for an analyst or a future LLM — the <strong>retrieval</strong> half of RAG, done well.</p><h3>Pipeline 1: Ingestion (load → chunk → embed → store)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BC5YD176R7NRHhWeTe1qew.png" /></figure><ol><li><strong>Load documents</strong></li></ol><p>Rows from Amazon_Reviews.csv become LangChain4j <strong>Document</strong> instances. The <strong>body</strong> is human-readable text (reviewer, country, rating, title, full review). <strong>Metadata</strong> holds structured fields for display and future filtering.</p><p><strong>2. Chunking</strong></p><p>Long reviews exceed what you want in a single vector or a single prompt chunk. <strong>DocumentSplitters.recursive</strong> breaks text into overlapping segments (size and overlap are configurable). Overlap reduces the chance that a critical sentence sits on a cut boundary.</p><p><strong>3. Embedding</strong></p><p>Each chunk is passed through <strong>AllMiniLmL6V2EmbeddingModel</strong> — a <strong>local</strong> ONNX model (MiniLM L6 v2 family). <strong>No API key</strong> is required for this step, which is great for demos, CI, and cost-sensitive environments.</p><p><strong>4. Vector store</strong></p><p>Chunks and vectors go into an <strong>InMemoryEmbeddingStore</strong>. For production you’d swap this for Postgres + pgvector, Redis, Milvus, etc. — LangChain4j supports multiple backends; the <strong>ingestion contract</strong> stays familiar.</p><p><strong>EmbeddingStoreIngestor</strong> ties these steps together so the service reads like the diagrams in RAG tutorials instead of a one-off loop.</p><h3>Pipeline 2: Retrieval (query → embed → search → results)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kxUxqO1_B9Kl3nmWm_HyNw.png" /></figure><p>When a user (or API client) submits a query:</p><ol><li>The <strong>same</strong> EmbeddingModel embeds the query — critical: <strong>same space</strong> as the indexed chunks.</li><li><strong>EmbeddingSearchRequest</strong> carries the query vector, <strong>top-K</strong>, and a <strong>minimum similarity</strong> threshold.</li><li>The store returns <strong>EmbeddingMatch</strong> objects: <strong>score</strong>, <strong>text</strong>, <strong>metadata</strong>.</li></ol><p>That is the <strong>“R”</strong> from RAG, implemented cleanly. If you add an LLM later, you pass these matches as <strong>context</strong> — exactly as in my previous article’s augmentation step — using LangChain4j’s higher-level APIs (AiServices, ContentRetriever) when you’re ready.</p><h3>What I learned compared to the FAQ / ChatBot-RAG build</h3><p><strong>Chunking is not optional</strong> for messy corpora. FAQs can be one embedding per Q&amp;A; <strong>reviews</strong> need splitting.</p><p><strong>Framework alignment pays off.</strong> Naming things Document, EmbeddingStore, EmbeddingStoreIngestor makes onboarding easier for anyone who has seen LangChain elsewhere.</p><p><strong>Retrieval-only is a valid product phase.</strong> You can ship <strong>search + evidence</strong> first, measure quality, <strong>then</strong> add generation — instead of coupling everything to an LLM on day one.</p><p><strong>Local embeddings</strong> trade a bit of setup (model load, CPU) for <strong>predictable cost</strong> and <strong>offline</strong> development — useful when teaching or prototyping.</p><h3>Who this is for</h3><ul><li>Backend engineers who <strong>already grasp RAG conceptually</strong> (see the <a href="https://medium.com/@YOUR_HANDLE/your-rag-article-slug">previous article</a>) and want a <strong>Java-native</strong> retrieval stack.</li><li>Teams standardized on <strong>Spring Boot</strong> who don’t want Python microservices for every AI feature.</li><li>Anyone building <strong>complaint analysis</strong>, <strong>support analytics</strong>, or <strong>review mining</strong> where <strong>semantic retrieval</strong> is the first milestone.</li></ul><h3>Source code</h3><p><strong>GitHub:</strong> <a href="https://github.com/OsamaAzhar101/RAG-LangChain">https://github.com/OsamaAzhar101/RAG-LangChain</a></p><p>The repo includes:</p><ul><li>Spring Boot API (/api/v1/ingest, /api/v1/search, /api/v1/health)</li><li>A small <strong>web UI</strong> for retrieval</li><li><strong>README</strong> and <strong>DOCUMENTATION</strong> for configuration and deeper flow</li></ul><p>Clone it, point app.rag.csv-path at your CSV, and run mvn spring-boot:run.</p><h3>Closing the loop with the first article</h3><p>In part one, I wrote:</p><blockquote>Without RAG: AI guesses. With RAG: AI retrieves → understands → then answers.</blockquote><p>In <strong>this</strong> project, the middle is explicit in code: <strong>retrieve</strong> with LangChain4j, <strong>inspect</strong> the evidence, and <strong>optionally</strong> hand that evidence to an LLM when you want the final “understands → answers” step.</p><p>Same story — <strong>better structure</strong> for the retrieval chapter.</p><p>I’m still learning in public. If you’re a developer building AI features behind real APIs, I hope this pair of articles helps you <strong>map concepts to repositories</strong> you can actually run.</p><p><strong>Portfolio:</strong> <a href="https://osamaazhar.com/">https://osamaazhar.com</a></p><p><strong>Previous project (full RAG + LLM flow):</strong> <a href="https://github.com/OsamaAzhar101/ChatBot-RAG">https://github.com/OsamaAzhar101/ChatBot-RAG</a></p><p><strong>This project (LangChain4j + retrieval focus):</strong> <a href="https://github.com/OsamaAzhar101/RAG-LangChain">https://github.com/OsamaAzhar101/RAG-LangChain</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf9ba012ee4a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding RAG (Retrieval-Augmented Generation) — A Practical Guide for Developers]]></title>
            <link>https://medium.com/@osamaazhar591/understanding-rag-retrieval-augmented-generation-a-practical-guide-for-developers-cf877ea11d5c?source=rss-7fd53afe0b6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf877ea11d5c</guid>
            <dc:creator><![CDATA[Osamaazhar]]></dc:creator>
            <pubDate>Sun, 19 Apr 2026 20:53:47 GMT</pubDate>
            <atom:updated>2026-04-21T20:51:48.526Z</atom:updated>
            <content:encoded><![CDATA[<p>Dear Readers,</p><p>Over the past few months, I’ve been exploring AI more seriously.</p><p>Not just watching tutorials… but actually trying to build things and understand how these systems work behind the scenes.</p><p>And honestly, in the beginning, it was a bit overwhelming.</p><p>There are so many terms:<br> LLMs, embeddings, vector databases, tokens…</p><p>I kept asking myself:</p><ul><li>How do these AI models actually work in real applications?</li><li>Can we use our own data with them?</li><li>And most importantly… how do we make their answers more reliable?</li></ul><p>That’s when I came across something that started to make things click:</p><p>✓ <strong>RAG (Retrieval-Augmented Generation)</strong></p><p><strong>What is RAG?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u-w6zAisAER8a202e1Yh0w.png" /></figure><p>Let’s not overcomplicate it.</p><p>In simple terms:</p><p>✓ <strong>RAG = LLM + external data (retrieved at runtime)</strong></p><p>Models like those from OpenAI are powerful, but they have limitations.</p><p>They generate responses based on:</p><ul><li>their training data</li><li>and the prompt you provide</li></ul><p>But in real-world scenarios, this is not enough.</p><p><strong>The Problem with Standalone LLMs</strong></p><p>If you use an LLM directly, you will notice a few issues:</p><ul><li>It doesn’t know your private/internal data</li><li>It may not have up-to-date information</li><li>It can hallucinate (generate incorrect answers confidently)</li></ul><p>This becomes a serious problem in production systems.</p><p>✓<strong> How RAG Solves This</strong></p><p>RAG introduces one important step before generation:</p><p>✓ <strong>Retrieval</strong></p><p>Instead of directly generating an answer, the system:</p><ol><li>Searches relevant data</li><li>Brings that data into context</li><li>Then asks the LLM to generate a response</li></ol><p><strong>RAG — Conceptual Flow</strong></p><p>You can think of it like this:</p><p><strong>Without RAG:</strong></p><p>AI = “I will answer based on what I remember”</p><p><strong>With RAG:</strong></p><p>AI = “Let me look at the relevant data first… then answer”</p><p><strong>The actual pipeline looks like:</strong></p><ol><li>User query</li><li>Convert query → embedding</li><li>Search in vector database</li><li>Retrieve top relevant results</li><li>Build context</li><li>Send to LLM</li><li>Generate response</li></ol><p>✓ This is the core idea behind most modern AI systems.</p><p><strong>Why RAG is Critical in Real Systems</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oTOLFivphBLz587RENfmuQ.jpeg" /></figure><p>In enterprise applications, most valuable data is:</p><ul><li>private</li><li>domain-specific</li><li>not publicly available</li></ul><p>For example:</p><p>✓<strong> Healthcare</strong></p><ul><li>patient records</li><li>prescriptions</li><li>clinical notes</li></ul><p>✓<strong> E-commerce</strong></p><ul><li>product catalog</li><li>customer orders</li><li>inventory</li></ul><p>A standalone LLM cannot access this data.</p><p>✓ RAG makes it possible <strong>without retraining the model</strong>.</p><p>✓<strong> Key Insight</strong></p><p>RAG acts as a bridge between proprietary data and AI models.</p><p>It allows organizations to:</p><ul><li>keep data secure</li><li>avoid expensive retraining</li><li>generate highly contextual responses</li></ul><p>✓<strong> My Practical Implementation (Spring Boot + RAG)</strong></p><p>To really understand this, I built a small project:</p><p>✓ GitHub:<br> <a href="https://github.com/OsamaAzhar101/ChatBot-RAG.git">https://github.com/OsamaAzhar101/ChatBot-RAG.git</a></p><p>The goal was not just to “use AI”<br> but to understand <strong>how to design a backend system around it</strong>.</p><p>✓<strong> How RAG Works in My Project (Detailed Flow)</strong></p><p>Let’s go a bit deeper into the actual implementation.</p><p><strong>1. User Query</strong></p><p>Everything starts with a simple question:</p><p>“What is the refund policy?”</p><p><strong>2. Language Detection</strong></p><p>The system first identifies the language.</p><p>✓ Why this matters:<br> Embeddings are language-sensitive, so this improves matching accuracy.</p><p><strong>3. Query Embedding</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V4FuEFQ5BaDbtiQQVkJVDg.png" /></figure><p>The user query is converted into a vector using an embedding model.</p><p>✓ This transforms text into a numerical representation in vector space.</p><p><strong>4. Vector Search (Similarity Matching)</strong></p><p>Stored FAQ data already has embeddings.</p><p>The system:</p><ul><li>compares the query vector</li><li>with stored vectors</li><li>using <strong>cosine similarity</strong></li></ul><p><strong>5. Retrieval (The “R”)</strong></p><p>Only the most relevant entries are selected.</p><p>✓ Typically top-K results (e.g., top 3–5)</p><p><strong>6. Augmentation (The “A”)</strong></p><p>Now we construct a prompt that includes:</p><ul><li>user question</li><li>retrieved FAQ data</li><li>system instructions</li></ul><p>This becomes the <strong>context</strong> sent to the model.</p><p><strong>7. Generation (The “G”)</strong></p><p>The LLM generates the final answer based on this enriched context.</p><p>✓ This significantly improves accuracy and relevance.</p><p><strong>Important Design Decision</strong></p><p>One key choice I made:</p><p>✓ <strong>Using FAQ questions for embeddings (not answers)</strong></p><p><strong>Why?</strong></p><p>Because:</p><ul><li>user queries are closer to questions</li><li>improves similarity matching</li><li>leads to better retrieval results</li></ul><p>This small decision actually had a noticeable impact.</p><p><strong>What I Learned While Building This</strong></p><p>Most tutorials online:</p><ul><li>explain the concept</li><li>show basic demos</li></ul><p>But real-world systems require:</p><ul><li>proper backend architecture</li><li>API design</li><li>data flow management</li><li>performance considerations</li></ul><p>Coming from a Spring Boot background,<br> I focused on building it like a real backend service.</p><p><strong>What You Can Build Using RAG</strong></p><p>Once you understand this pattern, you can build:</p><ul><li>AI chatbots with internal data</li><li>enterprise knowledge assistants</li><li>customer support systems</li><li>document-based Q&amp;A tools</li></ul><p>This is where AI becomes truly useful.</p><p><strong>Simple Takeaway</strong></p><p>Without RAG:</p><p>AI guesses</p><p>With RAG:</p><p>AI retrieves → understands → then answers</p><p><strong>Final Thoughts</strong></p><p>I’m still learning this space… and there’s a lot more to explore.</p><p>But one thing is clear:</p><p>✓ You don’t need to become an AI researcher to start building AI systems.</p><p>If you’re a backend developer,<br> you just need to understand how to <strong>connect components properly</strong>:</p><ul><li>embeddings</li><li>retrieval</li><li>prompting</li><li>generation</li></ul><p>That’s where the real power lies.</p><p>If you’re exploring AI from a developer perspective,<br> I hope this gives you a clearer and more practical understanding.</p><p>I’ll keep sharing more as I learn — <br> simple, practical, and from a backend engineer’s point of view.</p><p>🔗 GitHub:<br> <a href="https://github.com/OsamaAzhar101/ChatBot-RAG.git">https://github.com/OsamaAzhar101/ChatBot-RAG.git</a></p><p>🌐 Portfolio:<br> <a href="https://osamaazhar.com/">https://osamaazhar.com</a></p><p>#AI #RAG #Java #SpringBoot #BackendDevelopment #LearningInPublic</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf877ea11d5c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Spring Batch: Efficient Data Processing at Scale]]></title>
            <link>https://medium.com/@osamaazhar591/mastering-spring-batch-efficient-data-processing-at-scale-f5bfef6d78c3?source=rss-7fd53afe0b6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5bfef6d78c3</guid>
            <dc:creator><![CDATA[Osamaazhar]]></dc:creator>
            <pubDate>Sun, 26 Jan 2025 17:20:08 GMT</pubDate>
            <atom:updated>2025-01-26T17:20:08.866Z</atom:updated>
            <content:encoded><![CDATA[<p><em>In</em> the ever-evolving world of data-driven applications, processing large volumes of data efficiently is often a challenge. Imagine dealing with extensive datasets requiring transformation, validation, and storage — tasks that can easily overwhelm traditional systems. Enter <strong>Spring Batch</strong>, a robust framework designed for <strong>batch processing</strong>. In this article, we’ll explore how Spring Batch can help you tackle these challenges and implement efficient data processing solutions.</p><h3>What is Spring Batch?</h3><p>Think of Spring Batch as your digital bakery, designed to process “data batches” systematically, much like a bakery produces cookies in steps. Instead of manually handling data, Spring Batch automates the process, enabling efficient, reliable, and scalable workflows for <strong>large-scale data processing</strong> tasks.</p><p>Imagine running a bakery that needs to prepare 1,000 cookies daily. You wouldn’t bake each cookie individually; instead, you’d follow a structured process:</p><ol><li><strong>Gather Ingredients</strong>: Flour, sugar, and chocolate chips — analogous to fetching data using an <strong>ItemReader</strong>.</li><li><strong>Mix Dough</strong>: Combine the ingredients, just like transforming or validating records using an <strong>ItemProcessor</strong>.</li><li><strong>Shape Cookies</strong>: Roll the dough into cookie shapes, representing the business logic applied to your data.</li><li><strong>Bake</strong>: Cook the cookies, akin to finalizing the transformation process.</li><li><strong>Pack and Label</strong>: Box and label the cookies, similar to writing processed data to a destination using an <strong>ItemWriter</strong>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LF8OvM9TPUR2wtiCcE9Mww.jpeg" /></figure><h4>Key Features of Spring Batch:</h4><ul><li><strong>Chunk-based Processing</strong>:<br>In the bakery, instead of handling 1,000 cookies at once, you bake them in batches of 100. Similarly, <strong>Spring Batch</strong> processes data in chunks, reading, processing, and writing manageable portions to ensure efficiency and performance.</li><li><strong>Fault Tolerance</strong>: Imagine a tray of cookies burns in the oven. Instead of stopping the entire bakery operation, you replace that tray and continue. Similarly, <strong>Spring Batch</strong> detects and gracefully handles errors without interrupting the entire batch process.</li><li><strong>Scalability</strong>:As the bakery grows, you might add more ovens or workers to produce 10,000 cookies daily. <strong>Spring Batch</strong> is built to scale, allowing you to process millions of records efficiently by leveraging multiple threads or distributed systems.</li><li><strong>Transaction Management</strong>: When boxing cookies, you ensure each box has the right number before sealing it. If a mistake happens, you redo the box, not the entire process. Similarly, <strong>Spring Batch</strong> ensures data consistency across steps, rolling back changes if an error occurs during processing.</li></ul><h3>Common Use Cases:</h3><ul><li>Importing massive datasets (e.g., CSV files).</li><li>Transforming and exporting data for analytics.</li><li>Processing financial transactions, user updates, or product catalogs.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*26bhiKOQFeCTHRp6asDL4g.png" /></figure><h3>Core Concepts of Spring Batch</h3><ol><li><strong>Job</strong>: A Job represents the overall task or workflow. For instance, if you’re processing payroll, the Job encompasses all the steps from data retrieval to calculations and updates.</li><li><strong>Step</strong>: Each Step is an independent unit within a Job, responsible for a specific action like reading data, processing it, or writing it to a database.</li><li><strong>ItemReader</strong>: This component reads data from a source, such as a file, database, or API, preparing it for processing.</li><li><strong>ItemProcessor</strong>: It transforms or validates the data. For example:</li></ol><ul><li>Filter records with missing fields.</li><li>Transform data formats (e.g., date conversions).</li><li>Perform calculations like computing interest for financial records.</li></ul><p><strong>5. ItemWriter</strong>: Writes the processed data to a destination, such as a database, another file, or even a cloud bucket.</p><h3>Real-World Example: Importing and Transforming Student Records</h3><p>Let’s take an example of importing a large set of student records from a CSV file. The process involves reading the file, transforming the data, and saving it to a database.</p><h4>Step 1: Configure the Application</h4><p>Set up your Spring Boot project with the necessary dependencies:</p><ul><li><strong>Spring Batch</strong></li><li><strong>Spring Data JPA</strong></li><li><strong>H2 </strong>(or your preferred database)</li></ul><h4>Step 2: Define the Domain Object</h4><p>Define a Student class representing the data structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e8i0yOEXL-A6dTFFMA922A.png" /></figure><h4>Step 3: Implement ItemReader</h4><p>Use FlatFileItemReader to read the CSV file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JzPSFa4r8jDJDgAOMupDKQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3JrkRScBsExcHJHutlFJ9Q.png" /></figure><h4>Step 4: Implement ItemProcessor</h4><p>Apply transformations to the data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1RhsRqR5jPVQVhIYydZBrw.png" /></figure><h4>Step 5: Implement ItemWriter</h4><p>Save the processed records into the database:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r7YnxscCQVtGbhls98JqUg.png" /></figure><h4>Step 6: Configure the Job and Step</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VFjxXBh37ZvLArfLP-nE9g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mJ-wXJdXwUSzx0LitYf77g.png" /></figure><h4>Step 8: Fault Tolerance and Restartability</h4><p>Spring Batch is designed to handle failures gracefully and allow jobs to restart seamlessly. Here’s how it achieves fault tolerance and restartability:</p><h4>Fault Tolerance</h4><ul><li><strong>Skip Policy</strong>: You can define a policy to skip problematic records (e.g., invalid data formats) instead of failing the entire job.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c-rcZclUzRJ4jSqs55J9jw.png" /></figure><ul><li><strong>Retry Policy</strong>: Retry failed operations (e.g., transient database issues) before marking them as skipped.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hOjDjQgHnXpHgp639EzrCA.png" /></figure><h4>Restartability</h4><p>Spring Batch jobs are inherently restartable. When a job fails, you can rerun it without reprocessing successfully completed steps or records.</p><ul><li><strong>Execution Context</strong>: Maintains the state of a job, including processed records, so the job can resume from where it left off.</li><li><strong>Job Parameters</strong>: Ensure job uniqueness by passing unique parameters (e.g., timestamps or job-specific identifiers). This helps differentiate between multiple runs of the same job.</li></ul><p>For example:</p><pre>JobParameters jobParameters = new JobParametersBuilder()<br>        .addString(&quot;jobId&quot;, UUID.randomUUID().toString()) // Unique identifier<br>        .addLong(&quot;time&quot;, System.currentTimeMillis()) // Timestamp for uniqueness<br>        .toJobParameters();</pre><p>Spring Batch combines these mechanisms to resume operations efficiently. By tracking progress through the <strong>Execution Context</strong>, it avoids duplicating already processed records. This ensures faster recovery and minimizes resource consumption in case of a failure.</p><h4>Step 9: Running the Job</h4><p>Trigger the job execution using the JobLauncher interface:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SsOQCe-fSpZ0nwpEUrm-LQ.png" /></figure><h3>GitHub Repository</h3><p>For the complete implementation and code examples, visit the GitHub repository:<br><a href="https://github.com/OsamaAzhar101/batch.git">Spring Batch Example Code</a></p><p>This repository includes all the necessary configurations, classes, and resources to set up and run the examples discussed in this article.</p><h3>Conclusion</h3><p>Spring Batch simplifies the complexity of batch processing with its robust features and modular architecture. By breaking down tasks into Jobs, Steps, and Chunks, it provides a structured and scalable solution for processing large datasets efficiently. Whether you’re transforming data or automating recurring tasks, Spring Batch ensures reliability and performance. Start building your batch jobs today and take your data processing capabilities to the next level!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5bfef6d78c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing OAuth 2.0 and OpenID Connect with Spring Boot: A Code-Centric Guide — PART 2]]></title>
            <link>https://medium.com/@osamaazhar591/implementing-oauth-2-0-and-openid-connect-with-spring-boot-a-code-centric-guide-part-2-d11edd3cf38e?source=rss-7fd53afe0b6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d11edd3cf38e</guid>
            <dc:creator><![CDATA[Osamaazhar]]></dc:creator>
            <pubDate>Tue, 14 Jan 2025 08:57:40 GMT</pubDate>
            <atom:updated>2025-01-14T09:16:56.232Z</atom:updated>
            <content:encoded><![CDATA[<h3>Implementing OAuth 2.0 and OpenID Connect with Spring Boot: A Code-Centric Guide — PART 2</h3><p>Previously, we had a chance to look into the theoretical part of what is OAuth 2.0 and how does it work.</p><p><a href="https://medium.com/@osamaazhar591/understanding-oauth-2-0-a-deep-dive-into-theory-part-1-22feae965e6e">https://medium.com/@osamaazhar591/understanding-oauth-2-0-a-deep-dive-into-theory-part-1-22feae965e6e</a></p><p>In this article, we dive into the practical implementation of OAuth 2.0 and OpenID Connect in a Spring Boot application. By the end of this guide, you’ll have a working example of an Authorization Server, Resource Server, and Client Application. Let’s get started!</p><h3>Understanding the Flow</h3><p>Before jumping into the code, here’s a quick summary of the components we’ll implement:</p><ol><li><strong>Authorization Server</strong>: Issues access tokens and handles authentication.</li><li><strong>Resource Server</strong>: Protects the APIs and verifies access tokens.</li><li><strong>Client Application</strong>: Interacts with the Authorization Server to obtain tokens and calls secured APIs on the Resource Server.</li></ol><h3>Step 1: Set Up the Authorization Server</h3><h3>Dependencies</h3><p>Add the following dependencies to your pom.xml:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tyydXIQycZgahrwJ-rJvww.png" /></figure><h3>Configuration</h3><p>Create a configuration class to set up the Authorization Server:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EA8lZ3wSPoncEfzOFZQLYQ.png" /></figure><h3>Step 2: Build the Resource Server</h3><h3>Dependencies</h3><p>Add the following dependencies:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2MY-w2IKx0QGIpQFP49hIg.png" /></figure><h3>Configuration</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3udvuc8N_hEGhpvdV64jbA.png" /></figure><h3>API Implementation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JOCGfnVCmQKUc3cW1TIZQg.png" /></figure><h3>Step 3: Set Up the Client Application</h3><h3>Dependencies</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H7gb-58korriDeXuKdWA6Q.png" /></figure><h3>Configuration</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sKEI7AFDurqo_FD4OwA5TA.png" /></figure><h3>Application yml</h3><pre>server:<br>  port: 8080<br><br>spring:<br>  application:<br>    name: oAuthIntegration<br>  security:<br>    oauth2:<br>      client:<br>        registration:<br>          google:<br>            client-id: YOUR_GOOGLE_CLIENT_ID<br>            client-secret: YOUR_GOOGLE_CLIENT_SECRET<br>            redirect-uri: &quot;http://localhost:8080/login/oauth2/code/google&quot;<br>#          linkedin:<br>#            client-id: YOUR_LINKEDIN_CLIENT_ID<br>#            client-secret: YOUR_LINKEDIN_CLIENT_SECRET<br>#            redirect-uri: &quot;http://localhost:8080/login/oauth2/code/linkedin&quot;<br>#          github:<br>#            client-id: YOUR_GITHUB_CLIENT_ID<br>#            client-secret: YOUR_GITHUB_CLIENT_SECRET<br>#            redirect-uri: &quot;http://localhost:8080/login/oauth2/code/github&quot;</pre><h3>Adding Social Login and Customization</h3><p>If there is someother oAuth 2.0 provider like Github, Linkedin, Google, then you need to do configuration to get the clientID and secret-key, here providing example for google.</p><h4>Configuring Google Login</h4><p>After setting up your project:</p><ol><li><strong>Create a Google Cloud project</strong> at Google Cloud Console and generate credentials.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*YZiKRz-b3bHqJwcBQdjRtw.png" /></figure><ol><li>Configure the OAuth Consent Screen, choosing “External” for broader user access.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3hcdXV6TBWRu_TeBHgJ8kA.png" /></figure><ol><li>Define authorized redirect URIs in the format: <a href="http://localhost:8080/login/oauth2/code/google.">http://localhost:8080/login/oauth2/code/google.</a></li><li>Retrieve the <strong>Client ID</strong> and <strong>Client Secret</strong>, and add them to your application.yml.</li></ol><h3>Github Repository</h3><p>Kindly find the related GitHub link below:</p><ul><li><a href="https://github.com/OsamaAzhar101/OAuthClient.git">GitHub - OsamaAzhar101/OAuthClient</a></li><li><a href="https://github.com/OsamaAzhar101/spring-oAuthsecurity.git">GitHub - OsamaAzhar101/spring-oAuthsecurity</a></li></ul><h3>Conclusion</h3><p>This code-centric guide demonstrates how to set up OAuth 2.0 with OpenID Connect in Spring Boot applications. With this foundation, you can expand and secure your applications for production environments. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d11edd3cf38e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding OAuth 2.0: A Deep Dive into Theory — Part 1]]></title>
            <link>https://medium.com/@osamaazhar591/understanding-oauth-2-0-a-deep-dive-into-theory-part-1-22feae965e6e?source=rss-7fd53afe0b6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/22feae965e6e</guid>
            <dc:creator><![CDATA[Osamaazhar]]></dc:creator>
            <pubDate>Sun, 12 Jan 2025 15:13:01 GMT</pubDate>
            <atom:updated>2025-01-12T15:13:01.540Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Understanding OAuth 2.0: A Deep Dive into Theory — Part 1</strong></h3><p>🌟🌍🔐 In today’s interconnected world, applications often need to interact with other services on behalf of their users. This is where <strong>OAuth 2.0</strong>, a powerful authorization framework, comes into play. It ensures secure and efficient access delegation, enabling users to share their resources without exposing sensitive credentials.</p><h3>What is OAuth 2.0?</h3><p>OAuth 2.0 is an <strong>authorization protocol</strong> designed to grant third-party applications limited access to resources on behalf of a resource owner (typically a user). Unlike traditional authentication mechanisms where credentials are shared, OAuth 2.0 focuses on granting access through tokens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O4735gXc-JzxiOKVKbw5ew.jpeg" /></figure><h3>Real-World Analogy</h3><p>To put it simply, think of OAuth 2.0 as a <strong>hotel keycard system</strong>. Instead of handing over your house key to a guest, you’d provide a temporary hotel keycard that only allows access to specific areas for a defined period. 🏨🔑✨</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2u0-fUPkY5p7d3_kGoR2Xg.jpeg" /></figure><p>Lets dig more in detail on it, <br>let’s say you want to let your friend use your room during your absence. Instead of handing over your personal house key 🔑, you give them a temporary keycard that grants them access only to the living room and balcony area, and it expires once you’re back. No need to worry about someone entering your personal space, like your bedroom. This keycard system ensures that only the areas you’re comfortable with are accessible. OAuth 2.0 works in the same way. Instead of sharing your login credentials, you give third-party applications limited access to your data through a temporary “keycard” (the access token). This way, you remain in control, only granting permission for specific actions, and the access expires once the time is up. <strong>It’s about authorization, not authentication</strong> — you’re simply giving someone the right to access certain areas of your “hotel” for a while.</p><p>it’s about <strong>authorization</strong>, not authentication. Authentication comes later, often <strong>by integrating OpenID with OAuth 2.0</strong>.</p><h3>Key Components of OAuth 2.0 And How OAuth 2.0 Works</h3><p>🔍🧩🛡️ Understanding OAuth 2.0 requires familiarity with its fundamental components:</p><ol><li><strong>Resource Owner</strong>: The user or system who owns the product/app.<br>Example : <strong>YOU —</strong> the person who owns the room and decides who gets access</li><li><strong>Client</strong>: The system or application requesting access to the resource on behalf of the resource owner. <strong>The client must have an access token</strong>.<br><strong>Example</strong>: <strong>Your Friend — </strong>Your friend uses the temporary keycard to access the living room and balcony.</li><li><strong>Authorization Server</strong>: The server that receives requests from the client for an access token. It provides the token upon successful authentication and consent from the resource owner.<br><strong>Example: The Front Desk —</strong> The front desk issues the keycard (access token) based on your permission. It enforces your decision to grant access to specific areas of the room.</li><li><strong>Resource Server</strong>: The server hosting the protected resource. It accepts and validates access tokens from the client and provides the appropriate resource.<br><strong>Example: The Lock System on the Room Doors</strong> — The lock system enforces the access rules. It checks the keycard and ensures it only opens the living room and balcony, while the bedroom remains inaccessible..</li></ol><h3>OAuth Playground</h3><p>For a hands-on understanding of OAuth 2.0, visit the OAuth Playground: <a href="https://www.oauth.com/playground/">https://www.oauth.com/playground/</a></p><p>Here’s how it works:</p><ol><li>Choose an OAuth flow ⬇️</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iyZQGdwOuHlABp1j5RoSgA.png" /></figure><p>2. Register client</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S5yiTIJe1TsZJEGzZpy34A.png" /></figure><p>3. Keep the client-Id, secret Key and credentials.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*q_QLz8RnLCw3oZh9slueOw.png" /></figure><p>4. Authorization code flow</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H5SgBeqyOHjsOdBPihxYhw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2qwv7DFGlI_hhfx_lkyPHw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pju4g17KnQHx3_MZFGJiLA.png" /></figure><p><strong>once you log in </strong>, <strong>it ask for the permission to the resource-owner</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*iZK-FUHrBGWtWQNdnBbrlA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T7Lf_bCty4oVElK7LUZVbA.png" /></figure><p>If the state matches, you receive an access token in exchange for a code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kw7SB70rjbNbSvBWjyZyvQ.png" /></figure><p>Hurray!, you get the Token now..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vrdwZLZXGdha_zN5bpCz5Q.png" /></figure><p>Hurray! You’ve now successfully interacted with OAuth 2.0. 🚀</p><h3>Conclusion</h3><p>🔚🔑🌟 OAuth 2.0 has revolutionized how applications handle authorization by focusing on delegation and token-based access. By separating authentication from authorization, it ensures users can share resources securely without compromising their credentials.</p><p>In <strong>Part 2</strong>, we’ll dive into the practical implementation of OAuth 2.0, exploring how to build secure and scalable applications using Spring Boot and Spring Security. Stay tuned! 🚀💻📚</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22feae965e6e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Authorization in Spring Security using Custom Interceptors]]></title>
            <link>https://medium.com/@osamaazhar591/enhancing-authorization-in-spring-security-using-custom-interceptors-6716a64f78e2?source=rss-7fd53afe0b6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/6716a64f78e2</guid>
            <dc:creator><![CDATA[Osamaazhar]]></dc:creator>
            <pubDate>Mon, 06 Jan 2025 13:54:53 GMT</pubDate>
            <atom:updated>2025-01-06T14:35:16.338Z</atom:updated>
            <content:encoded><![CDATA[<p>In my <a href="https://medium.com/@osamaazhar591/securing-your-spring-boot-applications-with-jwt-85b25f82e78d">previous article</a>, we discussed role-based authentication and authorization in Spring Boot applications. The GitHub repository associated with that article includes an implementation where interceptors were used as well. Building on that foundation, let’s dive deeper into the topic to better understand how interceptors can enhance security in Spring Boot applications.</p><h3>Key Components of the Implementation</h3><ol><li><strong>Custom Annotation for Role-Based Access Control<br></strong>We define a custom annotation, @RoleInterceptor, to specify the role required to access specific endpoints.</li><li><strong>Interceptor Handler<br></strong>A HandlerInterceptor is implemented to enforce the role check at runtime.</li><li><strong>Configuration<br></strong>The custom interceptor is registered with Spring’s InterceptorRegistry.</li></ol><h3>Step 1: Define the Custom Annotation</h3><p>We create a custom annotation named @RoleInterceptor with an attribute to specify the required role.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*opTeABXTyWWQ-85xxssw-A.png" /></figure><p>This annotation will be used to mark endpoints that require role-based access.</p><h3>Step 2: Implement the Interceptor Handler</h3><p>The RoleInterceptorHandler class implements HandlerInterceptor to enforce role-based access control.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AfI-UsI_1ASaYiKeIfaulA.png" /></figure><ul><li><strong>Logic</strong>: The preHandle method inspects the request and checks if the user has the required role based on the annotation. If the role doesn’t match, it sets the HTTP response status to 403 Forbidden.</li></ul><h3>Step 3: Register the Interceptor</h3><p>The WebConfig class registers the custom interceptor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pq6Lp-fwpnj709v4qaSjXw.png" /></figure><h3>Step 4: Use the Annotation in Controllers</h3><p>Apply the @RoleInterceptor annotation to secure specific endpoints.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lJhCbnzwyw06vpkCraTpTw.png" /></figure><h3>How It Works</h3><ol><li>When a request is made to /admin, the RoleInterceptorHandler checks if the current user has the ADMIN role.</li><li>If the user has the role, the request proceeds; otherwise, a 403 Forbidden response is returned.</li></ol><h3>Conclusion</h3><p>This implementation demonstrates how custom interceptors can enhance the security and maintainability of Spring Boot applications. By centralizing role checks within an interceptor, we ensure a clean and modular approach to enforcing role-based access control.</p><p>Explore the <a href="https://github.com/OsamaAzhar101/springsecurity.git">GitHub Repository</a> for the complete source code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6716a64f78e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Securing Your Spring Boot Applications With JWT]]></title>
            <link>https://medium.com/@osamaazhar591/securing-your-spring-boot-applications-with-jwt-85b25f82e78d?source=rss-7fd53afe0b6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/85b25f82e78d</guid>
            <dc:creator><![CDATA[Osamaazhar]]></dc:creator>
            <pubDate>Sat, 04 Jan 2025 15:17:53 GMT</pubDate>
            <atom:updated>2025-01-05T12:57:19.472Z</atom:updated>
            <content:encoded><![CDATA[<p>Securing a Spring Boot application with <strong>JWT (JSON Web Tokens)</strong> enables stateless authentication, enhancing both scalability and security. Here’s a step-by-step guide to implementing authentication and authorization in your Spring Boot project.</p><p>🔐 <strong>Secure Your Spring Boot Application with JWT Authentication</strong></p><p>We’ve all been there — building applications with tight deadlines, where security often gets pushed to “later.” But, what if I told you securing your Spring Boot application can be both quick and robust? Let’s dive into how <strong>Spring Security</strong> paired with <strong>JWT</strong> can make your APIs secure and stateless.</p><h3>What’s Happening Behind the Scenes?</h3><p>Here’s a simplified flow to secure your app:</p><p>Here’s a step-by-step overview of how your Spring Boot application processes secure requests:</p><p>1️⃣ The <strong>AuthFilter</strong> intercepts the request and checks for the presence of a JWT in the Authorization header.<br>2️⃣ If a JWT is found, it extracts the token and passes it to the <strong>JwtService</strong> for validation.<br>3️⃣ Upon successful validation, the <strong>SecurityContextHolder</strong> is updated with the authenticated user’s details.<br>4️⃣ Finally, the request proceeds to the <strong>DispatcherServlet</strong>, where it is routed to the appropriate controller.</p><p>Request ➡️ AuthFilter ➡️ JwtService ➡️ SecurityContextHolder ➡️ DispatcherServlet ➡️ Controller</p><h3>Step-by-Step Implementation</h3><h4>1️⃣ Add Dependencies</h4><p>Add the following to your pom.xml or build.gradle</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dMwYqgOFOXOut9jcOI0uGg.png" /></figure><h4>2️⃣ Configure Security</h4><p>Create a configuration class to define your security rules:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5J_GYzf2a0XhztjaefMUwg.png" /></figure><h3>Steps for Authentication and Authorization</h3><p>1️⃣ Authentication Manager</p><p>The <strong>AuthenticationManager</strong> is the central component for verifying user credentials. Instead of directly dealing with it, we configure it using <strong>AuthenticationManagerBuilder</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IwuQ7GFIkvKvA7C0alnhXg.png" /></figure><h4>2️⃣ Authorization Manager</h4><p>The <strong>Authorization Manager</strong> controls access to specific endpoints based on roles, permissions, or other criteria.</p><p><strong>Steps to Configure:</strong></p><ol><li><strong>Define Roles/Permissions</strong>:<br>Configure which roles or users can access specific endpoints.</li><li><strong>Set Security Rules</strong>:<br>Use authorizeRequests to define access rules for specific URL patterns.</li></ol><pre>@Override<br>protected void configure(HttpSecurity http) throws Exception {<br>    http.csrf().disable()<br>        .authorizeRequests()<br>            .antMatchers(&quot;/admin/**&quot;).hasRole(&quot;ADMIN&quot;) // Restrict /admin/* to users with ADMIN role<br>            .antMatchers(&quot;/user/**&quot;).hasAnyRole(&quot;USER&quot;, &quot;ADMIN&quot;) // Restrict /user/* to USER or ADMIN roles<br>            .antMatchers(&quot;/authenticate&quot;).permitAll() // Public access<br>            .anyRequest().authenticated() // Default rule: all other endpoints require authentication<br>        .and()<br>        .sessionManagement()<br>            .sessionCreationPolicy(SessionCreationPolicy.STATELESS);<br>}</pre><h4>3️⃣ UserDetailsService</h4><p>Implement <strong>UserDetailsService</strong> to load user details (username, password, roles) from the database or another source.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rHIE2xh7-4QKlloY45mHsg.png" /></figure><h4>3️⃣ Set Up JWT Utility</h4><p>Here’s how to generate, validate, and extract information from a JWT:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HCE46GZwGD2xU5I2qlQq0A.png" /></figure><h4>4️⃣ Build Your Authentication Endpoint</h4><p>Here’s a basic controller to authenticate users:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j7SH6h6-idcFEXo3xR9hvQ.png" /></figure><h3>💡 Why JWT?</h3><p>JWT makes your API stateless, scalable, and secure. No more sticky sessions — just pass tokens between client and server. Pair JWT with multi-factor authentication for an even more robust setup!</p><h3>💻 GitHub Repository for Securing Spring Boot Applications with JWT</h3><p>You can find the complete source code for the example provided in this article here:</p><p><a href="https://github.com/OsamaAzhar101/springsecurity"><strong>🔗 GitHub Repository: springsecurity</strong></a></p><p>This repository includes:</p><ul><li>🛡️ Authentication and Authorization setup</li><li>🔑 JWT generation, validation, and extraction</li><li>🧑‍💻 Implementation of AuthenticationManager and UserDetailsService</li><li>🌐 Secure endpoint configuration with role-based access</li></ul><p>Feel free to clone, explore, and contribute! 🚀</p><h3>🚀 Your Turn</h3><p>What’s your go-to strategy for API security? Let’s share, learn, and grow together in this new year! Feel free to drop your thoughts or challenges in the comments — I’d love to hear them.</p><p>Here’s to a year of <strong>learning</strong>, <strong>sharing</strong>, and building better tech. Let’s make 2025 amazing! 🌟</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85b25f82e78d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>