<?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 Nikoo Asadnejad on Medium]]></title>
        <description><![CDATA[Stories by Nikoo Asadnejad on Medium]]></description>
        <link>https://medium.com/@nikoo.asadnejad.work?source=rss-155ce63ec305------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*b8oRL6hzHMB7DZ2fux0ymg@2x.jpeg</url>
            <title>Stories by Nikoo Asadnejad on Medium</title>
            <link>https://medium.com/@nikoo.asadnejad.work?source=rss-155ce63ec305------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 12:22:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nikoo.asadnejad.work/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[Your RAG Found the Right Topic. Did It Find the Right Answer?]]></title>
            <link>https://medium.com/@nikoo.asadnejad.work/your-rag-found-the-right-topic-did-it-find-the-right-answer-f97cb97622ca?source=rss-155ce63ec305------2</link>
            <guid isPermaLink="false">https://medium.com/p/f97cb97622ca</guid>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[rag-pipeline]]></category>
            <category><![CDATA[cross-encoder-rerank]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Nikoo Asadnejad]]></dc:creator>
            <pubDate>Thu, 19 Nov 2026 12:49:17 GMT</pubDate>
            <atom:updated>2026-11-19T12:49:17.067Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How bi-encoders, cross-encoders, and reranking help choose better context before an LLM starts writing.</em></p><figure><img alt="RAG Reranking" src="https://cdn-images-1.medium.com/max/1024/1*Ge3_4PB3o6LKb9DlqTtLrw.png" /><figcaption>RAG Reranking</figcaption></figure><p>You build a RAG pipeline. You split documents into chunks, generate embeddings, and store them in a vector database.</p><p>Then you ask a question.</p><p>The search results look relevant. The LLM produces a fluent answer. But something is missing: the specific information you needed.</p><p>For example, you ask:</p><blockquote><em>“How can I rotate an API key without interrupting running services?”</em></blockquote><p>Your search returns three passages:</p><ul><li>A definition of API keys.</li><li>A recommendation to rotate credentials regularly.</li><li>A procedure for introducing a new key before revoking the old one.</li></ul><p>All three belong to the same topic. Only the third directly explains how to do the job.</p><p>This is where <strong>reranking</strong> can help.</p><p>In my previous article, <a href="https://medium.com/@nikoo.asadnejad.work/inside-modern-ai-search-rag-embeddings-vector-databases-and-similarity-algorithms-b282342e0286">Inside Modern AI Search: RAG, Embeddings, Vector Databases, and Similarity Algorithms</a>, I covered how a RAG system finds information. Here, we’ll look at how it chooses which retrieved passages deserve a place in the final prompt.</p><h3>Search First, Look More Closely Second</h3><p>Imagine searching for a book in a large library.</p><p>The catalog gives you a shortlist. You then open those books and check which ones contain the information you need.</p><p>A retrieval-and-reranking pipeline follows a similar process:</p><pre>Question<br>   ↓<br>Find promising passages<br>   ↓<br>Evaluate each candidate more carefully<br>   ↓<br>Select useful context<br>   ↓<br>Ask the LLM to answer</pre><p>The first step needs to search a large collection quickly. The second can spend more effort evaluating a smaller set.</p><p>Two model architectures commonly support these stages: <strong>bi-encoders</strong> and <strong>cross-encoders</strong>.</p><h3>Bi-Encoders: Finding Candidates Quickly</h3><p>A bi-encoder processes the question and each passage separately, turning both into vectors:</p><pre>Question → Encoder → Query vector<br>Passage  → Encoder → Passage vector</pre><p>The two encoding paths often share the same model. The name describes how the texts are processed independently.</p><p>The search system then compares their vectors using a similarity measure such as cosine similarity or dot product.</p><p>Consider this example:</p><blockquote><strong><em>Question:</em></strong><em> “How can I change credentials without downtime?”<br></em><strong><em>Passage:</em></strong><em> “Keep the old API key active while applications switch to its replacement.”</em></blockquote><p>A well-trained embedding model can place these texts close together, even though their wording differs.</p><p>The biggest advantage is efficiency.</p><p><strong>Passage vectors can be generated during ingestion and stored in the vector database.</strong> When a question arrives, the system only needs to encode that question and search the existing index.</p><p>However, the passage’s vector was created without seeing the question. In a typical single-vector system, it also compresses the passage into one representation.</p><p>That representation may capture the overall topic well while missing the importance of a specific condition, such as <strong>“without downtime.”</strong></p><p>The right passage might appear somewhere in the results, with a less useful introduction ranked above it.</p><p>A cross-encoder gives the pipeline another opportunity to evaluate that order.</p><h3>Cross-Encoders: Evaluating the Question and Passage Together</h3><p>A cross-encoder receives <strong>the question and a candidate passage together</strong>:</p><pre>Question + Passage → Cross-encoder → Relevance score</pre><p>For our API-key question, it evaluates pairs like these:</p><pre>“How can I rotate an API key without interruption?”<br>+<br>“An API key identifies an application making a request.”</pre><p>And:</p><pre>“How can I rotate an API key without interruption?”<br>+<br>“Create a replacement key, update consumers, verify the<br>transition, and then revoke the previous key.”</pre><p>The model can learn that the second passage addresses the requested procedure more directly.</p><p>It repeats this process for every candidate. The pipeline then sorts the passages by their scores.</p><p>This additional interaction often improves ranking quality, although the result depends on the model and the documents. The tradeoff is that each question–passage pair requires fresh computation. <a href="https://www.sbert.net/docs/cross_encoder/usage/usage.html">Sentence Transformers describes this cross-encoder tradeoff</a>.</p><p>This gives the two architectures complementary roles:</p><ul><li><strong>Bi-encoder:</strong> efficiently find promising passages across the collection.</li><li><strong>Cross-encoder:</strong> evaluate the shortlisted passages together with the question.</li></ul><h3>What Happens Inside a Cross-Encoder?</h3><p>In a typical BERT-style cross-encoder, the question and passage become one combined sequence of tokens:</p><pre>[CLS] question tokens [SEP] passage tokens [SEP]</pre><p>The special tokens mark the structure of the input.</p><p>The combined text passes through Transformer layers. Their attention mechanism allows words in the question to interact with words in the passage.</p><p>For example, <strong>“without interruption”</strong> can influence how the model evaluates instructions about keeping both keys valid during a transition.</p><p>After processing the pair, a scoring layer produces a relevance score. The model is trained so that useful passages receive higher scores than less useful ones. This is the basic mechanism used in <a href="https://arxiv.org/html/1901.04085v5">BERT-based passage reranking</a>.</p><p>You don’t need to implement the Transformer yourself. Libraries provide pretrained rerankers that accept a question and a list of passages.</p><p>One detail matters: <strong>a relevance score does not guarantee correctness.</strong></p><p>A passage can closely address a question while containing outdated or incorrect information. Some models also return raw scores rather than probabilities. A higher score helps order candidates; it doesn’t certify their contents.</p><h3>Why Not Use a Cross-Encoder for Everything?</h3><p>Because it needs to process each question–passage pair.</p><p>With vector search, document embeddings are already waiting in the index. With a cross-encoder, a new question requires fresh processing of its candidate passages.</p><p>Doing that across an entire collection would usually be too expensive.</p><p>A practical pipeline therefore looks like this:</p><pre>Large document collection<br>          ↓<br>Fast retrieval<br>          ↓<br>Small candidate set<br>          ↓<br>Cross-encoder reranking<br>          ↓<br>Selected context</pre><p>There is also a limit to what reranking can fix.</p><p><strong>If retrieval never finds the right passage, the reranker cannot recover it.</strong></p><p>Before tuning the reranker, check whether the necessary evidence appears in the candidate set at all.</p><h3>Which Algorithms Are Involved?</h3><p>Several names appear in discussions about reranking. They become easier to understand when we separate <strong>how the model learns</strong> from <strong>how the pipeline combines and selects results</strong>.</p><h3>Pointwise Training: Judge One Passage</h3><p>Pointwise training teaches the model using individual examples:</p><blockquote><em>“This passage is relevant to this question.”</em></blockquote><p>Each question–passage pair receives a label. Binary cross-entropy is a common training objective.</p><p>At search time, the model scores each candidate independently, and the pipeline sorts the results.</p><h3>Pairwise Training: Learn a Preference</h3><p>Pairwise training uses comparisons:</p><blockquote><em>“For this question, passage A should rank above passage B.”</em></blockquote><p><strong>RankNet</strong> learns from the difference between the two scores. <strong>Margin-ranking loss</strong> encourages the relevant passage to score higher by a chosen margin.</p><p>This does not mean the system must compare every possible pair during search. A scalar-scoring model can still score each candidate once and sort the results.</p><h3>Listwise Training: Learn From an Ordering</h3><p>Listwise training uses a group of passages:</p><blockquote><em>“For this question, this is the desired order.”</em></blockquote><p><strong>ListNet</strong> and <strong>ListMLE</strong> are examples.</p><p>These objectives train the scoring model using relationships across a list. They do not necessarily require feeding every passage into the Transformer together.</p><p>These are training choices, so you can use a pretrained reranker without implementing them yourself. The <a href="https://www.sbert.net/docs/cross_encoder/loss_overview.html">Sentence Transformers loss overview</a> provides the available options.</p><p>Across these approaches, the quality of the examples matters.</p><p>A passage about API-key rotation that omits the deployment procedure may be a more useful negative example than an unrelated passage about cooking. These difficult examples are commonly called <strong>hard negatives</strong>.</p><p>They require careful labeling because an apparently negative passage may contain valid supporting evidence.</p><h3>How I’m Using This in My Project</h3><p>In my <a href="https://github.com/Nikoo-Asadnejad/Security-Knowledge-Assistant">Security Knowledge Assistant</a>, the search pipeline combines dense retrieval and BM25 over OWASP documentation.</p><p>Its current flow is:</p><pre>User question<br>      ↓<br>Dense search + BM25 search<br>      ↓<br>Combine results with RRF<br>      ↓<br>Rerank up to 20 candidates<br>      ↓<br>Return up to 3 passages</pre><p>The reranker runs locally on the CPU using FastEmbed and a MiniLM cross-encoder.</p><p>The search stage is implemented. Answer generation and expansion into larger parent sections are planned.</p><p>That distinction matters: adding a reranker is an implementation decision. Demonstrating that it improves answers requires evaluation.</p><h3>How Do You Know It Helps?</h3><p>Start with a small set of realistic questions and identify which passages contain useful evidence.</p><p>Compare the results before and after reranking:</p><ul><li>Does the useful passage move closer to the top?</li><li>Do the selected passages cover what the question asks?</li><li>Are several results repeating the same information?</li><li>How much latency does reranking add?</li><li>Once generation is connected, do answers become better supported?</li></ul><p>Also check input length.</p><p>The reranker must fit the <strong>question and passage together</strong> within its token limit. A passage that fits your embedding model may still be too long after adding the question. If useful information gets truncated, it cannot influence the score.</p><p>The candidate count deserves attention too. More candidates give the reranker more opportunities to find useful evidence, but increase processing cost.</p><p>Choose that number using your own questions and latency requirements.</p><p>Reranking gives a RAG pipeline another opportunity to select useful evidence before generation begins. When retrieval finds that evidence but leaves it buried in the results, this extra step can make a meaningful difference.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f97cb97622ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding LangChain:From Workflows to Intelligent Agents]]></title>
            <link>https://medium.com/@nikoo.asadnejad.work/understanding-langchain-from-workflows-to-intelligent-agents-8593a2bdbe81?source=rss-155ce63ec305------2</link>
            <guid isPermaLink="false">https://medium.com/p/8593a2bdbe81</guid>
            <category><![CDATA[ai-tools]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <dc:creator><![CDATA[Nikoo Asadnejad]]></dc:creator>
            <pubDate>Sat, 25 Jul 2026 17:37:59 GMT</pubDate>
            <atom:updated>2026-07-25T17:37:59.364Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5V6S-A6Hip2ZA-SwIFB9JA.png" /><figcaption>LangChain</figcaption></figure><p>If you’re joining this series here, I highly recommend starting with the first two parts before diving into AI agents.</p><p>In <a href="https://medium.com/@nikoo.asadnejad.work/understanding-langchain-the-building-blocks-of-modern-ai-applications-df56924076e4"><strong>Part 1</strong></a>, we explored the core <a href="https://medium.com/@nikoo.asadnejad.work/understanding-langchain-the-building-blocks-of-modern-ai-applications-df56924076e4">building blocks of LangChain</a>, including <strong>Chat Models</strong>, <strong>Messages</strong>, <strong>Runnables</strong>, <strong>Output Parsers</strong>, <strong>Callbacks</strong>, and <strong>Middleware</strong>. These components form the foundation of every LangChain application.</p><p>In <a href="https://medium.com/@nikoo.asadnejad.work/understanding-langchain-building-intelligent-workflows-765354005151"><strong>Part 2</strong></a>, we built on that foundation by learning how <strong>Sequential</strong>, <strong>Parallel</strong>, <strong>Conditional</strong>, <strong>Branching</strong>, and <strong>Dynamic Chains</strong> connect those building blocks into structured <a href="https://medium.com/@nikoo.asadnejad.work/understanding-langchain-building-intelligent-workflows-765354005151">AI workflows</a> capable of solving more complex problems.</p><p>Now it’s time for the final step. Instead of following predefined workflows, we’ll explore how <strong>ReAct</strong> and <strong>Tool Calling</strong> enable AI applications to reason, make decisions, and interact with external tools — bringing us closer to truly intelligent AI agents.</p><p>Chains are great when you already know the steps involved.</p><p>But what if the application doesn’t know what to do next?</p><p>Should it search the web?</p><p>Query a database?</p><p>Use a calculator?</p><p>Call an API?</p><p>This is where <strong>AI Agents</strong> come in.</p><p>Unlike chains, which follow predefined workflows, agents can <strong>reason</strong>, <strong>make decisions</strong>, and <strong>choose actions</strong> during execution.</p><h3>ReAct: Think, Act, Observe</h3><p>One of the most popular agent architectures is <strong>ReAct</strong>, which stands for <strong>Reason + Act</strong>.</p><p>Instead of immediately generating an answer, the model follows a simple reasoning loop:</p><ol><li>Think about the problem.</li><li>Decide whether additional information is needed.</li><li>Use a tool if necessary.</li><li>Observe the result.</li><li>Generate the final answer.</li></ol><pre>Question<br>    │<br>    ▼<br> Think<br>    │<br>Need a Tool?<br> ┌──┴──┐<br> │     │<br>Yes    No<br> │      │<br>Use Tool<br> │<br> ▼<br>Observe<br> │<br> ▼<br>Final Answer</pre><p>Imagine asking:</p><p><em>“What’s the weather in Sydney today, and should I carry an umbrella?”</em></p><p>The model doesn’t guess.</p><p>Instead, it realizes that it needs current weather information, calls a weather service, receives the result, and then generates an informed answer.</p><p>This ability to combine reasoning with actions is what makes ReAct such a powerful approach for building intelligent AI assistants.</p><h3>Tool Calling : Giving LLMs Real-World Capabilities</h3><p>By themselves, language models are limited to the information they learned during training.</p><p>They can’t:</p><ul><li>Check today’s weather</li><li>Read your database</li><li>Send an email</li><li>Search the web</li><li>Execute business logic</li></ul><p>That’s why <strong>Tool Calling</strong> is one of the most important features in modern AI applications.</p><p>A tool is simply a Python function or an external service that the model is allowed to use whenever it needs additional information.</p><pre>from langchain.tools import tool</pre><pre>@tool<br>def get_weather(city: str):<br>    &quot;&quot;&quot;Returns today&#39;s weather.&quot;&quot;&quot;<br>    return &quot;Sunny, 26°C&quot;</pre><p>Now imagine the following conversation:</p><p><strong>User:</strong> <em>“What’s the weather in Paris today?”</em></p><p>Instead of making something up, the workflow becomes:</p><pre>User Question<br>      │<br>      ▼<br>    Agent<br>      │<br>      ▼<br> Chooses Weather Tool<br>      │<br>      ▼<br> Gets Live Data<br>      │<br>      ▼<br> Generates Answer</pre><p>The exciting part is that the user never has to tell the AI which tool to use. The language model decides that for itself.</p><p>This transforms an LLM from a chatbot into an intelligent assistant capable of interacting with real-world systems.</p><h3>Guardrails : Keeping AI Agents Safe and Reliable</h3><p>As AI agents become more capable, they also become more powerful. An agent that can search the web, query databases, or call external APIs should be able to make decisions — but within well-defined boundaries. This is where <strong>Guardrails</strong> come in.</p><p>Guardrails are the rules and constraints that help ensure your AI application behaves as intended. They can validate user input, enforce output formats, prevent unsafe actions, restrict access to certain tools, or require human approval before executing sensitive operations. Think of them as safety mechanisms that help keep your AI reliable, secure, and aligned with your application’s business requirements.</p><p>For example, an AI customer support agent might be allowed to retrieve order information but not issue refunds without human approval. Similarly, an internal company assistant may answer questions about documentation but should never expose confidential data to unauthorized users.</p><p>LangChain supports implementing guardrails in several ways, including <strong>middleware</strong>, <strong>structured output validation with Pydantic</strong>, <strong>custom tool validation</strong>, and integration with specialized guardrail frameworks. The right approach depends on your application’s requirements, but the goal is always the same: give your AI enough freedom to be helpful while ensuring it operates within safe and predictable limits.</p><p>As you build more advanced AI systems, guardrails become just as important as prompts, chains, and agents. They transform a capable AI application into one that’s ready for real-world production.</p><h3>Wrapping Up</h3><p>LangChain isn’t just a library for talking to language models — it’s a framework for building complete AI applications.</p><p>We started with <strong>Chat Models</strong> and <strong>Messages</strong>, which allow us to communicate with LLMs. Then we explored <strong>Runnables</strong>, the reusable building blocks that power modern LangChain applications, along with <strong>RunnableLambda</strong> and <strong>RunnableSequence</strong>, which help us integrate custom logic into AI workflows. We also looked at <strong>Output Parsers</strong> which transform free-form AI responses into structured, reliable data, while <strong>Callbacks</strong> and <strong>Middleware</strong> make applications easier to monitor, secure, and maintain.</p><p>Once those pieces are in place, <strong>Chains</strong> help organize them into clear workflows whether they run sequentially, in parallel, conditionally, or adapt dynamically at runtime. Finally, <strong>ReAct</strong> and <strong>Tool Calling</strong> introduce reasoning and interaction with external systems, allowing AI applications to move beyond simple text generation and solve real-world problems.</p><p>The LangChain ecosystem is much larger than what we’ve covered here, but understanding these core concepts gives you a strong foundation. As you continue learning, you’ll find that advanced topics such as <strong>LangGraph</strong>, <a href="https://medium.com/@nikoo.asadnejad.work/inside-modern-ai-search-rag-embeddings-vector-databases-and-similarity-algorithms-b282342e0286"><strong>RAG (Retrieval-Augmented Generation)</strong></a>, <strong>Memory</strong>, and <strong>Multi-Agent Systems</strong> are all built upon the same ideas you’ve explored in this article.</p><p>Once these fundamentals click, building intelligent AI applications becomes much less intimidating — and much more enjoyable.</p><h3>Related Topics :</h3><ul><li><a href="https://medium.com/@nikoo.asadnejad.work/understanding-langchain-the-building-blocks-of-modern-ai-applications-df56924076e4"><strong>Understanding LangChain: The Building Blocks of Modern AI Applications</strong></a></li><li><a href="https://medium.com/@nikoo.asadnejad.work/understanding-langchain-building-intelligent-workflows-765354005151"><strong>Understanding LangChain:Building Intelligent Workflows</strong></a></li><li><a href="https://medium.com/@nikoo.asadnejad.work/inside-modern-ai-search-rag-embeddings-vector-databases-and-similarity-algorithms-b282342e0286"><strong>Inside Modern AI Search: RAG, Embeddings, Vector Databases, and Similarity Algorithms.</strong></a></li><li><a href="https://medium.com/@nikoo.asadnejad.work/from-monoliths-to-societies-understanding-agent-oriented-software-engineering-aose-6552d52c3514?postPublishedType=repub"><strong>From Monoliths to Societies: Understanding Agent-Oriented Software Engineering (AOSE)</strong></a></li><li><a href="https://medium.com/@nikoo.asadnejad.work/ai-vs-machine-learning-vs-neural-networks-vs-deep-learning-bc709468f863?postPublishedType=repub"><strong>AI vs. Machine Learning vs. Deep Learning vs. Neural Networks</strong></a></li><li><a href="https://medium.com/@nikoo.asadnejad.work/how-generative-ai-and-large-language-models-are-transforming-software-5e06c74b420b"><strong>How Generative AI and Large Language Models Are Transforming Software.</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8593a2bdbe81" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding LangChain:Building Intelligent Workflows]]></title>
            <link>https://medium.com/@nikoo.asadnejad.work/understanding-langchain-building-intelligent-workflows-765354005151?source=rss-155ce63ec305------2</link>
            <guid isPermaLink="false">https://medium.com/p/765354005151</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[ai-workflow]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <dc:creator><![CDATA[Nikoo Asadnejad]]></dc:creator>
            <pubDate>Fri, 24 Jul 2026 16:23:30 GMT</pubDate>
            <atom:updated>2026-07-25T17:40:40.724Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5V6S-A6Hip2ZA-SwIFB9JA.png" /><figcaption>LangChain</figcaption></figure><p>In <strong>Part 1</strong> of this series, we explored the fundamental <a href="https://medium.com/@nikoo.asadnejad.work/understanding-langchain-the-building-blocks-of-modern-ai-applications-df56924076e4">building blocks of LangChai</a>n, including <strong>Chat Models, Messages, Runnables, Output Parsers, Callbacks, and Middleware</strong>. If you haven’t read it yet, I recommend starting <a href="https://medium.com/@nikoo.asadnejad.work/understanding-langchain-the-building-blocks-of-modern-ai-applications-df56924076e4">there</a>, as these concepts form the foundation for everything we’ll cover in this article. Now it’s time to connect those building blocks into intelligent workflows using <strong>Chains</strong> and <strong>AI Agents</strong>.</p><h3>Connecting the Components with Chains:</h3><p>Now that we understand the core building blocks, the next question is:</p><p><strong>How do we connect them together to solve real problems?</strong></p><p>A user request rarely involves just one step. Imagine asking an AI assistant to write a blog post. Before returning the final result, it might generate an outline, write the content and finally create a catchy title.</p><p>Instead of manually managing every step, LangChain introduces <strong><em>Chains</em> </strong>workflows that connect multiple components into a single pipeline.</p><p>You can think of a chain like an assembly line in a factory. Each component has one responsibility, and together they produce the final result.</p><h3>Types Of Chains:</h3><h3>1. Sequential Chains : One Step Leads to the Next</h3><p>The simplest workflow is a <strong>Sequential Chain</strong>.</p><p>Here, each step depends on the output of the previous one, making it perfect for tasks that naturally follow a specific order.</p><p>For example, imagine building an AI content generator:</p><pre>Topic<br>  │<br>  ▼<br>Generate Outline<br>  │<br>  ▼<br>Write Article<br>  │<br>  ▼<br>Proofread<br>  │<br>  ▼<br>Generate Title</pre><p>Each stage improves or builds upon the previous result.</p><p>This is one of the most common patterns you’ll encounter when working with LLMs because many AI tasks naturally happen step by step.</p><h3>2. Parallel Chains : Divide and Conquer</h3><p>Not every task needs to wait for another one to finish.</p><p>Suppose you’re creating an AI assistant that generates product content for an online store. From the same product information, you want to create:</p><ul><li>A product description</li><li>SEO keywords</li><li>A social media caption</li><li>A short summary</li></ul><p>These tasks are completely independent, so why execute them one after another?</p><p>A <strong><em>Parallel Chain</em></strong> runs them simultaneously, making your application faster and more efficient.</p><pre>Product Details<br>                  │<br>     ┌────────────┼────────────┐<br>     ▼            ▼            ▼<br> Description   Keywords   Social Caption<br>     └────────────┼────────────┘<br>                  ▼<br>           Combined Result</pre><p>Whenever different tasks don’t depend on each other, parallel execution is usually the better choice.</p><h3>3. Conditional Chains : Making Decisions</h3><p>Real-world applications don’t always follow the same workflow.</p><p>Imagine a customer support assistant.</p><ul><li>If the question is about billing, it should contact the billing system.</li><li>If it’s a technical question, it should search the documentation.</li><li>If it’s a simple greeting, it can respond immediately.</li></ul><p>This is where <strong>Conditional Chains</strong> become useful.</p><pre>User Question<br>               │<br>        What type is it?<br>       ┌────────┴────────┐<br>       ▼                 ▼<br> Technical          Non-Technical<br>       │                 │<br> Search Docs      Answer Directly</pre><p>Instead of treating every request the same way, the application chooses the most appropriate path based on the user’s input.</p><h3>4. Branching Chains : One Input, Multiple Outputs</h3><p>Conditional chains choose <strong>one</strong> path.</p><p><strong>Branching Chains</strong> are different they execute <strong>multiple paths</strong> using the same input.</p><p>Imagine uploading a research paper.</p><p>At the same time, your application could:</p><ul><li>Generate a summary</li><li>Extract keywords</li><li>Identify important people</li><li>Translate the abstract</li></ul><pre>Research Paper<br>                │<br>      ┌─────────┼─────────┐<br>      ▼         ▼         ▼<br> Summary   Keywords   Translation<br>      └─────────┼─────────┘<br>                ▼<br>          Final Response</pre><p>Branching is useful when several independent tasks can be performed simultaneously on the same information.</p><h3>5. Dynamic Chains : Workflows That Adapt</h3><p>Some applications can’t decide their workflow until the user asks a question.</p><p>Imagine an AI travel assistant.</p><p>One user asks about flights.</p><p>Another wants hotel recommendations.</p><p>Someone else asks about today’s weather.</p><p>Each request requires a completely different workflow.</p><p>Rather than building dozens of fixed pipelines, a <strong>Dynamic Chain</strong> decides what to do while it’s running. It can choose different prompts, models, or tools based on the current situation, making the application much more flexible.</p><h3>What’s Next?</h3><p>We’ve learned how to build structured AI workflows with LangChain Chains. But what happens when an application needs to <strong>make decisions</strong>, <strong>choose its own actions</strong>, or <strong>interact with external systems</strong>? In <a href="https://medium.com/@nikoo.asadnejad.work/understanding-langchain-from-workflows-to-intelligent-agents-8593a2bdbe81"><strong>Part 3</strong></a>, we’ll explore <strong>ReAct</strong> and <strong>Tool Calling</strong>, the concepts that power modern AI agents. Click <a href="https://medium.com/@nikoo.asadnejad.work/understanding-langchain-from-workflows-to-intelligent-agents-8593a2bdbe81">here</a> for reading.</p><h3>Related Topics :</h3><ul><li><a href="https://medium.com/@nikoo.asadnejad.work/from-monoliths-to-societies-understanding-agent-oriented-software-engineering-aose-6552d52c3514?postPublishedType=repub"><strong>From Monoliths to Societies: Understanding Agent-Oriented Software Engineering (AOSE)</strong></a></li><li><a href="https://medium.com/@nikoo.asadnejad.work/understanding-langchain-the-building-blocks-of-modern-ai-applications-df56924076e4?postPublishedType=repub"><strong>Understanding LangChain: The Building Blocks of Modern AI Applications</strong></a></li><li><a href="https://medium.com/@nikoo.asadnejad.work/understanding-langchain-from-workflows-to-intelligent-agents-8593a2bdbe81"><strong>Understanding LangChain:From Workflows to Intelligent Agents</strong></a></li><li><a href="https://medium.com/@nikoo.asadnejad.work/inside-modern-ai-search-rag-embeddings-vector-databases-and-similarity-algorithms-b282342e0286"><strong>Inside Modern AI Search: RAG, Embeddings, Vector Databases, and Similarity Algorithms</strong></a></li><li><a href="https://medium.com/@nikoo.asadnejad.work/understanding-the-model-context-protocol-mcp-how-ai-apps-connect-to-the-world-1d62690c2ec9?postPublishedType=repub"><strong>Understanding the Model Context Protocol (MCP): How AI Apps Connect to the World</strong></a></li><li><a href="https://medium.com/@nikoo.asadnejad.work/ai-vs-machine-learning-vs-neural-networks-vs-deep-learning-bc709468f863?postPublishedType=repub"><strong>AI vs. Machine Learning vs. Deep Learning vs. Neural Networks</strong></a></li><li><a href="https://medium.com/@nikoo.asadnejad.work/how-generative-ai-and-large-language-models-are-transforming-software-5e06c74b420b"><strong>How Generative AI and Large Language Models Are Transforming Software.</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=765354005151" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding LangChain: The Building Blocks of Modern AI Applications]]></title>
            <link>https://medium.com/@nikoo.asadnejad.work/understanding-langchain-the-building-blocks-of-modern-ai-applications-df56924076e4?source=rss-155ce63ec305------2</link>
            <guid isPermaLink="false">https://medium.com/p/df56924076e4</guid>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[langchain-agents]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Nikoo Asadnejad]]></dc:creator>
            <pubDate>Fri, 24 Jul 2026 16:07:44 GMT</pubDate>
            <atom:updated>2026-07-24T16:40:35.392Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5V6S-A6Hip2ZA-SwIFB9JA.png" /><figcaption>LangChain</figcaption></figure><p>When most developers first start working with Large Language Models (LLMs), the workflow seems surprisingly simple: send a prompt to the model and display the response. While this works for basic chatbots, real-world AI applications are much more sophisticated. They need to interact with APIs, process structured data, follow business rules, and sometimes even decide which action to take next.</p><p>That’s where <strong><em>LangChain</em></strong> comes in.</p><p><em>LangChain</em> is an open-source framework that helps developers build AI-powered applications by connecting language models with prompts, tools, APIs, databases, and custom business logic. Instead of writing everything from scratch, it provides reusable building blocks that can be combined to create anything from a simple chatbot to a production-ready AI assistant.</p><p>In this article, we’ll take a tour of the most important LangChain concepts. Rather than diving deeply into every feature, the goal is to build a mental model of how the pieces fit together so you can confidently continue your LangChain journey.</p><h3>The Building Blocks of LangChain :</h3><p>Before we can build intelligent AI workflows, we need to understand the fundamental components that almost every LangChain application uses.</p><h3>1. Chat Models : The Brain of Your Application</h3><p>Every AI application starts with a language model. In LangChain, these are represented as <strong>Chat Models</strong>.</p><p>Instead of locking you into a single provider, LangChain offers a consistent interface for models from <em>OpenAI</em>, <em>Anthropic</em>, <em>Google Gemini</em>, <em>Mistral</em>, and even local models running through <em>Ollama</em>. This means switching providers often requires changing only a few lines of code rather than rewriting your entire application.</p><pre>from langchain.chat_models import init_chat_model</pre><pre>model = init_chat_model(<br>    model=&quot;gpt-4.1&quot;,<br>    model_provider=&quot;openai&quot;<br>)</pre><pre>response = model.invoke(&quot;Explain LangChain in one sentence.&quot;)<br>print(response.content)</pre><p>The chat model is the “<em>brain</em>” of your application, but by itself it only generates text. Everything else in LangChain exists to make that intelligence useful in real software.</p><h3>2. Messages :Giving Conversations Context</h3><p>Unlike traditional APIs that receive a single block of text, modern LLMs communicate through <strong>messages</strong>.</p><p>Each message has a role:</p><ul><li><strong>SystemMessage</strong> defines how the assistant should behave.</li><li><strong>HumanMessage</strong> represents the user’s request.</li><li><strong>AIMessage</strong> stores the model’s previous responses.</li></ul><pre>from langchain_core.messages import (<br>    SystemMessage,<br>    HumanMessage<br>)</pre><pre>messages = [<br>    SystemMessage(&quot;You are an experienced Python tutor.&quot;),<br>    HumanMessage(&quot;Explain decorators.&quot;)<br>]</pre><pre>response = model.invoke(messages)</pre><p>Think of messages as the conversation history. Instead of asking isolated questions, you’re building a dialogue that helps the model understand context and produce more relevant responses.</p><h3>3. Runnable : The Foundation of LangChain</h3><p>If there’s one concept that ties the entire framework together, it’s the <strong>Runnable</strong>.</p><p>A Runnable is simply something that receives an input, performs a task, and returns an output.</p><p>That might sound simple and that’s exactly the point.</p><p>In modern LangChain, almost everything is a Runnable:</p><ul><li>Chat Models</li><li>Prompt Templates</li><li>Output Parsers</li><li>Retrievers</li><li>Your own Python functions</li></ul><p>Because every component follows the same interface, they can be connected together effortlessly. Once you understand Runnables, you’ll notice that the rest of LangChain is really just different ways of combining them.</p><h3>4. RunnableLambda : Turning Python Functions into Workflow Components</h3><p>Sometimes you need more than an LLM. Maybe you want to clean user input, calculate a value, or format some text before sending it to the model.</p><p>Instead of writing separate logic outside your AI pipeline, LangChain lets you wrap ordinary Python functions using <strong>RunnableLambda</strong>.</p><pre>from langchain_core.runnables import RunnableLambda</pre><pre>uppercase = RunnableLambda(<br>    lambda text: text.upper()<br>)</pre><pre>print(uppercase.invoke(&quot;hello langchain&quot;))</pre><p>Although this example is simple, it highlights an important idea: your own code becomes a first-class citizen in a LangChain workflow. Custom business logic can be composed with prompts, models, and parsers just like any built-in component.</p><h3>5. RunnableSequence : Building AI Pipelines</h3><p>Individual components are useful, but AI applications usually involve multiple steps.</p><p>For example, a user asks a question, a prompt is created, the model generates a response, and finally the response is converted into structured data.</p><p>Instead of manually calling each step, LangChain lets you connect them into a <strong>RunnableSequence</strong>.</p><pre>User Input<br>      │<br>      ▼<br> Prompt<br>      │<br>      ▼<br> Chat Model<br>      │<br>      ▼<br> Output Parser<br>      │<br>      ▼<br> Final Result</pre><p>Creating a sequence is remarkably clean:</p><pre>chain = prompt | model | parser</pre><pre>result = chain.invoke({<br>    &quot;topic&quot;: &quot;LangChain&quot;<br>})</pre><p>The pipe (|) operator makes workflows easy to read because the output from one component automatically becomes the input for the next.</p><h3>6. Output Parsers : Making AI Responses Useful</h3><p>Language models naturally generate text, but applications often need structured information.</p><p>Imagine asking an AI to extract customer details from an email. A paragraph describing the customer isn’t nearly as useful as a structured object containing a name, email, and phone number.</p><p>This is the job of an <strong>Output Parser</strong>.</p><p>It converts raw AI responses into formats your application can work with, such as JSON, Python dictionaries, lists, or custom objects. Instead of manually parsing strings, your application receives clean, predictable data.</p><h3>7. Callbacks : Looking Behind the Curtain</h3><p>As your application grows, you’ll eventually ask questions like:</p><ul><li>Which prompt was sent?</li><li>How many tokens were used?</li><li>Why is this request slow?</li><li>Which step failed?</li></ul><p>This is where <strong>Callbacks</strong> become incredibly valuable.</p><p>Callbacks allow you to observe what’s happening inside your workflow without changing your application logic. They can log prompts, measure execution time, calculate token usage, or integrate with observability platforms such as LangSmith.</p><p>In production systems, callbacks provide the visibility needed to debug and optimize AI applications.</p><h3>8. Middleware :Cross-Cutting Features Made Easy</h3><p>Imagine wanting every request to be authenticated, logged, cached, or checked for safety before it reaches the language model.</p><p>Rather than repeating that code everywhere, you can place it in <strong>Middleware</strong>.</p><p>Middleware sits between your application and the model, intercepting requests and responses so you can add features such as:</p><ul><li>Authentication</li><li>Logging</li><li>Caching</li><li>Rate limiting</li><li>Guardrails</li><li>Monitoring</li><li>Content filtering</li></ul><p>If you’ve worked with ASP.NET Core, Express.js, or FastAPI, the idea will feel very familiar. The concept is the same only now the middleware is managing AI requests instead of HTTP requests.</p><h3>Ready for the Next Step?</h3><p>Now that you’ve learned the core building blocks of LangChain, it’s time to see how they work together. In <a href="https://medium.com/@nikoo.asadnejad.work/understanding-langchain-building-intelligent-workflows-765354005151?postPublishedType=repub"><strong>Part 2</strong></a>, we’ll explore <strong>Sequential, Parallel, Conditional, Branching, and Dynamic Chains</strong> and learn how to transform individual components into intelligent AI workflows. Click <a href="https://medium.com/@nikoo.asadnejad.work/understanding-langchain-building-intelligent-workflows-765354005151?postPublishedType=repub"><em>here</em></a> to read.</p><h3>Related Topics :</h3><ul><li><a href="https://medium.com/@nikoo.asadnejad.work/from-monoliths-to-societies-understanding-agent-oriented-software-engineering-aose-6552d52c3514?postPublishedType=repub"><strong>From Monoliths to Societies: Understanding Agent-Oriented Software Engineering (AOSE)</strong></a></li><li><a href="https://medium.com/@nikoo.asadnejad.work/inside-modern-ai-search-rag-embeddings-vector-databases-and-similarity-algorithms-b282342e0286"><strong>Inside Modern AI Search: RAG, Embeddings, Vector Databases, and Similarity Algorithms</strong></a></li><li><a href="https://medium.com/@nikoo.asadnejad.work/understanding-the-model-context-protocol-mcp-how-ai-apps-connect-to-the-world-1d62690c2ec9?postPublishedType=repub"><strong>Understanding the Model Context Protocol (MCP): How AI Apps Connect to the World</strong></a></li><li><a href="https://medium.com/@nikoo.asadnejad.work/ai-vs-machine-learning-vs-neural-networks-vs-deep-learning-bc709468f863?postPublishedType=repub"><strong>AI vs. Machine Learning vs. Deep Learning vs. Neural Networks</strong></a></li><li><a href="https://medium.com/@nikoo.asadnejad.work/how-generative-ai-and-large-language-models-are-transforming-software-5e06c74b420b"><strong>How Generative AI and Large Language Models Are Transforming Software.</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df56924076e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Event Sourcing: Events, Aggregates, Streams, and Projections]]></title>
            <link>https://medium.com/@nikoo.asadnejad.work/understanding-event-sourcing-events-aggregates-streams-and-projections-5c69665d9bbd?source=rss-155ce63ec305------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c69665d9bbd</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[event-sourcing]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Nikoo Asadnejad]]></dc:creator>
            <pubDate>Thu, 18 Jun 2026 12:51:11 GMT</pubDate>
            <atom:updated>2026-06-18T12:51:11.051Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sd6YMfTQtli4jz6AyGyMVw.jpeg" /></figure><p><em>Part 2 of the Event Sourcing Series</em></p><p>In the <a href="https://medium.com/p/e62b32786ab6?postPublishedType=initial">previous article</a>, we explored why traditional CRUD applications can struggle to meet requirements such as auditability, historical analysis, and complex business workflows. Event Sourcing addresses these challenges by storing every state change as a sequence of immutable events.</p><p>However, Event Sourcing introduces several concepts that are unfamiliar to developers coming from a CRUD background. Terms such as <strong>events</strong>, <strong>aggregates</strong>, <strong>streams</strong>, and <strong>projections</strong> are fundamental to understanding how an event-sourced system works.</p><p>In this article, we’ll examine each of these building blocks and see how they fit together.</p><h3>The Core Idea of Event Sourcing</h3><p>Traditional applications persist the <strong>current state</strong> of an entity.</p><p>For example, a customer table might contain:</p><p><strong>CustomerId : </strong>42</p><p><strong>Name : </strong>Alice</p><p><strong>Status : </strong>Premium</p><p>Although we know the customer is currently a Premium member, we have no information about <strong>how</strong> they reached that state. Did they upgrade yesterday? Have they downgraded before? When did they first register?</p><p>An event-sourced system stores the complete history instead.</p><pre>CustomerRegistered<br>MembershipUpgraded<br>AddressChanged<br>MembershipRenewed</pre><p>The current state is reconstructed from these recorded events rather than being stored directly.</p><p>This shift — from storing state to storing business facts — is the defining characteristic of Event Sourcing.</p><h3>What Is an Event?</h3><p>An <strong>event</strong> represents something that has already happened within the business domain.</p><p>Events are:</p><ul><li>immutable</li><li>expressed in the past tense</li><li>ordered chronologically</li><li>part of the permanent system history</li></ul><p>Examples include:</p><pre>OrderCreated<br>ItemAddedToOrder<br>PaymentReceived<br>OrderShipped</pre><p>Each event describes a completed business action rather than an intention.</p><p>For example:</p><p>❌ Command</p><pre>ShipOrder</pre><p>✅ Event</p><pre>OrderShipped</pre><p>The distinction is important.</p><p>A <strong>command</strong> expresses intent:</p><p>“Please ship this order.”</p><p>An <strong>event</strong> records the result:</p><p>“The order has been shipped.”</p><p>Only successful business operations become events.</p><h3>Events Are Immutable</h3><p>One of the most important principles of Event Sourcing is that events are <strong>never modified or deleted</strong>.</p><p>Suppose an incorrect shipping address was recorded.</p><p>Instead of changing an existing event:</p><p>❌</p><pre>OrderCreated</pre><p>The system records a new fact:</p><pre>ShippingAddressCorrected</pre><p>The complete business history remains intact.</p><p>Immutability provides several advantages:</p><ul><li>complete audit history</li><li>reproducible system state</li><li>easier debugging</li><li>support for temporal queries</li></ul><p>Because events represent facts, changing them would effectively rewrite history.</p><h3>Event Streams</h3><p>Events rarely exist in isolation.</p><p>Instead, related events are grouped into an <strong>event stream</strong>.</p><p>A stream contains every event associated with a single aggregate instance.</p><p>For example:</p><pre>Order-123</pre><pre>OrderCreated<br>↓</pre><pre>ItemAdded<br>↓</pre><pre>ItemAdded<br>↓</pre><pre>PaymentReceived<br>↓</pre><pre>OrderConfirmed<br>↓</pre><pre>OrderShipped</pre><p>Each new event is appended to the end of the stream.</p><p>The order of events is significant because replaying them in a different sequence could produce a different state.</p><h3>Stream Versioning and Optimistic Concurrency</h3><p>Each event appended to a stream increases its version.</p><p>OrderShipped</p><p>Many event stores use stream versions to implement <strong>optimistic concurrency control</strong>.</p><p>Imagine two users attempting to modify the same order simultaneously.</p><p>Both load version 3.</p><p>Developer A appends:</p><pre>DiscountApplied</pre><p>The stream becomes version 4.</p><p>Developer B then attempts to append:</p><pre>OrderCancelled</pre><p>using the assumption that the stream is still version 3.</p><p>The event store detects that the expected version no longer matches the actual version and rejects the write.</p><p>This mechanism helps prevent conflicting updates without relying on long-running database locks.</p><h3>Aggregates</h3><p>If events record business history, <strong>aggregates</strong> enforce business rules.</p><p>An aggregate represents a consistency boundary within the domain.</p><p>Its responsibilities include:</p><ul><li>validating commands</li><li>enforcing business invariants</li><li>deciding which events should be produced</li></ul><p>Consider an order.</p><p>Business rules might include:</p><ul><li>A shipped order cannot be cancelled.</li><li>Payment cannot exceed the order total.</li><li>An item cannot have a negative quantity.</li></ul><p>These rules belong inside the Order aggregate.</p><p>A simplified flow looks like this:</p><pre>Command<br>      ↓<br>Aggregate<br>      ↓<br>Validation<br>      ↓<br>Events</pre><p>The aggregate does not directly update a database row.</p><p>Instead, it evaluates the incoming command and produces one or more events that describe the successful outcome.</p><h3>Rehydrating an Aggregate</h3><p>Unlike CRUD applications, aggregates in an event-sourced system are not typically loaded from a single database record.</p><p>Instead, they are rebuilt by replaying events from the corresponding stream.</p><p>Imagine the following stream:</p><pre>OrderCreated</pre><pre>ItemAdded</pre><pre>ItemAdded</pre><pre>PaymentReceived</pre><p>When the application needs the current Order aggregate, it loads these events in sequence.</p><pre>Load Events<br>      ↓<br>Apply OrderCreated<br>      ↓<br>Apply ItemAdded<br>      ↓<br>Apply ItemAdded<br>      ↓<br>Apply PaymentReceived<br>      ↓<br>Current Aggregate State</pre><p>This process is commonly called <strong>rehydration</strong> or <strong>replaying events</strong>.</p><p>Each event updates the aggregate until its current state is reconstructed.</p><h3>When Do Snapshots Help?</h3><p>Replaying thousands of events every time an aggregate is loaded can become expensive.</p><p>To reduce replay time, some systems periodically store a <strong>snapshot</strong> of the aggregate’s state.</p><p>For example:</p><pre>Events 1–5000<br>↓</pre><pre>Snapshot</pre><pre>↓</pre><pre>Replay Events 5001–5015</pre><p>Instead of replaying every event from the beginning, the application restores the snapshot and then applies only the events recorded afterward.</p><p>Snapshots are an optimization rather than a requirement.</p><p>Many systems function perfectly well without them, especially when streams remain relatively small.</p><h3>What Are Projections?</h3><p>One common misconception is that users query event streams directly.</p><p>In practice, this is uncommon.</p><p>Business applications typically require optimized read models:</p><ul><li>customer dashboards</li><li>order lists</li><li>reports</li><li>analytics</li><li>search indexes</li></ul><p>These read models are called <strong>projections</strong>.</p><p>A projection consumes events and builds data structures designed specifically for querying.</p><p>For example:</p><p>Events</p><pre>OrderCreated<br>ItemAdded<br>PaymentReceived<br>OrderShipped</pre><p>Projection</p><pre>Orders Table</pre><pre>OrderId<br>Customer<br>Status<br>Total<br>ShippedDate</pre><p>The projection transforms a stream of business events into a representation that is efficient to query.</p><p>Multiple projections can be generated from the same event stream.</p><p>For example:</p><ul><li>Order summary</li><li>Customer purchase history</li><li>Sales dashboard</li><li>Revenue report</li><li>Inventory statistics</li></ul><p>Each projection serves a different purpose while sharing the same source of truth.</p><h3>Putting Everything Together</h3><p>The complete lifecycle of an event-sourced request looks like this:</p><pre>Client<br>   │<br>   ▼<br>Command<br>   │<br>   ▼<br>Aggregate<br>   │<br>Validates business rules<br>   │<br>   ▼<br>Produces Events<br>   │<br>   ▼<br>Event Store<br>   │<br>   ├────────► Projection A<br>   │<br>   ├────────► Projection B<br>   │<br>   └────────► Projection C<br>                     │<br>                     ▼<br>               Read Models</pre><p>The write side records immutable business events.</p><p>The read side transforms those events into query-optimized views.</p><p>This separation allows the same historical data to support multiple read models without duplicating business logic.</p><h3>Key Takeaways</h3><p>Event Sourcing is more than storing events in a database. It introduces a different way of modeling business systems.</p><p>The key concepts are:</p><ul><li><strong>Events</strong> are immutable records of completed business facts.</li><li><strong>Streams</strong> organize events for a single aggregate instance in chronological order.</li><li><strong>Aggregates</strong> enforce business rules and decide which events should be recorded.</li><li><strong>Rehydration</strong> rebuilds aggregate state by replaying events.</li><li><strong>Snapshots</strong> reduce replay time for long event streams.</li><li><strong>Projections</strong> create read models optimized for querying and reporting.</li></ul><p>Together, these concepts form the foundation of an event-sourced architecture.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c69665d9bbd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why CRUD Isn’t Enough: An Introduction to Event Sourcing]]></title>
            <link>https://medium.com/@nikoo.asadnejad.work/why-crud-isnt-enough-an-introduction-to-event-sourcing-e62b32786ab6?source=rss-155ce63ec305------2</link>
            <guid isPermaLink="false">https://medium.com/p/e62b32786ab6</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[event-sourcing]]></category>
            <dc:creator><![CDATA[Nikoo Asadnejad]]></dc:creator>
            <pubDate>Thu, 18 Jun 2026 12:29:54 GMT</pubDate>
            <atom:updated>2026-06-18T12:29:54.938Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sd6YMfTQtli4jz6AyGyMVw.jpeg" /></figure><p>When most developers build business applications, they naturally reach for the CRUD (Create, Read, Update, Delete) model. Frameworks like Entity Framework Core make it easy to persist objects by simply inserting or updating rows in a relational database. For many applications, this approach is perfectly adequate.</p><p>However, some domains have requirements that CRUD was never designed to solve. Financial systems, banking platforms, digital wallets, accounting software, inventory management, and trading systems all share a common characteristic: <strong>history is just as important as the current state</strong>.</p><p>Imagine a digital wallet with a balance of $850. A customer asks a simple question:</p><p>“How did my balance become $850?”</p><p>In a traditional CRUD application, the database may only contain:</p><pre>Wallet<br>--------------------<br>Id: 42<br>Balance: $850</pre><p>The current balance is available, but the journey that produced it has largely been lost. Perhaps there are audit tables or transaction logs elsewhere, but the application’s primary model focuses on the latest state.</p><p>Now consider the same wallet represented with Event Sourcing.</p><pre>WalletCreated<br>↓<br>FundsDeposited($1000)<br>↓<br>FundsReserved($200)<br>↓<br>ReservationReleased($50)<br>↓<br>FundsSettled($150)</pre><p>The balance of $850 is not stored directly. Instead, it is derived by replaying the sequence of business events. Every change has context, meaning, and a timestamp.</p><h3>What Is Event Sourcing?</h3><p>Event Sourcing is an architectural pattern in which <strong>domain events become the primary source of truth</strong>.</p><p>Instead of storing the current state of an entity, the system stores every significant business event that has occurred. The current state is reconstructed by replaying those events in order.</p><p>An event is an immutable fact — something that has already happened.</p><p>Examples include:</p><ul><li>FundsDeposited</li><li>ReservationCreated</li><li>PaymentCaptured</li><li>RefundCompleted</li><li>InventoryReserved</li></ul><p>Notice that events are expressed in the past tense because they describe completed business actions.</p><h3>CRUD vs Event Sourcing</h3><p>The difference between the two approaches can be summarized as follows:</p><pre>| CRUD | Event Sourcing |<br>|---------|-------------|<br>| Stores current state | Stores complete history |<br>| Updates rows | Appends events |<br>| Deletes data | Preserves history |<br>| State is authoritative | Events are authoritative |<br>| Audit often requires extra work| Audit is built in </pre><p><strong>CRUD answers:</strong></p><p><em>“What is the current state?”</em></p><p><strong>Event Sourcing answers:</strong></p><p><em>“How did we get here?”</em></p><p>Neither model is universally better. They solve different problems.</p><h3>Why Financial Systems Benefit</h3><p>Financial applications rarely care only about balances. They care about accountability.</p><p>Consider a payment workflow:</p><ol><li>A customer deposits money.</li><li>Some funds are reserved.</li><li>The reservation is partially settled.</li><li>The remaining funds are released.</li><li>A refund is issued.</li></ol><p>Each step represents a business fact that may need to be audited months or even years later. Replacing one balance with another discards valuable information. Recording each business event preserves the complete financial story.</p><p>This is one reason many payment platforms and ledger systems adopt Event Sourcing for their core financial domains.</p><h3>Event Sourcing Does Not Mean “Everything Is an Event”</h3><p>One of the biggest misconceptions is that adopting Event Sourcing requires converting every entity into an event stream.</p><p>In reality, many successful systems use a <strong>hybrid architecture</strong>.</p><p>Administrative data often remains CRUD:</p><ul><li>Tenants</li><li>Organizations</li><li>Users</li><li>Roles</li><li>Configuration</li><li>Lookup tables</li></ul><p>These entities rarely require a complete historical replay.</p><p>Business processes, however, often benefit from Event Sourcing:</p><ul><li>Wallets</li><li>Reservations</li><li>Refunds</li><li>Financial operations</li><li>Inventory allocations</li><li>Orders (in some domains)</li></ul><p>Applying Event Sourcing selectively keeps the architecture simpler while preserving the advantages where they matter most.</p><h3>Benefits</h3><p>When used in the right domain, Event Sourcing offers several advantages:</p><ul><li>Complete audit history without additional audit tables.</li><li>The ability to rebuild read models from historical events.</li><li>Easier debugging because every business action is preserved.</li><li>Natural integration with CQRS and messaging systems.</li><li>Time-travel capabilities for analyzing historical state.</li><li>Improved traceability for compliance and financial reporting.</li></ul><h3>Challenges</h3><p>Event Sourcing also introduces additional complexity.</p><p>Developers must think in terms of business events instead of mutable entities. Systems often require projections for efficient querying, event versioning strategies, and mechanisms for replaying or snapshotting long event streams.</p><p>For many CRUD applications, this additional complexity is unnecessary.</p><h3>What’s Next?</h3><p>Understanding Event Sourcing begins with understanding its building blocks.</p><p>In the next article, we’ll explore the core concepts that make Event Sourcing work, including events, aggregates, event streams, projections, snapshots, optimistic concurrency, and read models. By the end, you’ll see how these pieces fit together to form a reliable, scalable architecture for modern business systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e62b32786ab6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Guessing Why Your API Is Slow: A Practical Guide to Observability with OpenTelemetry]]></title>
            <link>https://medium.com/@nikoo.asadnejad.work/stop-guessing-why-your-api-is-slow-a-practical-guide-to-observability-with-opentelemetry-d3a43ce6795b?source=rss-155ce63ec305------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3a43ce6795b</guid>
            <category><![CDATA[opentelemetry]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Nikoo Asadnejad]]></dc:creator>
            <pubDate>Thu, 11 Jun 2026 14:27:25 GMT</pubDate>
            <atom:updated>2026-06-11T14:27:25.537Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gBhQWSvANVMVUDPxtH4U_g.jpeg" /></figure><p><strong>We all know the feeling…</strong></p><p>A user reports that an API suddenly became slow.</p><p>You open your logs.</p><p>Everything looks normal.</p><p>CPU usage isn’t high.</p><p>Memory looks fine.</p><p>The database server is healthy.</p><p>So where is the latency coming from?</p><p>You start adding log statements:</p><pre><br>Console.WriteLine(&quot;Entering Service…&quot;);<br>Console.WriteLine(&quot;Before Mongo Query…&quot;);<br>Console.WriteLine(&quot;After Mongo Query…&quot;);<br>Console.WriteLine(&quot;Before External API…&quot;);</pre><p>Then you deploy again, reproduce the issue, inspect the logs, and maybe discover the problem after several attempts.</p><p>I’ve been in exactly this situation.</p><p>One of our APIs became significantly slower than expected. Initially, I didn’t know whether the bottleneck was:</p><p>- The controller<br>- Business logic<br>- MongoDB<br>- An external HTTP call<br>- Serialization<br>- Network latency</p><p>Instead of guessing, I enabled **OpenTelemetry distributed tracing**.</p><p>Within minutes, the trace showed that almost all of the request time was spent executing a MongoDB query. After analyzing the query, I added appropriate indexes, and the latency dropped dramatically.</p><p>That experience completely changed how I think about debugging distributed systems.</p><p>This is exactly why **Observability** exists.</p><h3>What is Observability?</h3><p>Observability is the ability to understand what is happening inside a system <strong>from the outside</strong> by analyzing the telemetry data it emits.</p><p>More importantly, observability helps answer the question:</p><p><strong>”Why is this happening?”</strong></p><p>Traditional monitoring tells us that something is wrong.</p><p>Observability tells us <strong>why</strong> it is wrong.</p><p>It allows engineers to investigate problems that they never anticipated — often called <strong>unknown unknowns.</strong></p><p>Instead of modifying application code every time a problem occurs, a properly instrumented application already produces enough information to diagnose issues.</p><h3>Monitoring vs Observability</h3><p>Many people confuse monitoring with observability.</p><p>Monitoring answers questions that you already know to ask.</p><p>Examples:</p><p>- Is CPU above 80%?<br>- Is memory usage increasing?<br>- Is the service down?</p><p>Observability goes much further.</p><p>It lets you ask questions you didn’t know you would need:</p><p>- Why did this request take 8 seconds?<br>- Which microservice introduced the delay?<br>- Which database query is responsible?<br>- Which external dependency is failing?<br>- Which tenant experiences the problem?</p><p>Instead of predefined dashboards, observability enables exploration.</p><h3>The Three Pillars of Observability</h3><p>Observability is commonly built upon three types of telemetry data:</p><p>- Logs<br>- Metrics<br>- Traces</p><p>Together they provide a complete picture of system behavior.</p><h4>Logs</h4><p>Logs are timestamped records generated by applications.</p><p>Examples:</p><pre>User logged in<br>Payment started<br>Order created<br>Connection failed</pre><p>Logs are excellent for recording events and errors.</p><p>However, logs alone have limitations.</p><p>Suppose a request passes through six microservices.</p><p>Each service generates hundreds of log entries.</p><p>Finding which logs belong to one user request becomes difficult.</p><p>Logs answer:</p><p><em>“What happened?”</em></p><p>But not necessarily:</p><p><em>“How did the request travel through the system?”</em></p><h4>Metrics:</h4><p>Metrics are numerical measurements collected over time.</p><p>Examples include:</p><p>- CPU utilization<br>- Memory usage<br>- Request count<br>- Requests per second<br>- Error rate<br>- Database latency</p><p>Metrics are ideal for dashboards and alerting.</p><p>For example:</p><p>- Average response time increased<br>- Error rate exceeded 5%<br>- CPU reached 95%</p><p>Metrics help answer:</p><p><em>“How much?”</em></p><p>But they cannot fully explain:</p><p><em>“Why?”</em></p><h4>Traces</h4><p>Tracing is arguably the most powerful part of observability for distributed systems.</p><p>A trace records the complete journey of a single request across multiple services.</p><p>Imagine a user sends a request:</p><pre>Client<br>↓<br>API Gateway<br>↓<br>Order Service<br>↓<br>Inventory Service<br>↓<br>Payment Service<br>↓<br>MongoDB</pre><p>Every operation becomes part of one trace.</p><p>Instead of isolated logs from multiple systems, you can visualize the entire execution path.</p><p>Tracing makes distributed systems understandable.</p><h3>Understanding Spans</h3><p>A trace consists of one or more <strong>spans</strong>.</p><p>A span represents a single unit of work.</p><p>Examples:</p><p>- HTTP request<br>- SQL query<br>- MongoDB query<br>- Redis operation<br>- External API call<br>- Kafka publish<br>- RabbitMQ consume</p><p>Each span contains information such as:</p><p>- Name<br>- Start time<br>- End time<br>- Duration<br>- Status<br>- Attributes (metadata)<br>- Events</p><p>For example:</p><pre>Trace<br>├── HTTP Request (1200 ms)<br>├── Business Logic (150 ms)<br>└── Mongo Query (950 ms)</pre><p>Immediately, we can see where the latency originates.</p><p>Without tracing, this investigation could take hours.</p><h3>What is OpenTelemetry?</h3><p>OpenTelemetry (often abbreviated as OTel) is an open-source observability framework that standardizes the collection of:</p><ul><li>Traces</li><li>Metrics</li><li>Logs</li></ul><p>Instead of every vendor providing its own instrumentation library, OpenTelemetry provides a common standard.</p><p>It enables applications to generate telemetry data that can later be exported to different observability platforms.</p><p>One of its biggest strengths is vendor neutrality.</p><p>Today you may use Jaeger.</p><p>Tomorrow you may migrate to Grafana.</p><p>Your application instrumentation remains largely unchanged.</p><h3>How OpenTelemetry Helped Me Find a Performance Problem</h3><p>One of our APIs unexpectedly became slow.</p><p>Initially, I considered several possibilities:</p><p>- Business logic<br>- Network latency<br>- MongoDB<br>- External services</p><p>Without tracing, every hypothesis would require manual investigation.</p><p>After enabling OpenTelemetry tracing, I opened the distributed trace and immediately noticed that the MongoDB span consumed most of the request duration.</p><p>The visualization looked conceptually like this:</p><pre>HTTP Request<br>├── Authentication (20 ms)<br>├── Business Logic (45 ms)<br>├── Mongo Query (1750 ms)<br>└── Response (15 ms)</pre><p>The culprit was obvious.</p><p>The MongoDB query needed optimization.</p><p>After creating appropriate indexes, the query execution time dropped significantly, and the API performance improved.</p><p>Rather than guessing, the trace provided evidence.</p><p>This experience demonstrated that observability is not just about collecting data — it is about reducing debugging time and making better engineering decisions.</p><h3>OpenTelemetry in .NET: Activity</h3><p>In .NET, distributed tracing is implemented through the <em>System.Diagnostics.Activity</em> class.</p><p>Within OpenTelemetry, an <em>Activity</em> essentially represents a span.</p><p>An Activity stores information such as:</p><p>- TraceId<br>- SpanId<br>- ParentId<br>- Duration<br>- Tags<br>- Events<br>- Status</p><p>When an HTTP request enters an ASP.NET Core application, an Activity is typically created automatically.</p><p>As execution continues through services and repositories, child Activities can be created for database operations or external calls.</p><h3>Activity Flows Through Async Operations</h3><p>One impressive feature of .NET is that <em>Activity.Current </em>flows through asynchronous execution.</p><p>For example:</p><pre>Controller<br>↓<br>Service<br>↓<br>Repository<br>↓<br>MongoDB</pre><p>Even if methods use <em>await</em>, the current Activity remains available throughout the logical execution context.</p><p>This allows the entire request to remain connected within the same trace.</p><h3>Tags vs Baggage</h3><p>These two concepts are frequently confused.</p><h4>Tags</h4><p>Tags are metadata attached to a specific Activity.</p><p>Examples:</p><pre>user.id<br>order.id<br>db.collection<br>payment.type</pre><p>They describe that particular span.</p><p>They do not automatically propagate to other spans.</p><p>Think of tags as annotations on one operation.</p><h4>Baggage</h4><p>Baggage serves a different purpose.</p><p>It stores small pieces of contextual information that can propagate across service boundaries.</p><p>For example:</p><pre>tenantId<br>customerType<br>correlationId</pre><p>Suppose Service A calls Service B over HTTP.</p><p>The baggage can travel with the request so downstream services have access to the same contextual information.</p><p>This is extremely useful for multi-tenant systems or business context propagation.</p><h3>Does Baggage Always Flow?</h3><p><strong>No</strong>.</p><p>Baggage can propagate across supported communication channels such as HTTP when propagation is configured.</p><p>However, consider this scenario:</p><pre>API<br>↓<br>RabbitMQ<br>↓<br>Worker</pre><p>or</p><pre>API<br>↓<br>Kafka<br>↓<br>Consumer</pre><p>The original request has already completed.</p><p>The background worker executes independently.</p><p>Therefore, <em>Activity.Current</em> is not automatically available inside the worker.</p><p>If you want trace context or baggage to continue, you must explicitly propagate and restore that context through the message.</p><p>This distinction is important when designing event-driven architectures.</p><h3>OpenTelemetry Automatically Instruments Many Operations</h3><p>Modern OpenTelemetry libraries can automatically capture spans for many common operations, including:</p><ul><li>Incoming HTTP requests</li><li>Outgoing HTTP requests</li><li>SQL Server queries</li><li>PostgreSQL queries</li><li>MongoDB operations</li><li>Redis operations</li><li>gRPC calls</li></ul><p>As a result, developers often obtain end-to-end traces with minimal code changes.</p><h3>What is the OpenTelemetry Collector?</h3><p>One of the most useful components of the OpenTelemetry ecosystem is the <strong>OpenTelemetry Collector</strong>.</p><p>Instead of every application sending telemetry directly to different backends, applications can send everything to the Collector.</p><p>The Collector then:</p><p>- Receives telemetry<br>- Processes it<br>- Filters it<br>- Enriches it<br>- Batches it<br>- Exports it</p><p>Conceptually:</p><pre>Application<br>↓<br>OpenTelemetry SDK<br>↓<br>OpenTelemetry Collector<br>↓<br>Jaeger</pre><p>This architecture provides several advantages:</p><p>- Vendor independence<br>- Centralized configuration<br>- Better scalability<br>- Easier maintenance<br>- Ability to export to multiple systems simultaneously</p><h3>Exporters</h3><p>Exporters determine where telemetry data is sent.</p><p>Examples include:</p><h4>Jaeger</h4><p>Jaeger specializes in distributed tracing.</p><p>It allows developers to visualize traces and inspect spans across multiple services.</p><p>When debugging latency problems, Jaeger provides an excellent end-to-end view of request execution.</p><h4>Prometheus</h4><p>Prometheus focuses primarily on metrics.</p><p>It periodically scrapes metric endpoints and stores time-series data.</p><p>Typical metrics include:</p><p>- Request count<br>- Response time<br>- Error rate<br>- CPU usage<br>- Memory usage</p><p>Prometheus is widely used for alerting and operational monitoring.</p><h4>Grafana</h4><p>Grafana is a <strong>visualization</strong> platform.</p><p>It can display information collected from multiple sources, including Prometheus and tracing backends.</p><p>Grafana dashboards allow engineers to monitor:</p><p>- Service health<br>- Request latency<br>- Throughput<br>- Error rates<br>- Infrastructure metrics</p><p>Everything can be viewed in one place.</p><h3>Why Tracing Matters in Microservices?</h3><p>In a monolithic application, debugging is relatively straightforward because everything executes within one process.</p><p>In a microservice architecture, a single user request may involve:</p><p>- API Gateway<br>- Authentication Service<br>- Order Service<br>- Inventory Service<br>- Payment Service<br>- Notification Service<br>- Database<br>- Cache</p><p>Without distributed tracing, reconstructing this execution path is extremely difficult.</p><p>Tracing connects all these operations into one coherent story.</p><h3>Final Thoughts</h3><p>Observability is far more than collecting logs.</p><p>It is the ability to understand complex systems by combining logs, metrics, and traces to answer questions that were never anticipated during development.</p><p>OpenTelemetry has become the industry standard for achieving this goal because it provides a vendor-neutral way to instrument applications and export telemetry to multiple platforms.</p><p>For me, its value became obvious when an API suddenly became slow. Rather than adding dozens of log statements or guessing where the bottleneck was, distributed tracing showed that a MongoDB query was responsible for most of the latency. After adding the appropriate indexes, the issue was resolved.</p><h3>Related Topics:</h3><ul><li><a href="https://medium.com/@nikoo.asadnejad.work/essential-concepts-every-software-engineer-must-know-43a9cf6b7ef2"><strong>Essential Concepts Every Software Engineer Must Know.</strong></a></li><li><a href="https://medium.com/@nikoo.asadnejad.work/microservices-at-scale-docker-swarms-load-balancing-and-raft-consensus-mechanisms-6a90af924e98"><strong>Microservices at Scale: Docker Swarm’s Load Balancing and Raft Consensus Mechanisms</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3a43ce6795b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[C# Multithreading and Asynchronous Programming: Interview Questions Every .NET Developer Should Know]]></title>
            <link>https://medium.com/@nikoo.asadnejad.work/c-multithreading-and-asynchronous-programming-interview-questions-every-net-developer-should-know-d371311320d8?source=rss-155ce63ec305------2</link>
            <guid isPermaLink="false">https://medium.com/p/d371311320d8</guid>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[asynchronous-programming]]></category>
            <dc:creator><![CDATA[Nikoo Asadnejad]]></dc:creator>
            <pubDate>Fri, 05 Jun 2026 07:33:46 GMT</pubDate>
            <atom:updated>2026-06-05T07:33:46.007Z</atom:updated>
            <content:encoded><![CDATA[<h3>Advanced C# Multithreading and Asynchronous Programming: Interview Questions Every .NET Developer Should Know</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*Rj-RX14kIfuQHtvodmurag.png" /></figure><p>Modern .NET applications increasingly rely on concurrency and asynchronous programming to achieve scalability, responsiveness, and efficient resource utilization. Whether you’re preparing for a senior .NET interview or strengthening your understanding of concurrency, mastering multithreading concepts is essential.</p><p>This article explores some of the most important advanced C# multithreading and asynchronous programming interview questions and answers.</p><h3>What Synchronization Primitives Are Available in C# for Managing Resource Access?</h3><p>C# provides several synchronization primitives that help control access to shared resources and maintain data consistency in multithreaded environments.</p><h4>Monitor</h4><p>Monitor allows a thread to acquire a lock on an object and is commonly used through the lock statement.</p><p>Characteristics:</p><p>- Fast synchronization mechanism<br>- Operates within a single process<br>- Best suited for short-lived critical sections with low contention</p><h4>lock Statement</h4><p>The lock statement is syntactic sugar around Monitor.Enter() and Monitor.Exit().</p><p>Benefits:</p><p>- Easy to use<br>- Automatically releases locks<br>- Ideal for protecting critical sections</p><h4>Mutex</h4><p>A Mutex functions similarly to a Monitor but supports synchronization across <strong>multiple</strong> processes.</p><p>Characteristics:</p><p>- Cross-process synchronization<br>- Suitable for shared resources accessed by multiple applications<br>- Higher overhead than Monitor due to operating system involvement</p><h4>Semaphore</h4><p>A Semaphore controls access to a resource by limiting the number of threads that may enter simultaneously.</p><p>Characteristics:</p><ul><li>Maintains a count rather than a simple locked/unlocked state</li><li>Useful in asynchronous programming</li><li>Useful for connection pools and resource throttling</li><li>Supports controlled concurrency</li></ul><h4>ReaderWriterLock and ReaderWriterLockSlim</h4><p>These synchronization primitives allow:</p><p>- Multiple concurrent readers<br>- A single writer at a time</p><p>They are especially useful when reads occur far more frequently than writes.</p><h3>What Is a Deadlock and How Can It Be Avoided?</h3><p>A deadlock occurs when two or more threads are <strong>waiting indefinitely</strong> for resources held by one another.</p><p>As a result:</p><p>- Execution stops progressing<br>- Threads remain permanently blocked</p><h4>Strategies for Avoiding Deadlocks</h4><p><strong>1.Consistent Lock Ordering</strong></p><p>Acquire locks in a <strong>predefined order</strong> throughout the application.</p><p>This prevents circular waiting, one of the key conditions that causes deadlocks.</p><p><strong>2. Lock Timeouts</strong></p><p>Use timeout-based lock acquisition strategies.</p><p>If a lock cannot be acquired within a specified period, release existing locks and retry.</p><p><strong>3.Deadlock Detection</strong></p><p>Some systems implement deadlock detection and recovery mechanisms, particularly when deadlocks could significantly impact availability.</p><h3>What Is the Difference Between a Task and a Thread?</h3><p>A Thread represents an <strong>operating system</strong> execution path.</p><p>A Task represents an asynchronous operation and provides a higher-level <strong>abstraction</strong> over threads.</p><h4>Benefits of Task</h4><p><strong>Asynchronous Programming</strong></p><p>Tasks integrate naturally with the async and await keywords.</p><p><strong>Resource Management</strong></p><p>Tasks often execute using ThreadPool threads, reducing the overhead associated with creating dedicated threads.</p><p><strong>Composability</strong></p><p>Tasks can easily be chained and combined to create complex asynchronous workflows.</p><p><strong>Exception Handling</strong></p><p>Tasks provide a centralized model for handling exceptions in asynchronous operations.</p><p>In short, a Thread represents <strong>execution</strong>, while a Task represents <strong>work</strong>.</p><h3>How Can Safe Data Exchange Be Ensured Between Threads?</h3><p>Thread-safe communication is critical for maintaining data consistency.</p><h4>Synchronization Primitives</h4><p>Use mechanisms such as:</p><p><strong>- lock<br>- Monitor<br>- Mutex<br>- Semaphore<br>- ReaderWriterLock</strong></p><p>to protect shared resources.</p><h4>Concurrent Collections</h4><p>The .NET framework provides thread-safe collections, including:</p><p><strong>- ConcurrentDictionary<br>- ConcurrentQueue<br>- ConcurrentStack<br>- BlockingCollection<br>- ConcurrentBag</strong></p><p>These collections are designed specifically for concurrent access.</p><h4>Immutable Data Structures</h4><p>Immutable objects cannot be modified after creation.</p><p>Because no state changes occur, they can safely be shared among threads without synchronization.</p><h4>volatile Keyword</h4><p>The volatile keyword ensures that reads and writes occur directly against main memory rather than potentially stale cached values.</p><h3>How Do async and await Enable Asynchronous Programming?</h3><p>The async and await keywords allow developers to write asynchronous code that resembles synchronous code.</p><p>When an awaited operation has not yet completed:</p><p>- Execution pauses<br>- The current thread is released<br>- The thread can perform other work<br>- Execution resumes when the operation completes</p><p>This model improves resource utilization while hiding much of the complexity traditionally associated with asynchronous programming.</p><h3>What Is Thread-Local Storage?</h3><p>Thread-Local Storage (TLS) allows each thread to maintain its own isolated copy of a variable.</p><p>C# supports TLS through:</p><p><strong>- ThreadStatic<br>- ThreadLocal&lt;T&gt;</strong></p><p>Benefits include:</p><p>- Thread-specific state management<br>- Reduced synchronization requirements<br>- <strong>Isolation</strong> between threads</p><h3>What Is the Purpose of Memory Barriers?</h3><p>Modern compilers and processors may reorder instructions to optimize performance.</p><p>Memory barriers, also known as memory fences, ensure a <strong>specific ordering of memory</strong> operations.</p><p>They:</p><p>- Prevent unwanted instruction reordering<br>- Maintain data consistency between threads<br>- Ensure visibility of writes and reads across threads</p><p>Memory barriers are particularly important when correct behavior depends on operation ordering.</p><h3>When Should SpinLock Be Used?</h3><p>SpinLock differs from traditional locks because it actively spins while waiting for a lock rather than suspending the thread.</p><p>SpinLock is most effective when:</p><p>- Lock <strong>hold times</strong> are extremely <strong>short</strong><br>- Context switching overhead exceeds the expected wait time<br>- High-performance scenarios require minimal synchronization overhead</p><p>It is best suited for situations where locks are expected to become available almost immediately.</p><h3>What Is the Purpose of the volatile Keyword?</h3><p>The volatile keyword informs the compiler that a field may be accessed by multiple threads simultaneously.</p><p>It provides:</p><p>- Improved visibility of updates across threads<br>- Protection from certain compiler optimizations<br>- Memory-barrier-like behavior</p><p>As a result, reads and writes interact directly with <strong>main memory</strong> rather than relying on cached values.</p><p>This helps ensure that threads observe the most recent value of the variable.</p><h3>What Are the Differences Between BlockingCollection, ConcurrentBag, ConcurrentQueue, and ConcurrentStack?</h3><h4>BlockingCollection</h4><p>A wrapper around concurrent collections that adds:</p><p>- Blocking capabilities<br>- Bounding capabilities</p><p>It is commonly used in producer-consumer scenarios.</p><h4>ConcurrentBag</h4><p>A thread-safe <strong>unordered</strong> collection optimized for situations where threads frequently add and remove their own items.</p><h4>ConcurrentQueue</h4><p>A thread-safe First-In-First-Out (<strong>FIFO</strong>) collection.</p><h4>ConcurrentStack</h4><p>A thread-safe Last-In-First-Out (<strong>LIFO</strong>) collection.</p><h4>ConcurrentDictionary</h4><p>A thread-safe key-value collection supporting concurrent access and updates.</p><h3>What Is ThreadLocal&lt;T&gt;?</h3><p>ThreadLocal&lt;T&gt; provides thread-specific data storage.</p><p>Each thread receives its own independent value.</p><h4>Advantages</h4><p><strong>Data Isolation</strong></p><p>Eliminates sharing between threads.</p><p><strong>Performance</strong></p><p>Access is typically faster than accessing shared data protected by locks.</p><h4>Drawbacks</h4><p><strong>Increased Memory Usage</strong></p><p>Each thread maintains its own instance.</p><p><strong>Potential Memory Leaks</strong></p><p>Improper cleanup or long-lived threads can increase memory consumption.</p><h3>What Is AsyncLocal&lt;T&gt;?</h3><p>While ThreadLocal&lt;T&gt; stores data per physical thread, AsyncLocal&lt;T&gt; stores data per <strong>asynchronous execution flow</strong>.</p><p>This makes AsyncLocal&lt;T&gt; particularly useful in asynchronous applications where execution may continue on different threads while preserving contextual information.</p><h3>What Is Starvation in Multithreaded Programming?</h3><p>Starvation occurs when one or more threads are continually denied access to resources or CPU time because other threads repeatedly monopolize them.</p><p>Potential consequences include:</p><p>- Reduced throughput<br>- Application unresponsiveness<br>- Execution delays</p><p>Starvation is often caused by poor scheduling or resource allocation strategies.</p><h3>How Does CancellationToken Help Manage Tasks and Threads?</h3><p>CancellationToken enables cooperative cancellation of operations.</p><h4>Benefits</h4><p><strong>Cooperative Cancellation</strong></p><p>Tasks can periodically check whether cancellation has been requested.</p><p><strong>Safe Termination</strong></p><p>Operations can exit gracefully without corrupting state.</p><p><strong>Improved Responsiveness</strong></p><p>Applications can react to user actions, timeouts, or changing conditions by canceling unnecessary work.</p><h3>How Does the Interlocked Class Facilitate Synchronization?</h3><p>The Interlocked class provides atomic operations.</p><p>Atomic operations complete without interruption by other threads.</p><h4>Benefits</h4><p><strong>Safety</strong></p><p>Allows thread-safe updates without locks.</p><p><strong>Performance</strong></p><p>Often faster than lock-based synchronization.</p><p><strong>Consistency</strong></p><p>Ensures correctness even when multiple threads access the same data concurrently.</p><p>Typical operations include:</p><p>- Incrementing counters<br>- Swapping values<br>- Updating shared variables</p><h3>Why Doesn’t lock Work Well with Asynchronous Code?</h3><p>The traditional lock mechanism <strong>blocks</strong> the current thread until the lock becomes available.</p><p>In asynchronous scenarios, blocking threads can:</p><p>- Reduce scalability<br>- Increase thread pool pressure<br>- Introduce deadlocks</p><p>Because asynchronous programming is designed to <strong>free threads</strong> while waiting, blocking synchronization mechanisms undermine many of its benefits.</p><h3>How Can Synchronization Be Achieved in Asynchronous Methods?</h3><p>Several synchronization primitives are better suited for asynchronous code.</p><h4>SemaphoreSlim</h4><p>Supports both synchronous and asynchronous waiting.</p><h4>AsyncLock</h4><p>Often implemented using SemaphoreSlim to provide lock-like behavior for asynchronous workflows.</p><h4>Mutex and ReaderWriterLockSlim</h4><p>Although traditionally associated with thread synchronization, they can be applied carefully in certain asynchronous scenarios.</p><p>These approaches allow mutual exclusion while avoiding unnecessary thread blocking.</p><h3>What Is the Purpose of Task.Yield()?</h3><p>Task.Yield() immediately yields execution back to the task scheduler.</p><p>This gives other queued work an opportunity to execute before the current operation continues.</p><h4>Benefits</h4><p><strong>Fairness</strong></p><p>Prevents long-running operations from monopolizing execution resources.</p><p><strong>Responsiveness</strong></p><p>Allows user interface updates and other pending work to proceed.</p><p><strong>Fine-Grained Scheduling Control</strong></p><p>Introduces an explicit asynchronous boundary into execution flow.</p><p>By temporarily yielding execution, Task.Yield() promotes more responsive and cooperative task scheduling.</p><h3>Best Practices for Multithreaded Development</h3><p>When working with multithreaded and asynchronous applications:</p><p>- Use synchronization primitives when accessing shared resources.<br>- Keep lock durations as short as possible.<br>- Avoid holding locks during I/O operations.<br>- Prefer Task and async/await over manually managing threads.<br>- Understand race conditions, deadlocks, and starvation.<br>- Utilize concurrent collections whenever possible.<br>- Consider immutable data structures for shared data.<br>- Use CancellationToken for long-running operations.<br>- Test under load and stress conditions to uncover concurrency issues.</p><h3>Conclusion</h3><p>Advanced<a href="https://medium.com/@nikoo.asadnejad.work/c-multithreading-and-concurrency-a-comprehensive-overview-08b0734a7a0e"> multithreading and asynchronous programming concepts</a> are fundamental for building scalable and reliable .NET applications. Understanding synchronization primitives, deadlocks, memory barriers, concurrent collections, cancellation, atomic operations, and asynchronous coordination mechanisms enables developers to write safer and more efficient concurrent code.</p><p>Mastering these topics will not only improve application quality but also prepare you for senior-level .NET interviews where concurrency and asynchronous programming frequently appear as key discussion areas.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d371311320d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inside Modern AI Search: RAG, Embeddings, Vector Databases, and Similarity Algorithms]]></title>
            <link>https://medium.com/@nikoo.asadnejad.work/inside-modern-ai-search-rag-embeddings-vector-databases-and-similarity-algorithms-b282342e0286?source=rss-155ce63ec305------2</link>
            <guid isPermaLink="false">https://medium.com/p/b282342e0286</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[vector-search]]></category>
            <category><![CDATA[embedding]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Nikoo Asadnejad]]></dc:creator>
            <pubDate>Thu, 04 Jun 2026 11:40:35 GMT</pubDate>
            <atom:updated>2026-06-11T13:17:41.382Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SvokklbDo1pUdDijtMrc2Q.png" /></figure><h3>Introduction</h3><p>Large Language Models (LLMs) such as GPT, Gemini, Claude, and Qwen can generate human-like text and answer a wide variety of questions. However, these models have an important limitation: they can only answer based on information available in their training data and the context provided in the prompt.</p><p>Retrieval-Augmented Generation (RAG) addresses this limitation by combining information retrieval techniques with language models. Instead of relying solely on the model’s internal knowledge, a RAG system retrieves relevant information from external data sources and provides it to the model before generating a response.</p><p>RAG systems are widely used in enterprise search, document question answering, customer support assistants, knowledge management systems, and AI-powered applications that require access to private or frequently changing information.</p><h3>What Is Retrieval-Augmented Generation (RAG)?</h3><p>Retrieval-Augmented Generation (RAG) is an architecture that combines:</p><p>1. <strong>Information Retrieval</strong><br>2. <strong>External Knowledge Sources</strong><br>3. <strong>Large Language Models</strong></p><p>The goal is to allow the language model to generate answers based on relevant retrieved information rather than relying only on its training data.</p><p>A typical RAG workflow consists of the following steps:</p><p>1. Documents are collected from knowledge sources.<br>2. Documents are split into smaller chunks.<br>3. Each chunk is converted into a vector representation using an embedding model.<br>4. Vectors are stored in a vector database.<br>5. A user’s question is converted into an embedding.<br>6. Similar vectors are retrieved from the database.<br>7. Retrieved content is added to the prompt.<br>8. The language model generates an answer using the retrieved context.</p><p>This approach enables AI systems to answer questions about information that was not available during the model’s training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*qdfooG-M8hdqo7AXVXj7_g.webp" /></figure><h3>Document Chunking</h3><p>Most documents are too large to be stored and searched efficiently as a single unit.</p><p>For this reason, documents are divided into smaller sections called chunks.</p><p>For example, a Kubernetes guide might be split into:</p><p>- Introduction to Kubernetes<br>- Pods and Containers<br>- Deployments<br>- Horizontal Pod Autoscaler<br>- Services and Networking</p><p>Chunking improves retrieval precision because only the relevant portions of a document need to be retrieved.</p><h3>What Are Embeddings?</h3><p>Embeddings are numerical representations of data generated by machine learning models.</p><p>An embedding model converts text into a vector consisting of many numerical dimensions.</p><p>For example:</p><p>Text: <em>“Train booking”</em></p><p>might be transformed into: <em>[0.23, -0.41, 0.82, …]</em></p><p>The exact values are not meaningful to humans. What matters is the relationship between vectors.</p><p>Texts with similar meanings tend to have vectors that are close together in the vector space.</p><p>Examples:</p><p>- <em>Train booking</em><br>- <em>Railway reservation</em></p><p>Although they use different words, a well-trained embedding model often produces similar vectors because the concepts are semantically related.</p><h3>How Embedding Models Learn Semantic Relationships</h3><p>Embedding models are trained on large collections of text.</p><p>During training, the model learns statistical relationships between words, phrases, and sentences.</p><p>Words that frequently appear in similar contexts tend to receive similar vector representations.</p><p>For example:</p><p>- <em>Train station</em><br>- <em>Railway station</em></p><p>- <em>Book a train ticket</em><br>-<em> Make a railway reservation</em></p><p>Because these phrases appear in similar contexts across large datasets, the model learns that terms such as “train” and “railway” are related concepts.</p><p>The semantic understanding comes from the embedding model itself, not from the vector database.</p><h3>Popular Embedding Models</h3><p>Several embedding models are commonly used in retrieval systems:</p><h4>OpenAI Embeddings</h4><p>Examples:</p><p><strong>- text-embedding-3-small<br>- text-embedding-3-large</strong></p><h4>BGE Models</h4><p>Developed by BAAI.</p><p>Examples:</p><p><strong>- BGE-Small<br>- BGE-Base<br>- BGE-Large<br>- BGE-M3</strong></p><h4>E5 Models</h4><p>Examples:</p><p><strong>- E5-Small<br>- E5-Base<br>- E5-Large</strong></p><h4>Sentence Transformers</h4><p>Examples:</p><p><strong>- all-MiniLM-L6-v2<br>- all-mpnet-base-v2</strong></p><p>These models are designed specifically for semantic retrieval and similarity search tasks.</p><h3>Dense Vectors</h3><p>Most modern embedding models generate dense vectors.</p><p>A dense vector contains values in most dimensions.</p><p>Example:</p><p>[0.23, -0.41, 0.82, 0.11, -0.37]</p><p>Dense vectors are effective at representing semantic meaning.</p><p>Advantages include:</p><p>- Semantic similarity search<br>- Synonym detection<br>- Natural language retrieval</p><p>Dense vectors are commonly used in modern RAG systems.</p><h3>Sparse Vectors</h3><p>Sparse vectors contain mostly zero values.</p><p>Traditional information retrieval systems such as BM25 use sparse representations.</p><p>Example vocabulary:</p><p>- train<br>- railway<br>- booking<br>- reservation</p><p>A document containing only “train booking” might be represented as:</p><p>[1, 0, 1, 0]</p><p>Sparse vectors focus on exact terms and term frequencies rather than semantic meaning.</p><p>Advantages include:</p><p>- Strong exact-match retrieval<br>- Good performance for identifiers, codes, and product names<br>- Compatibility with traditional search engines</p><h3>Dense Search vs Sparse Search</h3><p>Consider the query:</p><p><em>“railway reservation”</em></p><p>And a document:</p><p><em>“train booking guide”</em></p><p>Dense retrieval may identify these as similar because the embedding model understands the semantic relationship between the terms.</p><p>Sparse retrieval may not match them strongly because the exact words differ.</p><p>On the other hand, for a query such as: <em>“PNR123456”</em></p><p>Sparse retrieval is typically more effective because exact identifiers are important.</p><p>Many modern systems combine both approaches through hybrid search.</p><h3>Vector Search</h3><p>Vector search is the process of finding vectors that are most similar to a query vector.</p><p>The general workflow is:</p><p>1. Convert documents into embeddings.<br>2. Store embeddings in a vector database.<br>3. Convert the user’s query into an embedding.<br>4. Find the nearest vectors.<br>5. Return the corresponding documents.</p><p>This enables semantic retrieval rather than simple keyword matching.</p><h3>Similarity Metrics in Vector Search</h3><p>Vector databases use mathematical methods to measure similarity between vectors.</p><p>The most common approaches are:</p><h4>Cosine Similarity</h4><p>Cosine similarity measures the angle between vectors.</p><p>Properties:</p><p>- Range from -1 to 1<br>- Higher values indicate greater similarity<br>- Commonly used for semantic search</p><p>Cosine similarity is widely used because it focuses on vector direction rather than magnitude.</p><h4>Euclidean Distance</h4><p>Euclidean distance measures the straight-line distance between vectors.</p><p>Properties:</p><p>- Smaller values indicate greater similarity<br>- Represents geometric distance</p><p>Euclidean distance is commonly used in mathematical and spatial applications.</p><h4>Dot Product</h4><p>The dot product measures similarity using vector multiplication and summation.</p><p>Properties:</p><p>- Computationally efficient<br>- Frequently used in large-scale retrieval systems</p><p>Many embedding models are optimized for dot-product similarity.</p><h3>What Is a Vector Database?</h3><p>A vector database is a specialized database designed to store embeddings and perform efficient similarity searches.</p><p>Unlike traditional databases that primarily search structured fields, vector databases search based on vector similarity.</p><p>Their primary functions include:</p><p>- Storing embeddings<br>- Similarity search<br>- Metadata filtering<br>- High-performance nearest-neighbor retrieval</p><h3>Popular Vector Databases</h3><h4>Qdrant</h4><p>An open-source vector database written in Rust.</p><p>Features:</p><p>- Similarity search<br>- Metadata filtering<br>- Distributed deployment support</p><h4>Milvus</h4><p>An open-source vector database designed for large-scale vector workloads.</p><p>Features:</p><p>- High scalability<br>- Support for large vector collections</p><h4>Weaviate</h4><p>An open-source vector database that supports semantic search and retrieval applications.</p><p>Features:</p><p>- Vector search<br>- Hybrid search capabilities</p><h4>Pinecone</h4><p>A managed vector database service.</p><p>Features:</p><p>- Hosted infrastructure<br>- Managed scaling</p><h4>Elasticsearch</h4><p>Modern versions of Elasticsearch support dense vector fields and vector similarity search in addition to traditional keyword-based retrieval.</p><h3>Hybrid Search</h3><p>Many production systems combine:</p><p>- Sparse retrieval (BM25)<br>- Dense retrieval (Embeddings)</p><p>This approach is known as hybrid search.</p><p>Benefits include:</p><p>- Exact keyword matching<br>- Semantic understanding<br>- Improved retrieval quality</p><p>Hybrid search is commonly used in enterprise search and RAG applications.</p><h3>Conclusion</h3><p>Retrieval-Augmented Generation combines information retrieval and language models to create AI systems that can answer questions using external knowledge sources.</p><p>The core building blocks of a RAG system are:</p><p>- Document chunking<br>- Embeddings<br>- Vector search<br>- Vector databases<br>- Language models</p><p>Embeddings convert text into dense vector representations that capture semantic meaning. Vector databases store these embeddings and enable efficient similarity searches. Similarity metrics such as cosine similarity, Euclidean distance, and dot product determine how closely vectors are related.</p><p>Modern RAG systems often combine dense retrieval with sparse retrieval through hybrid search, providing both semantic understanding and exact keyword matching. This architecture has become a foundational pattern for building AI applications that require accurate access to organizational knowledge and external data sources.</p><h3>Related Topics :</h3><ul><li><a href="https://medium.com/@nikoo.asadnejad.work/from-monoliths-to-societies-understanding-agent-oriented-software-engineering-aose-6552d52c3514?postPublishedType=repub"><strong>From Monoliths to Societies: Understanding Agent-Oriented Software Engineering (AOSE)</strong></a></li><li><a href="https://medium.com/@nikoo.asadnejad.work/understanding-the-model-context-protocol-mcp-how-ai-apps-connect-to-the-world-1d62690c2ec9?postPublishedType=repub"><strong>Understanding the Model Context Protocol (MCP): How AI Apps Connect to the World</strong></a></li><li><a href="https://medium.com/@nikoo.asadnejad.work/ai-vs-machine-learning-vs-neural-networks-vs-deep-learning-bc709468f863?postPublishedType=repub"><strong>AI vs. Machine Learning vs. Deep Learning vs. Neural Networks</strong></a></li><li><a href="https://medium.com/@nikoo.asadnejad.work/how-generative-ai-and-large-language-models-are-transforming-software-5e06c74b420b"><strong>How Generative AI and Large Language Models Are Transforming Software.</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b282342e0286" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OWASP Top 10 (2026): The Most Critical Web Application Security Risks Every Developer Should…]]></title>
            <link>https://medium.com/@nikoo.asadnejad.work/owasp-top-10-2026-the-most-critical-web-application-security-risks-every-developer-should-d41531188c9a?source=rss-155ce63ec305------2</link>
            <guid isPermaLink="false">https://medium.com/p/d41531188c9a</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[security-vulnerabilities]]></category>
            <category><![CDATA[owasp]]></category>
            <category><![CDATA[owasp-top-10]]></category>
            <dc:creator><![CDATA[Nikoo Asadnejad]]></dc:creator>
            <pubDate>Tue, 02 Jun 2026 19:11:42 GMT</pubDate>
            <atom:updated>2026-06-11T13:21:40.392Z</atom:updated>
            <content:encoded><![CDATA[<h3>OWASP Top 10 (2026): The Most Critical Web Application Security Risks Every Developer Should Understand</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*4FcT-YVztTSFxmNUFrivRA.avif" /></figure><h3>Introduction</h3><p>Building secure software is no longer optional. Modern applications rely on APIs, cloud infrastructure, containers, third-party libraries, identity providers, and distributed microservices. Every additional component increases the attack surface.</p><p>The Open Worldwide Application Security Project (OWASP) publishes the OWASP Top 10, a widely recognized awareness document that identifies the most critical security risks affecting web applications.</p><p>The OWASP Top 10 (2026) highlights the vulnerabilities and weaknesses that organizations should prioritize when designing, developing, and operating software systems.</p><p>This article explains each category, why it matters, and practical approaches for reducing risk.</p><h3>A01: Broken Access Control</h3><h3>What Is It?</h3><p>Broken Access Control occurs when users can perform actions or access resources beyond their intended permissions.</p><p>Examples include:</p><ul><li>Accessing another user’s records</li><li>Viewing administrative functionality without authorization</li><li>Privilege escalation</li><li>Bypassing authorization checks</li></ul><h3>Why It Matters</h3><p>OWASP ranks Broken Access Control as the highest risk because authorization mistakes often expose sensitive data and critical business functions.</p><h3>How to Mitigate</h3><ul><li>Enforce server-side authorization checks.</li><li>Apply the principle of least privilege.</li><li>Validate ownership of resources before granting access.</li><li>Use centralized authorization policies.</li><li>Deny access by default and explicitly grant permissions where required.</li></ul><h3>A02: Security Misconfiguration</h3><h3>What Is It?</h3><p>Security Misconfiguration refers to insecure settings in applications, frameworks, servers, cloud services, containers, and infrastructure.</p><p>Examples include:</p><ul><li>Default credentials</li><li>Debug mode enabled in production</li><li>Excessive permissions</li><li>Missing security headers</li><li>Unnecessary services enabled</li></ul><h3>Why It Matters</h3><p>Misconfigurations are among the most common and easiest-to-overlook causes of security incidents.</p><h3>How to Mitigate</h3><ul><li>Establish secure configuration baselines.</li><li>Remove unused features and services.</li><li>Automate configuration reviews.</li><li>Implement infrastructure-as-code validation.</li><li>Apply security headers and HTTPS consistently.</li><li>Perform regular security audits.</li></ul><h3>A03: Software Supply Chain Failures</h3><h3>What Is It?</h3><p>Modern applications depend heavily on external software components, build pipelines, container images, package repositories, and CI/CD systems.</p><p>Software Supply Chain Failures occur when trust in those dependencies is compromised.</p><p>Examples include:</p><ul><li>Malicious packages</li><li>Compromised build pipelines</li><li>Tampered container images</li><li>Dependency poisoning</li></ul><h3>Why It Matters</h3><p>Organizations increasingly rely on thousands of third-party components, making the software supply chain a significant attack surface.</p><h3>How to Mitigate</h3><ul><li>Verify package sources.</li><li>Use trusted repositories.</li><li>Sign and verify software artifacts.</li><li>Continuously scan dependencies.</li><li>Secure CI/CD pipelines.</li><li>Maintain Software Bills of Materials (SBOMs).</li></ul><h3>A04: Cryptographic Failures</h3><h3>What Is It?</h3><p>Cryptographic Failures occur when sensitive information is not properly protected.</p><p>Examples include:</p><ul><li>Weak encryption algorithms</li><li>Missing encryption</li><li>Poor key management</li><li>Improper password storage</li><li>Unprotected secrets</li></ul><h3>Why It Matters</h3><p>Cryptography is often the final layer protecting sensitive information.</p><h3>How to Mitigate</h3><ul><li>Use industry-standard cryptographic algorithms.</li><li>Encrypt sensitive data both in transit and at rest.</li><li>Use secure password hashing algorithms.</li><li>Rotate and protect encryption keys.</li><li>Store secrets in dedicated secret-management systems.</li><li>Enforce HTTPS across all environments.</li></ul><h3>A05: Injection</h3><h3>What Is It?</h3><p>Injection vulnerabilities occur when untrusted input is interpreted as commands or queries.</p><p>Examples include:</p><ul><li>SQL Injection</li><li>Command Injection</li><li>LDAP Injection</li><li>NoSQL Injection</li></ul><h3>Why It Matters</h3><p>Injection attacks can lead to data theft, data modification, remote code execution, and complete system compromise.</p><h3>How to Mitigate</h3><ul><li>Use parameterized queries.</li><li>Avoid dynamic query construction.</li><li>Validate and sanitize inputs.</li><li>Use ORM frameworks appropriately.</li><li>Apply input allowlists where possible.</li></ul><h3>A06: Insecure Design</h3><h3>What Is It?</h3><p>Insecure Design represents flaws in application architecture or business processes rather than implementation bugs.</p><p>Examples include:</p><ul><li>Missing rate limiting</li><li>Lack of abuse prevention</li><li>Weak workflow design</li><li>Missing threat modeling</li></ul><h3>Why It Matters</h3><p>Some security issues cannot be fixed through code patches because they originate from fundamental design decisions.</p><h3>How to Mitigate</h3><ul><li>Conduct threat modeling early.</li><li>Define security requirements during design.</li><li>Evaluate abuse cases.</li><li>Apply secure-by-design principles.</li><li>Perform architecture reviews.</li></ul><h3>A07: Authentication Failures</h3><h3>What Is It?</h3><p>Authentication Failures occur when systems inadequately verify user identities.</p><p>Examples include:</p><ul><li>Weak password policies</li><li>Missing multi-factor authentication</li><li>Insecure session management</li><li>Improper token validation</li></ul><h3>Why It Matters</h3><p>Attackers increasingly target identity systems because compromised accounts often provide direct access to sensitive resources.</p><h3>How to Mitigate</h3><ul><li>Implement Multi-Factor Authentication (MFA).</li><li>Use secure authentication frameworks.</li><li>Enforce strong password policies.</li><li>Protect session tokens.</li><li>Validate tokens properly.</li><li>Monitor suspicious login activity.</li></ul><h3>A08: Software or Data Integrity Failures</h3><h3>What Is It?</h3><p>This category involves failures to verify the integrity of software, updates, data, and trusted processes.</p><p>Examples include:</p><ul><li>Unsigned software updates</li><li>Insecure deserialization</li><li>Compromised deployment pipelines</li><li>Tampered artifacts</li></ul><h3>Why It Matters</h3><p>Organizations increasingly automate deployments and software distribution, making integrity validation essential.</p><h3>How to Mitigate</h3><ul><li>Verify digital signatures.</li><li>Sign software artifacts.</li><li>Protect deployment pipelines.</li><li>Validate update sources.</li><li>Restrict execution of untrusted code.</li></ul><h3>A09: Security Logging and Alerting Failures</h3><h3>What Is It?</h3><p>Organizations often fail to detect attacks because of inadequate logging, monitoring, or alerting.</p><p>Examples include:</p><ul><li>Missing audit logs</li><li>Insufficient monitoring</li><li>Lack of security alerts</li><li>Poor incident visibility</li></ul><h3>Why It Matters</h3><p>Without proper visibility, security incidents may remain undetected for extended periods.</p><h3>How to Mitigate</h3><ul><li>Implement centralized logging.</li><li>Monitor authentication and authorization events.</li><li>Generate alerts for suspicious behavior.</li><li>Retain logs securely.</li><li>Establish incident response procedures.</li></ul><h3>A10: Mishandling of Exceptional Conditions</h3><h3>What Is It?</h3><p>This category focuses on failures that occur when applications encounter unexpected situations or abnormal operating conditions.</p><p>Examples include:</p><ul><li>Improper error handling</li><li>Failing open instead of failing securely</li><li>Unhandled edge cases</li><li>Unexpected state transitions</li></ul><h3>Why It Matters</h3><p>Systems frequently behave differently under stress, failures, or unusual inputs. Poor handling of these situations can introduce security vulnerabilities.</p><h3>How to Mitigate</h3><ul><li>Design systems to fail securely.</li><li>Validate assumptions about application state.</li><li>Implement robust exception handling.</li><li>Test failure scenarios regularly.</li><li>Include resilience and fault-injection testing.</li></ul><h3>Conclusion</h3><p>The OWASP Top 10 is not a checklist of individual vulnerabilities but a framework for understanding the most significant classes of security risk affecting modern applications.</p><p>The 2026 edition emphasizes several important themes:</p><ul><li>Authorization remains the most critical challenge.</li><li>Security misconfigurations continue to cause major incidents.</li><li>Supply chain security has become a primary concern.</li><li>Secure design is as important as secure coding.</li><li>Monitoring and visibility are essential for detecting attacks.</li><li>Organizations must secure the entire software lifecycle, not just application code.</li></ul><p>Developers, architects, and security teams should use the OWASP Top 10 as a foundation for secure software development, threat modeling, architecture reviews, and security testing programs.</p><p>By understanding these risks and implementing appropriate controls, organizations can significantly reduce their exposure to common and high-impact security threats.</p><h3>Related Topics:</h3><ul><li><a href="https://medium.com/@nikoo.asadnejad.work/managing-the-secure-software-development-life-cycle-bridging-methodologies-and-management-3360ce472588"><strong>Managing the Secure Software Development Life Cycle: Bridging Methodologies and Management</strong></a></li><li><a href="https://medium.com/@nikoo.asadnejad.work/essential-concepts-every-software-engineer-must-know-43a9cf6b7ef2"><strong>Essential Concepts Every Software Engineer Must Know</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d41531188c9a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>