<?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 Abhishek on Medium]]></title>
        <description><![CDATA[Stories by Abhishek on Medium]]></description>
        <link>https://medium.com/@abhilodha?source=rss-6b78bc6a2fe0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*p5A7839AEgERPYRfuWHhfQ.jpeg</url>
            <title>Stories by Abhishek on Medium</title>
            <link>https://medium.com/@abhilodha?source=rss-6b78bc6a2fe0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 14:40:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abhilodha/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Understanding RAG from the Ground Up]]></title>
            <link>https://abhilodha.medium.com/understanding-rag-from-the-ground-up-9790d4103a12?source=rss-6b78bc6a2fe0------2</link>
            <guid isPermaLink="false">https://medium.com/p/9790d4103a12</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[agentic-rag]]></category>
            <category><![CDATA[embedding]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[vector-database]]></category>
            <dc:creator><![CDATA[Abhishek]]></dc:creator>
            <pubDate>Sat, 31 Oct 2026 14:44:57 GMT</pubDate>
            <atom:updated>2026-10-31T14:46:17.712Z</atom:updated>
            <content:encoded><![CDATA[<p>From text vectorization and embeddings to semantic retrieval</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2P1uhoFTZGdTPpjyzmYtyw.png" /><figcaption>RAG workflow</figcaption></figure><p>Large language models (LLMs) are trained on large amounts of text and learn to generate responses by predicting the next token based on the preceding context. They are useful for many tasks, including summarization, reasoning, and question answering.</p><p>However, an LLM’s knowledge has limitations. It may not have access to your company’s internal policies, private documentation, latest product information, or other domain-specific data. Its training data also has a cutoff, and retraining or fine-tuning a model every time information changes is often impractical.</p><p>Consider a customer asking an AI support bot about the refund policy. Even if the LLM understands the question, it cannot reliably answer it without access to the relevant policy.</p><p>One approach is to provide the relevant information directly in the prompt. But what if the information is spread across thousands of documents?</p><p>We need a way to find the relevant information first and then provide it to the LLM as context. This is the idea behind <strong><em>Retrieval-Augmented Generation (RAG)</em>.</strong></p><h3>Pre-requisites</h3><ul><li>Basic Python</li><li>Fundamental linear algebra</li><li>Minimal LLM understanding: tokens, prompts, context window</li></ul><h3>What is RAG?</h3><p>RAG stands for <strong><em>Retrieval Augmented Generation</em></strong>. It consists of 2 parts: <strong><em>Retrieval</em></strong> &amp; <strong><em>Generation</em></strong>.</p><p><strong>Retrieval:</strong> Find the relevant information from an external source or information store.</p><p><strong>Generation: </strong>Provide the retrieved information to the LLM to augment its context with required information so it can generate the answer from the context.</p><blockquote>RAG doesn’t change any of the model parameters or retrains the model. It simply adds the relevant information in the context at the inference time.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6xO1sI6YKwah9nlTd7xQIg.png" /></figure><h3>Why vectorize text?</h3><p>Intent of RAG is to find the information relevant to the user’s query from the collection of documents. But how does the system know which documents are relevant?</p><p>Computers store text and the traditional search is based on exact match. But exact match doesn’t always work as the user might ask the same question differently. For example, customer can ask the support bot:</p><ul><li>What is the refund policy?</li><li>How can I get my money back?</li></ul><p>These use different words, but both questions are about refunds.</p><p><strong><em>Text Vectorization</em></strong> converts text into numbers which the computer can use to calculate the similarity score. There are different techniques to do this.</p><ul><li>One Hot Encoding</li><li>TF-IDF (term frequency — Inverse Document frequency)</li><li>Embeddings</li><li>TF-IDF + Embeddings (Hybrid approach)</li></ul><h3>Basics of text vectorization</h3><h4><strong>TF-IDF</strong></h4><p>TF-IDF calculates raw word count by combining 2 signals:</p><ul><li><strong>TF (term frequency):</strong> how often a word appears in a sentence.</li><li><strong>IDF (Inverse Document Frequency):</strong> how rare that word is across the collection of documents.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5pz0vHKTS7I73ZJUOmzDUA.png" /><figcaption>Formulae depicting TF &amp; IDF calculations</figcaption></figure><h4>Example: Calculating TF-IDF</h4><p>For simplicity, consider we have the following 3 sentences in our documents. We will only consider the lower case words for our example.</p><ul><li>The refund is delayed.</li><li>The order arrived damaged.</li><li>The refund was processed.</li></ul><p><strong><em>Term Frequency (TF):</em></strong><em> Counting Words in Each Sentence</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IiY80bc3Sib1JY-ZBHLogg.png" /><figcaption>Count each word’s occurrences and normalize by the total number of words in the sentence.</figcaption></figure><p><strong><em>Inverse Document Frequency (IDF):</em></strong><em> Measuring Word Importance</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WUYIzB_HaHzt373zfy7Cdg.png" /><figcaption>Calculate IDF across the three sentences. Words appearing in more sentences receive lower weights, while less common words receive higher weights.</figcaption></figure><p><strong><em>TF-IDF:</em></strong><em> Combining Term Frequency and Inverse Document Frequency</em></p><blockquote>TFIDF(t, d) = TF(t, d) * IDF(t)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IpMZsT5oW3wNYAmTpsUs1w.png" /><figcaption>Multiply each word’s TF by its IDF to assign a weight that reflects how frequently it appears in a sentence.</figcaption></figure><p>This gives weight to each term in the sentence. Hence each sentence could be represented in the vector format and we can do a cosine similarity to find similar documents. However, this is still keyword search through vector representation. It relies on word overlap rather than meaning.</p><h4>Limitations of TF-IDF</h4><ul><li><strong>Limited semantic understanding:</strong> “What is the refund policy?” and “how can I get my money back?” may have little exact word overlap despite asking the same thing.</li><li><strong>Sparse representation:</strong> Each document vector has one dimension per vocabulary term, and most entries are zero.</li><li>No word order perseverance</li><li>Any updates require re-computation of the TF-IDF score for the entire collection.</li></ul><h3>Introduction to embeddings</h3><p>TF-IDF works really well for exact keyword search but it is less effective for semantic search, that’s where embeddings come in.</p><p>Embeddings convert text into fixed size dense vector representation which helps capture the semantic similarity. Rather than checking which exact words appear, embeddings helps check the closeness of the meaning of the text.</p><p>An embedding maps text into vector of a fixed number of dimensions such ask 374, 768, 1024, 4096.</p><p>A word embedding could be represented as [0.12, 0.31, -0.43, …, 0.87, 0.65].</p><p>Unlike TF-IDF, embedding vector dimension are independent of the vocabulary size and hence are dense representations.</p><blockquote>An embedding vector has no meaning in itself.</blockquote><h4>Word Embeddings</h4><p>A word embedding represents individual words as a vector. In a well-trained embedding space, the words return and moneyback would be close together (they would have greater cosine similarity score).</p><p>But this too has a limitation. Words might have different meaning based on the context.</p><p>For example, bank would have the same representation for the following sentences:</p><ul><li>I deposited my money in the bank.</li><li>They sat on the river bank.</li></ul><p>This is where <strong><em>contextual embeddings</em></strong> help us.</p><h4>Contextual Embedding</h4><p>Contextual embedding solves this by generating the vector for a word/sentence based on its surrounding text. This helps create different embedding for the word bank based on the context around it.</p><h4>How are the embeddings generated?</h4><p>First of all, tokens are created from the sentence or the document. The model splits the text into words, subwords, punctuations. The model then generate a token ID and an initial vector.</p><p>During the training phase, the model sees a huge amount of text which lets it adjust the internal parameters. Self-attention lets each token’s representation influenced by other tokens. After the training, the model is ready with the final token vector.</p><p>For sentence or document, the model combines the token-level vectors into a single vector which is called the embedding.</p><h4>How embeddings are compared?</h4><p>Once we have the embeddings, comparison could be done by using cosine similarity.</p><p>Embedding is a point in a high dimensional space and we can use dot product to calculate the angle between the vectors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0GmzDgODFitiJFS2OOK81g.png" /><figcaption>Cosine calculation between vectors A &amp; B</figcaption></figure><p>For demonstration, we will keep consider a 3-dimensional space. Consider the vectors:</p><pre>A = (1, 2, 2)<br>B = (2, 1, 2)<br>C = (-2, -1, 1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7TE9qn0a76U9ObG_43rwtw.png" /><figcaption>Cosine similarity measuring angle between A &amp; B and A &amp; C — shows A and B are close in the embedding space.</figcaption></figure><blockquote>Lower the angle, closer the points are in space.</blockquote><h3>Indexing documents for RAG</h3><p>Before the RAG application can retrieve the relevant information, we need to index the documents in a vector store. There are multiple steps to indexing:</p><ul><li><strong><em>Document Chunking </em></strong>— All the documents that needs to be indexed are split into smaller chunks while retaining the context and meaning of the text.</li><li><strong><em>Embedding Generation</em></strong> — Each chunk of the document is converted into a vector representation using an embedding model.</li><li><strong><em>Storage</em></strong> — Each embedding is stored along with the corresponding chunk text and metadata.</li></ul><h4>Why we need to chunk documents?</h4><p>Some documents can be very large and contain information about multiple domains or topics. If we create an embedding for the entire document, information about different topics gets compressed into a single vector. This can make it difficult to identify the specific sections that are relevant to a given user query.</p><p>Chunking helps address this problem by splitting the document across smaller, meaningful pieces. There are multiple chunking strategies.</p><ol><li><strong>Size based chunking<br></strong>This is one of the most commonly used methods. A document is generally split into fixed-size chunks, such as 500 tokens, with some overlap between consecutive chunks. The overlap helps preserve context across chunk boundaries.</li><li><strong>Rule based chunking</strong><br>If the documents are in a structured format with headings, subheadings, paragraphs, sentences, or lists, we can leverage these boundaries to chunk the document rather than using a fixed size.</li><li><strong>Semantic chunking<br></strong>This strategy uses the content of the document to identify chunk boundaries. It groups similar content by checking the semantic similarity between consecutive sentences or paragraphs. A significant drop in similarity can indicate a change in topic and help identify a chunk boundary. This approach is generally more computationally expensive.</li></ol><p>There is no optimal chunking strategy. It depends on the type of documents you are trying to index, and sometimes a combination of strategies could be better suited.</p><p>Once the documents are indexed, the system is ready for retrieval.</p><p>When a user submits a query, we generate its embedding using the same embedding model and search the vector store for similar or relevant chunks. The vector store calculates the similarity between the query embedding and the indexed embeddings (<em>using cosine similarity or another configured similarity metric</em>) and returns the top-k results. These results are then passed to the LLM along with the user’s query to generate a response grounded in the retrieved context.</p><h3>What’s next?</h3><p>We have seen how text can be converted into vector representations (<em>embeddings</em>), how these embeddings can be compared using cosine similarity, and how documents are chunked and indexed in a vector store.</p><p>In next part, we will discuss about the retrieval, updating &amp; maintaining documents in vector store and evals.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9790d4103a12" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Practical Walkthrough of Redis]]></title>
            <link>https://abhilodha.medium.com/a-practical-walkthrough-of-redis-8d369bafcb17?source=rss-6b78bc6a2fe0------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d369bafcb17</guid>
            <category><![CDATA[lua]]></category>
            <category><![CDATA[redis-sorted-set]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[games]]></category>
            <category><![CDATA[leaderboard]]></category>
            <dc:creator><![CDATA[Abhishek]]></dc:creator>
            <pubDate>Fri, 23 Oct 2026 16:46:39 GMT</pubDate>
            <atom:updated>2026-10-25T03:44:00.678Z</atom:updated>
            <content:encoded><![CDATA[<p>From data types to building a game leaderboard</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h4TLpaLz_i5SapB61IHqdw.png" /><figcaption>A practical walkthrough of Redis</figcaption></figure><h4>What is Redis?</h4><p>Redis is an in-memory key value datastore used for fast data access. Unlike traditional datastores, it stores the working data in RAM that is faster than SSD or HDD.</p><p>Redis is commonly used for caching, session store, rate limiting, counters, real-time dashboards.</p><p>Redis support multiple data structure including Strings, Hashes, Lists, Sets, Sorted Sets, etc. which we will discuss in details in next sections. Redis also supports other useful types such as Streams, HyperLogLog, Bitmap and Geospatial Indexes.</p><h4>Why Redis?</h4><p>Redis is widely used for caching solution to improve application performance. By storing frequently accessed data in memory, it helps reduce database load, improve throughput and reduce the response latency of your application. This is especially useful when you need to serve frequently requested data.</p><p>Imagine you have an bakery website that displays a list of items available for purchase. Instead of querying the database every time a user visits your website, you can cache the item details in Redis and serve subsequent requests directly from the cache.</p><p>This eliminates unnecessary database queries, speeds up response times, and allows your application to handle more requests efficiently. When the item details change, you can update or invalidate the cached data to ensure users receive the latest information.</p><h4>A brief on how Redis works internally</h4><p>How does Redis handle thousands of concurrent client connections without creating a separate thread for each one?</p><p>Redis uses I/O multiplexing along with event-driven architecture. Instead of dedicating a thread to every client, Redis uses an OS-level I/O multiplexing mechanism (epoll on Linux) to efficiently monitor multiple client connections.</p><ul><li>When a client connects, Redis registers its socket with epoll. The OS monitors these sockets and identifies which are ready for reading or writing.</li><li>Redis runs an <strong>event loop</strong> that waits for the OS to report ready sockets.</li><li>Redis then reads the incoming data, parses the commands, and executes them sequentially on its main command-execution thread. Once the commands are processed, Redis sends the responses back to the respective clients.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DeNYHuDPKbI0CnOR_Dgx6w.png" /><figcaption>How Redis Handles Client Requests?</figcaption></figure><h4>Redis Data Type</h4><p>The most commonly used data types in Redis are:</p><ul><li><em>String</em><br>Stores text, numbers, binary data. Generally used for caching, session tokens, counters, etc.</li></ul><pre>SET user:101:name “John”<br>GET user:101:name<br>INCR page:views</pre><ul><li><em>Hashes</em><br>Stores attribute pairs under a key. Generally used to store object attributes like user profiles, item details, etc.</li></ul><pre>HSET product:101 name &quot;Belgian Chocolate Cake&quot; price 30<br>HGET product:101 name<br>HGETALL product:101</pre><ul><li><em>Lists</em><br>Stores ordered sequence of data. Generally used for recent activity tracking.</li></ul><pre>LPUSH user:101:activity &quot;login&quot;<br>LPUSH user:101:activity &quot;purchase&quot;<br>LRANGE user:101:activity 0 -1</pre><ul><li><em>Sets<br></em>Store unique elements. Generally used to store unique visitors, membership checks.</li></ul><pre>SADD article:42:likes user:101 user:102<br>SISMEMBER article:42:likes user:101<br>SCARD article:42:likes</pre><ul><li><em>Sorted Sets<br></em>Stores unique elements ordered by a score. Generally used to store rankings, leaderships, etc.</li></ul><pre>ZADD game:weekly 1200 player:101<br>ZADD game:weekly 950 player:102<br>ZREVRANGE game:weekly 0 9 WITHSCORES</pre><h4>Sorted Set</h4><p>A sorted set is a collection of unique elements where each element has a floating-point score. Redis automatically keeps elements ordered by score and hence this data type is the go-to choice for implementing leaderboards, rankings without the application level sorting.</p><p>Sorted Set is implemented using Hash tables and Skip-list.</p><ul><li>Hash tables maps each element to its score giving O(1) access time.</li><li>Skip list maintains elements ordered by score.</li></ul><p>A skip-list is a layer linked list structure. The bottom layer contains all the elements in sorted order; higher levels contains subset of elements letting Redis skip over large portions of the list while searching.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0n2orFGP_AbxzXOUyDY3OA.png" /><figcaption>Skip list with multiple levels</figcaption></figure><h4>Weekly Game Leaderboard</h4><p>Consider you’re building a game which conducts weekly contests where millions of players compete to earn the highest score. Every time a player completes some level, their score can change, potentially moving them up or down the leaderboard.</p><p>You need a leaderboard which supports 3 features:</p><ul><li><strong>Top players</strong>: Display the top N players in the weekly contest.</li><li><strong>Player ranking</strong>: Get the players current rank without fetching all the users.</li><li><strong>Nearby players</strong>: Show a few players ranked above and below the player.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UYDJ6hm7XkqKBCuRZsvxEw.png" /><figcaption>Weekly Leaderboard showing top 3 players, current rank of the player and few player above and below.</figcaption></figure><p>The challenge is to make all the 3 operations fast even with millions of players. The score may change throughout the week as players keep playing and the leaderboard needs to reflect these changes efficiently without repeatedly fetching and sorting every player’s score in the application.</p><p>Additionally the leaderboard resets every week for a new contest while the previous contest results remain accessbile.</p><p>Let’s see how Redis sorted set can be used to retrieve the player ranking efficiently. Sorted sets can be used to add/update the player score, retrieve top players, find a player’s rank and get list of nearby players.</p><p><strong><em>Add players’ score to a Sorted Set:</em></strong></p><p>ZADD leaderboard:weekly:2026-W42 10 player_1 — Adds player_1 with score 10</p><p>ZADD leaderboard:weekly:2026-W42 5 player_2 — Adds player_2 with score 5</p><blockquote>There is no need to explicitly create a sorted set before starting to add elements. Redis automatically creates the data structure when the first element is added using ZADD command. If a player already exists in the Sorted Set, ZADD updates their score instead of creating a duplicate member.</blockquote><p><strong><em>Check whether a player exists:</em></strong></p><p>ZSCORE leaderboard:weekly:2026-W42 player_1</p><p>ZSCORE returns the player&#39;s current score. If the player doesn&#39;t exist, Redis returns a null result, which can also be used to check membership.</p><p><strong><em>Update player’s score:</em></strong></p><p>ZINCRBY leaderboard:weekly:2026-W42 5 player_1</p><p>This increments player_1&#39;s score by 5. This is an atomic transaction.</p><p><strong><em>Get the top 3 players:</em></strong></p><p>ZRANGE leaderboard:weekly:2026-W42 0 2 REV WITHSCORES</p><p>The REV option returns players in descending order, while WITHSCORES includes their scores in the result.</p><p><strong><em>Get a player’s rank:</em></strong></p><p>ZREVRANK leaderboard:weekly:2026-W42 player_1</p><p>This returns the player’s rank in descending order. Redis uses zero-based indexing, so rank 0 represents first place.</p><p><strong><em>Get a player’s score:</em></strong></p><p>ZSCORE leaderboard:weekly:2026-W42 player_1</p><p>Same as checking player’s existence in the set</p><p><strong><em>Remove a player:</em></strong></p><p>ZREM leaderboard:weekly:2026-W42 player_1</p><p><strong><em>Get nearby players:</em></strong></p><p>ZREVRANK leaderboard:weekly:2026-W42 player_1</p><p>ZRANGE leaderboard:weekly:2026-W42 48 52 REV WITHSCORES</p><p>When a new contest starts, the application starts writing to a new key. The previous week’s leaderboard remains separate and can still be accessed until its deleted or expired.</p><h4>Lua Scripting: Atomic leaderboard updates</h4><p>So far, we have seen how Redis Sorted Sets make leaderboard operations efficient. However, there is a subtle problem.</p><p>When finding the nearby players, we first retrieve the players’ rank and then fetch the nearby players.</p><p>But imagine a scenario when before executing the second command, some players’s score gets updated which changes the rank of current player. So, when the second command executes, it returns a different result.</p><p>This happens because each Redis command is atomic individually, but the two commands together are not an atomic operation. Another client can modify the leaderboard between them.</p><p>Redis supports Lua scripting, which lets us execute multiple Redis commands as a single atomic operation. While a script is running, Redis does not interleave commands from other clients.</p><pre>— KEYS[1]: Leaderboard key<br>— ARGV[1]: Player ID<br>local leaderboard = KEYS[1]<br>local player = ARGV[1]<br>local neighbors = 3<br><br>- Find the player&#39;s zero-based rank (highest score first)<br>local rank = redis.call(&#39;ZREVRANK&#39;, leaderboard, player)<br><br>- Return nil if the player is not on the leaderboard<br>if not rank then<br> return nil<br>end<br><br>- Calculate the range around the player<br>local start_rank = math.max(0, rank - neighbors)<br>local end_rank = rank + neighbors<br><br>- Fetch nearby players and their scores<br>return redis.call(<br> &#39;ZRANGE&#39;,<br> leaderboard,<br> start_rank,<br> end_rank,<br> &#39;REV&#39;,<br> &#39;WITHSCORES&#39;<br>)</pre><p>By combining the commands in the above lua script, we ensure that the player’s rank and nearby players are fetched atomically. The same approach could be used when multiple commands are to be executed as a single atomic operation.</p><h4>Conclusion</h4><p>Redis is more than a key-value store. Its data structures let us model common application requirements which make the implemention both simple, efficient and improves the performance of the application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d369bafcb17" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Database Isolation Levels]]></title>
            <link>https://abhilodha.medium.com/understanding-database-isolation-levels-8c24f641b171?source=rss-6b78bc6a2fe0------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c24f641b171</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[isolation-level]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[Abhishek]]></dc:creator>
            <pubDate>Mon, 28 Sep 2026 04:58:22 GMT</pubDate>
            <atom:updated>2026-09-28T04:58:22.161Z</atom:updated>
            <content:encoded><![CDATA[<h4>From Read Committed to Serializable</h4><p>Imagine you’re trying to book <strong>Room A from 10:00 AM to 11:00 AM</strong> for an important meeting.</p><p>At almost the same time, another colleague is also trying to book <strong>Room A for the same time slot or overlapping time slot</strong>.</p><p>Both of you open the booking system, check the room’s availability, and see:</p><p><em>Room A is available from 10:00 AM to 11:00 AM.</em></p><p>So you both click <strong>Book</strong>.</p><p>Now Room A has <strong>two overlapping bookings</strong>.</p><p>The interesting part is that neither transaction necessarily did anything wrong on its own. Each transaction checked the database, found the room available, and created a booking.</p><p>The problem occured because the two transactions executed concurrently and produced this conflict. This is one of the fundamental problems databases have to solve when multiple transactions execute concurrently.</p><h4>Transactions</h4><p>Mechanism for grouping multiple operations on multiple objects into one unit of execution.</p><p>Transaction could be broadly described using:</p><ul><li>ACID — Atomicity, Consistency, <strong>Isolation</strong>, Durability</li><li>BASE — Basically Available, Soft State, Eventually Consistent</li></ul><p>Since our topic of this blog is Isolation, we will first define ACID and then move on to Isolation.</p><h3>Atomicity</h3><p>Any transaction should either get executed entirely or not at all (All or Nothing). It is the ability to abort a transaction on error and have all writes from that transaction discarded.</p><p>Transactions ensure Atomicity by commiting the transaction after all operations are done or rolling back the changes applied.</p><h3>Consistency</h3><p>This is the application’s responsibility to define transactions correctly so that they preserve consistency.</p><p>Ex. In accouting systems, credit &amp; debit must be balanced. This is dependent on how the application defines the transactions.</p><p>Databases achieve consistency by relying on Atomicity &amp; Isolation.</p><h3>Isolation</h3><p>Concurrently executing transactions are isolated from each other and should not interfere.</p><h3>Durability</h3><p>Durability ensures that once the transaction is committed, the data is never lost or forgotten even if there is hardware failure.</p><p>There are multiple isolation levels supported by databases, and the application owner is supposed to select the one which meets their requirements.</p><ol><li>Read Committed</li><li>Snapshot Isolation</li><li>Serializable Isolation</li></ol><h3>Read Committed</h3><p>This isolation level prevents from <strong><em>dirty reads</em></strong> and <strong><em>dirty writes.</em></strong></p><p><strong>What is Dirty Read?</strong></p><ul><li>If a transaction updating multiple objects is partially read by another transaction — it will only see some updates but not all. This is called inconsistent read problem.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4DK9GZ_dmt65prxyGxGw5g.png" /><figcaption>Inconsistent Read — Partial data visible to another transaction</figcaption></figure><ul><li>If a transaction writes to multiple objects and then abort, a concurrent transaction reads the partially written data — and might never see it roll back.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z5KqzII31uLemug9bHaaQA.png" /><figcaption>Dirty Read with Rollback</figcaption></figure><blockquote>If a transaction writes to an object that has not been committed or rollback yet, another concurrent transaction reading the same object is called <strong>dirty read</strong>.</blockquote><p><strong>What is Dirty Write?</strong></p><p>When two concurrent transactions update the same object, and one transaction overwrites the value written by another transaction <strong><em>before it commits</em></strong>, it results in a <em>dirty write</em>.</p><p>This is different from <strong><em>lost updates</em></strong> which means the other transaction overwrites the value written by first transaction after it’s committed. We’ll discuss this later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XT4-dQZUyurQdUcInpZ20Q.png" /><figcaption>Dirty Write</figcaption></figure><p><em>Dirty write are prevented by using row level locks. Locks are expensive for preventing dirty reads, so databases maintain both old committed value &amp; new value being set by the transaction holding the lock. Any other transaction reading the value is provided with the old committed value.</em></p><p>— — —</p><h3>Snapshot Isolation</h3><p>a.k.a MVCC (Multi Version Concurrency Control)</p><p>Snapshot Isolation helps prevent non-repeatable reads or read skews.</p><h4>What is Non-repeatable read?</h4><p>A single transaction reading different rows at different times and getting inconsistent version of data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AbgOLePHdcPtMOCaY3xCZw.png" /><figcaption>Non-repeatable read / Read Skew</figcaption></figure><h4>How does MVCC prevent this?</h4><p>Instead of overwriting data immediately, db keeps multiple versions of the rows. The database keeps track of which transaction created each version.</p><ol><li>Similar to Read Committed, it also uses locks to prevent dirty writes. And follow the principle:<br><em>Readers never block Writers, Writers never block Readers.</em></li><li>All transactions are given an incremantal id and every row stores which transaction created/deleted id.<br><em>a. </em>When a new transaction begins, db makes a list of all ongoing transactions (not yet committed or aborted).<br><em>b. </em>Any writes made by those transactions are ignored.<br><em>c.</em> Any writes by transactions with later ID are ignored.<br><em>d.</em> All other writes are visible to the query.</li></ol><p>But two transactions concurrently writing is still ignored and not addressed. This causes the lost update or write skew problem.</p><h4>Lost Updates</h4><p>A lost update occurs when 2 transactions concurrently perform a read-modify-update cycle, and one transaction would overwrite the changes made by the other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-dtXuiWhXoE53lopQVk7pg.png" /><figcaption>Lost update — 2 concurrent transactions performing read-modify-update operation leading 1 transaction to overwrite the changes.</figcaption></figure><p>This is different from a <strong>dirty write</strong>, where one transaction overwrites data that another transaction has written but not yet committed.</p><p>Lost updates can be addressed using several approaches:</p><ol><li><strong>Atomic write operations<br></strong>Instead of performing a read -&gt; modify -&gt; update operation, perform the modification on a single atomic cycle. The database can execute this operation atomically, avoiding the need for the application to first read the value.<br>UPDATE accounts<br>SET balance = balance + 10<br>WHERE id = 1;<br>Another approach could be to execute the updates on a single thread.</li><li><strong>Explicit Locking<br></strong>Explicitly lock the object being modified when atomic read cannot be applied.</li><li><strong>Compare &amp; Set<br></strong>Allow update to only happen if the value has not changed since it was last read.<br>UPDATE accounts<br>SET balance = 110<br>WHERE id = 1 AND balance = 100;</li><li><strong>Conflict Resolution<br></strong>Locks or Compare &amp; Set work well for single up-to-date copy. But in distributed systems with multi-leader setup or leaderless replication, replicas can receive concurrent writes and a conflict resolution strategy is needed. LWW (Last Write Wins) is generally the default option.</li></ol><h4>Write Skew</h4><p>Write Skew is similar to lost update. They both arise from concurrent read -&gt; modify -&gt; update operations.</p><p><strong>Lost Update: </strong>Two transactions read and update the same object, causing one update to be overwritten.</p><p><strong>Write Skew: </strong>Two transaction read the same data but update different objects.</p><p>Suppose two engineers are on-call for a week, with a requirement that <strong>at least one engineer must always be available</strong>. The on-call schedule is maintained in a database table containing the engineer’s ID and availability status.<br>Now imagine that both engineers become unwell and try to mark themselves as <strong>unavailable at the same time</strong>.<br>Each transaction may observe that the other engineer is still available:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bVjrkMIyinLh5QB06RRquw.png" /><figcaption>Write Skew — On-call Engineer case</figcaption></figure><p>Both transactions can successfully commit because each transaction, based on the data it read, believes that <strong>at least one engineer will remain available</strong>. But after the transactions commit, the original constraint is violated.</p><blockquote>This is <strong>write skew</strong>: neither transaction overwrote the other’s update, but their independent updates together produced an invalid state.</blockquote><p>Some write-skew scenarios can be prevented using explicit locking, but not all as correctly choosing what to lock can become difficult when the constraint involves multiple rows. Similar problems can occur in:</p><ol><li><em>Meeting room booking</em> — concurrent transactions book the same time slot.</li><li><em>Multiplayer games</em> — Where different users try to move different objects to same location</li><li><em>Double spending </em>— concurrent operations independently determine sufficient balance is available and both proceed.</li></ol><h4>Phantoms</h4><ul><li><strong>Non-repeatable read</strong> → an existing row changes between two reads.</li><li><strong>Phantom read</strong> → the <strong>set of rows matching a query changes</strong> between two reads because another transaction inserted, deleted or changed rows.</li></ul><p>Consider a meeting room booking system. The rule is simple: <em>A room cannot have overlapping bookings.</em></p><p>Two concurrent transactions check for conflicting bookings and both find none. Each transaction therefore concludes that the room is available and inserts its booking. The transactions can both commit, resulting in overlapping bookings.</p><p>If either transaction executes the same query again after the other transaction commits, a row that wasn’t present during the first read now appears. This newly matching row is the <strong>phantom</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LFmWDtMq618b3oWJmxueOQ.png" /><figcaption>Phantom based anomaly</figcaption></figure><p><strong><em>So how to prevent these problems?</em></strong><br>One options is to use explicit locking. However, correctly identifying which all rows to lock can become complicated especially when the constraint involves a set of rows rather than a single row.</p><p>This is where <strong><em>Serialisable Isolation</em></strong> comes in.</p><h3>Serialisable Isolation</h3><p>Serialisable Isolation is regarded as the strongest isolation level. It gurantees that even though transactions may execute in parallel, the end result is the same as if they had executed serially one after the other. There are multiple techniques which can be used to provide serialisability.</p><ol><li><strong>Actual Serial Execution</strong><br>Simplest way is to remove any concurrency and execute only one transaction at a time in serial order <em>on a single thread</em>. But only one slow transaction is enough to stall the entire processing. This leads to poor performance during high contention.</li><li>Two Phase Locking</li><li>Optimistic Concurrency Control — Serializable Snapshot Isolation</li></ol><h4>Two Phase Locking (2PL)</h4><p>2PL is a concurrency-control protocol that ensures transactions are <strong>conflict-serializable</strong> by dividing lock management into two phases:</p><ol><li><strong>Growing Phase:</strong> When locks are acquired for the transaction</li><li><strong>Shrinking Phase:</strong> When locks are being released after transaction commits/aborts. No new locks can be acquired by the transaction in this phase.</li></ol><p>2PL uses <strong><em>shared</em></strong> and <strong><em>exclusive</em></strong> locks to control both reads and writes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WXqAHSA0GuqPfLQqr-Ow2Q.png" /><figcaption>Shared and Exclusive locks: shared locks permit multiple readers and may be upgraded to exclusive locks for writing; exclusive locks permit one writer and block other shared and exclusive locks.</figcaption></figure><blockquote><strong>2PL:</strong> readers can block writers because reads acquire locks.<br><strong>Snapshot isolation:</strong> readers generally don’t block writers because reads use a snapshot.</blockquote><p>But row locking doesn’t prevent phantoms.</p><p>In the meeting room booking example above, there are no rows to lock at the beginning and concurrent transactions could still create conflicting bookings. This is where <strong>Predicate Locking</strong> comes in.</p><p><strong>Predicate Lock<br></strong>Instead of locking only the rows returned by the query, predicate locking protects the predicate (<em>search query</em>) including the rows that could satisfy it in future.</p><p><strong>Index-range Locks or Gap Locks<br></strong>Predicate locking protects the set of rows that satisfy a condition. However, implementing and checking arbitrary predicates can be expensive, especially under high concurrency.<br>A database can instead use <strong>index-range or gap locking</strong>. Rather than locking the exact logical predicate, it locks a range in an index that covers the predicate.</p><p>For example, suppose meeting bookings are indexed by room_id. When a transaction checks whether a room has a conflicting booking, the database can protect the relevant index range for that room, including the gap where a new booking could be inserted.<br>This is an <em>approximation based locking</em>. The protected range can be broader than the actual predicate. Example — a transaction checking for a booking from 10:00–11:00 could temporarily block another transaction booking the same room from 14:00–15:00, even though the two bookings do not actually overlap.</p><h4>Optimistic Concurrency Control (OCC)</h4><p>2PL is pessimistic concurrency control implementation. It assumes that a conflict might occur, so a transaction waits for the required locks before proceeding. This works well under high contention.</p><p>However, not every application has frequent conflicts. In many applications, most transactions read or modify different records, so acquiring locks upfront can add unnecessary delay and reduce concurrency. Optimistic concurrency control takes the opposite approach: it lets transactions run without blocking each other, then validates for conflicts before committing. If a conflict is found, the transaction is aborted and retried. This approach works well under low contention.</p><p>Serializable Snapshot Isolation (SSI) is an Optimistic Concurrency Control techniquebuilt on top of snapshot isolation. Every transaction reads from a consistent snapshot of the database. SSI then additionally tracks read-write dependencies between concurrent transactions. If those dependencies could form a cycle that makes the final result non-serializable, SSI aborts one of the transactions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WOfNAef8xjCSd4uT0i90ZA.png" /><figcaption>SSI</figcaption></figure><blockquote><strong>Snapshot isolation</strong> gives each transaction a consistent view of the database.<br><strong>SSI</strong> combines the snapshot-based execution model with conflict tracking, so it can prevent serialization anomalies such as write skew.</blockquote><h3>Conclusion</h3><p>We discussed various problems caused by concurrent transactions. We started with Dirty Reads, Dirty Writes, Lost Updates, Write Skews, Phantoms and discussed how different isolation levels and different concurreny controls address these.</p><p><strong>Isolation Levels:</strong></p><ul><li><strong>Read Committed</strong> — Prevents Dirty Reads and Dirty Writes.</li><li><strong>Snapshot Isolation — </strong>Prevents lost updates</li><li><strong>Serializable Isolation</strong> — Prevents Write skews and Phantoms.</li></ul><p><strong>Concurrency control techniques:</strong></p><ul><li><strong>Row Locks</strong> — Protect existing rows from conflicting concurrent operations.</li><li><strong>Shared and Exclusive Locks</strong> — Control concurrent reads and writes; shared locks allow multiple readers, while exclusive locks prevent other conflicting access.</li><li><strong>Two-Phase Locking (2PL)</strong> — Uses locks during a growing and shrinking phase to ensure conflict-serializable execution.</li><li><strong>Predicate and Range Locks</strong> — Extend locking beyond existing rows to protect ranges or predicates, helping prevent phantom inserts.</li><li><strong>Snapshot Isolation</strong> — Allows transactions to read from consistent snapshots, generally avoiding the reader-writer blocking associated with traditional locking.</li><li><strong>Serializable Snapshot Isolation (SSI)</strong> — Builds on snapshot isolation by detecting dangerous transaction dependencies and aborting transactions when necessary to preserve serializability.</li></ul><p>Ultimately, choosing an isolation strategy is a trade-off between <strong><em>blocking, concurrency, and retries</em></strong>. Understanding the anomalies you need to prevent is therefore more useful than simply choosing an isolation level by name.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c24f641b171" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Model Context Protocol (MCP) Explained: Tools, Transports, and Real-World Usage]]></title>
            <link>https://abhilodha.medium.com/model-context-protocol-mcp-explained-tools-transports-and-real-world-usage-f203f5d3a7bf?source=rss-6b78bc6a2fe0------2</link>
            <guid isPermaLink="false">https://medium.com/p/f203f5d3a7bf</guid>
            <category><![CDATA[tools]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[mcp-protocol]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <dc:creator><![CDATA[Abhishek]]></dc:creator>
            <pubDate>Fri, 17 Apr 2026 05:01:03 GMT</pubDate>
            <atom:updated>2026-05-13T13:53:32.854Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Build reusable, scalable AI agents using MCP with tools, streaming, and standardised integrations</em></p><h3>What is MCP?</h3><p>Model Context Protocol (MCP) is a open standard designed by Anthropic for AI agents to augment the context with external tools, data sources in a consistent way.</p><p>Think of it like a USB-C port which allows any AI agent to connect to it and access the data without the requirement for the agent to have the implementation built in.</p><blockquote>AI Agent = device<br>MCP = port<br>MCP Server = connected accessory</blockquote><h3>Why MCP?</h3><p>Large Language Models (LLMs) are trained on large amount of mostly public data. But that knowledge is static and is limited by a cut-off date. Because of this reasone, a model alone cannot answer all your questions, specially the one’s which require real-time data, example:</p><ul><li>real time information like news, stock prices, etc</li><li>private data</li><li>business specific rules</li></ul><p>To build a usable AI Agent, you need access to the most up-to-date information. To augment the model with the such information - you need to provide your agent with tools which can fetch the information and feed it to the agent.</p><p>Without MCP, every agent would need to implement these tools which creates a few problems:</p><ul><li>duplicated implementation across agents,</li><li>inconsistent behavior between agents,</li><li>higher maintainence over-head,</li><li>redeployment needed when the implementation changes</li></ul><p>MCP solves this problem by standardizing the tools. Instead of every agent having their own implementation of the tools, you can build a MCP server and allow any agent requiring those tools connect to this server via a MCP client. This gives the following benefits:</p><ul><li><strong>Reuse:</strong> Build the tool once in MCP server and let it serve multiple the agents.</li><li><strong>Maintainability</strong>: Any changes to the implementation only applies to the MCP server. Any agent using the tools via MCP require no changes.</li><li><strong>Consistency</strong>: All the agents using the tools via MCP get the same implementation and output from the tool.</li><li><strong>Discoverability</strong>: New tools could be added to the MCP server and any agent could use them via MCP.</li></ul><p><strong><em>Simple Example</em></strong></p><p>Suppose you are building an agent which needs to connect to Github and read the content from repositories. You build a tool which authenticates with Github and calls the read api’s to fetch the content.</p><p>Another team member is building another agent which needs access to <em>Issues</em> in some repos. They will also need to build a tool which connects to Github (maintain apikey/secrets, establish connection) and retrieve the data.</p><p>In both these cases, the agent needs to handle authentication, secret management, establish connection and perform operation.</p><p>As you can see, the complexity start to grow as more agents are built or new functionality is added to existing agents.</p><p>With MCP, the integration with Github can be done once in the MCP server and reused across any agent.</p><h3>Building MCP Server</h3><p>If you are using <a href="https://gofastmcp.com/getting-started/welcome">FastMCP</a> python package, MCP server implementation is pretty straightforward.</p><pre>from fastmcp import FastMCP<br><br>mcp = FastMCP(&quot;AnyName&quot;)<br><br>@mcp.tool<br>def add(a: int, b: int) -&gt; int:<br>    &quot;&quot;&quot;Add two integer numbers. &quot;&quot;&quot;<br>    return a + b<br><br>if __name__==&quot;__main__&quot;:<br>   mcp.run()</pre><p>And your MCP server is ready.</p><h3>Components of MCP server</h3><h4>Tools</h4><p>Tools allow the LLM to interact with external system and retrieve data which was not present in the models training data.</p><h4>Resources</h4><p>Resources allow your agentic application to access the data or files. Example: You can connect Google Drive to ChatGPT/Claude to read files and answer questions based on the documents.</p><h4>Prompts</h4><p>Prompts allow users to use pre-built templated instructions and pass the formatted prompt to the LLM to get better results.</p><p>Example: You can ask an LLM to perform the below operation —</p><p><em>“rewrite the content in markdown format”</em></p><p>This will give you decent results. But if you define a prompt in your MCP server like below:</p><pre>@mcp.prompt(name=&quot;format&quot;, description=&quot;Rewrites content in Markdown format&quot;)<br>def format_document(content: str) -&gt; str:<br>    prompt = f&quot;&quot;&quot;<br>    Rewrite the below content in markdown format:<br>    {{content}}\n<br>    Add headers, bullet points, etc. Ensure the content is not fabricated and do not add information beyond what&#39;s provided..<br>    &quot;&quot;&quot;<br>    return prompt<br></pre><p>This will always give you results in a similar structure.</p><h4>Context</h4><p>Context allows our application to access MCP capabilities like logging, progress updates, LLM sampling, user elicitation, etc. <br><strong>Logging</strong> helps in sending messages back to the client while the tool is still running.<br><strong>Progress reporting</strong> helps in sending progress updates back to the client.<br><strong>User elicitation</strong> allows requesting input from the user during tool execution.</p><pre>@mcp.tool<br>async def some_long_running_tool(input: str, ctx: Context) -&gt; str:<br>    &quot;&quot;&quot;Performs some long running operations&quot;&quot;&quot;<br>    await ctx.info(&quot;Started Processing the request&quot;)<br>    await ctx.report_progress(progress=10, total=100) # 10% Complete<br>    sleep(5)<br>    await ctx.report_progress(progress=90, total=100)<br>    return &quot;Some Result&quot;</pre><p>This is very useful when tool execution takes long but you want to stream progress update to the client.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WZHa5Z6SYM6GlwOPEINCJg.png" /></figure><h3>MCP Transport</h3><h4>STDIO</h4><p>Standard input/output. Stdio transport uses subprocess pipes to communicate with MCP server. When stdio is used, MCP client launches and manages the lifecycle of MCP server as a subprocess.</p><p>In this setup, both MCP server and client are running on the same machine. The client sends messages to the server’s stdin and the server responds via the stdout.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SbypOlF50XQ9jxNwJ27pcg.png" /></figure><p>This allows for the bidirectional communication between the client and the server.</p><p>But this requires your client to manage the server process as well — which raises some concerns like managing the server lifecycle, restarting the client on modifications to the server, secret management, etc.</p><h4>Streamable HTTP</h4><p>The streamable HTTP transport lets MCP servers run as a remote web service and allows clients to connect over HTTP.</p><p>HTTP allows only unidirectional communication (client requests, server responds; no server-initiated messages). To overcome this, streamable HTTP uses a workaround.</p><p>Streamable HTTP is HTTP + SSE (Server Sent Events).</p><p><strong>HTTP</strong> — used by the client to send requests</p><p><strong>SSE</strong> — used by the server to send streams of data</p><p>Server decides the response:</p><ul><li>If the response is simple → return standard JSON</li><li>If streaming is needed → return an SSE stream <br>Content-Type: text/event-stream<br>Instead of closing the connection, it keeps it open and sends events.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YY2TZZTpo5MwTRSzky_qKA.png" /><figcaption>MCP Client Server interaction over HTTP</figcaption></figure><p>Streamable HTTP include 2 main configuration properties:</p><ul><li><strong>stateless_http</strong> (default: false)<br>When set to true, the server operates in <strong>stateless mode<br>Disables long-lived connections</strong> (no SSE streaming)<br>All interactions follow standard request-response HTTP</li><li><strong>json_response (</strong>default: false<strong>)<br></strong>When set to true , the server always return json response.</li></ul><p>Streaming is only possible when both of these are set to false .</p><p><strong>Example:</strong></p><ul><li><em>Client requesting for list of tools</em> (tools/list)</li></ul><pre>{<br>  &quot;jsonrpc&quot;: &quot;2.0&quot;,<br>  &quot;id&quot;: 1,<br>  &quot;method&quot;: &quot;tools/list&quot;,<br>  &quot;params&quot;: {}<br>}</pre><ul><li><em>Server respose with list of tools</em></li></ul><pre>{<br>  &quot;jsonrpc&quot;: &quot;2.0&quot;,<br>  &quot;id&quot;: 1,<br>  &quot;result&quot;: {<br>    &quot;tools&quot;: [<br>      {<br>        &quot;name&quot;: &quot;github_repository_tree_get&quot;,<br>        &quot;description&quot;: &quot;List tree entries for a path at a ref for a Github repository.&quot;,<br>        &quot;inputSchema&quot;: {<br>          &quot;type&quot;: &quot;object&quot;,<br>          &quot;properties&quot;: {<br>            &quot;repo_name&quot;: { &quot;type&quot;: &quot;string&quot; },<br>            &quot;commit_id&quot;: { &quot;type&quot;: &quot;string&quot; },<br>            &quot;recursive&quot;: { &quot;type&quot;: &quot;boolean&quot;, &quot;default&quot;: false }<br>          },<br>          &quot;required&quot;: [&quot;repo_name&quot;, &quot;commit_id&quot;]<br>        }<br>      },<br>      {<br>        &quot;name&quot;: &quot;github_issues_list&quot;,<br>        &quot;description&quot;: &quot;List issues for a repository with optional filters.&quot;,<br>        &quot;inputSchema&quot;: {<br>          &quot;type&quot;: &quot;object&quot;,<br>          &quot;properties&quot;: {<br>            &quot;repo_name&quot;: { &quot;type&quot;: &quot;string&quot; },<br>            &quot;state&quot;: { &quot;type&quot;: &quot;string&quot;, &quot;enum&quot;: [&quot;open&quot;, &quot;closed&quot;, &quot;all&quot;], &quot;default&quot;: &quot;open&quot; },<br>            &quot;labels&quot;: { &quot;type&quot;: &quot;string&quot;, &quot;description&quot;: &quot;Comma-separated label names&quot; },<br>            &quot;per_page&quot;: { &quot;type&quot;: &quot;integer&quot;, &quot;default&quot;: 30, &quot;maximum&quot;: 100 }<br>          },<br>          &quot;required&quot;: [&quot;repo_name&quot;]<br>        }<br>      },<br>      {<br>        &quot;name&quot;: &quot;github_issue_get&quot;,<br>        &quot;description&quot;: &quot;Fetch a single issue by number.&quot;,<br>        &quot;inputSchema&quot;: {<br>          &quot;type&quot;: &quot;object&quot;,<br>          &quot;properties&quot;: {<br>            &quot;repo_name&quot;: { &quot;type&quot;: &quot;string&quot; },<br>            &quot;issue_number&quot;: { &quot;type&quot;: &quot;string&quot;}<br>          },<br>          &quot;required&quot;: [&quot;repo_name&quot;, &quot;issue_number&quot;]<br>        }<br>      }<br>    ]<br>  }<br>}</pre><ul><li><em>Client calling a particular tool</em> (tools/call)</li></ul><pre>{<br>  &quot;jsonrpc&quot;: &quot;2.0&quot;,<br>  &quot;id&quot;: 20,<br>  &quot;method&quot;: &quot;tools/call&quot;,<br>  &quot;params&quot;: {<br>    &quot;name&quot;: &quot;github_list_issues&quot;,<br>    &quot;arguments&quot;: {<br>      &quot;repo&quot;: &quot;my_repo_name&quot;,<br>      &quot;state&quot;: &quot;open&quot;,<br>      &quot;labels&quot;: &quot;bug,priority-high&quot;<br>    }<br>  }<br>}</pre><h3>Summing it up</h3><p>MCP allows the agent to focus on reasoning while decoupling them from the tool integrations.</p><p>Instead of every agent implementing the same tools, MCP provide a clean layer where:</p><ul><li>MCP handles the external integrations</li><li>Agent connects via a standard protocol.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f203f5d3a7bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Replication in Distributed Systems: Beyond Just Copying Data]]></title>
            <link>https://abhilodha.medium.com/replication-in-distributed-systems-beyond-just-copying-data-90555ff5bc6f?source=rss-6b78bc6a2fe0------2</link>
            <guid isPermaLink="false">https://medium.com/p/90555ff5bc6f</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[replication]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <dc:creator><![CDATA[Abhishek]]></dc:creator>
            <pubDate>Fri, 10 Apr 2026 18:37:14 GMT</pubDate>
            <atom:updated>2026-04-10T18:39:23.715Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Understanding consistency, failures, and the tradeoffs that define distributed databases</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h-5RtkjwXuF9zKkwypYIKA.png" /></figure><p>Replication is the process of maintaining multiple copies of data across different machines for:</p><ul><li><strong>High availability or fault-tolerance</strong> — In case of node failure or network issues, the system is still available to serve user requests.</li><li><strong>Latency</strong> — Keeping data closer to user’s geographical location.</li><li><strong>Scalability</strong> — Allowing reads to happen on read replicas, the application can handle high volumes than a single node can.</li></ul><p>While the idea sounds simple, replication introduces complex trade-offs around consistency, latency, and fault tolerance.</p><p>At a high level, replication systems must answer three key questions:</p><ul><li>How are writes propagated?</li><li>What happens when nodes fail?</li><li>How do we ensure consistency across replicas?</li></ul><p>Let’s first understand the different ways to perform replication and what problems does each approach has.</p><h3>Single Leader Replication</h3><p>a.k.a <em>master-slave</em>, <em>active-passive</em></p><ol><li><strong>Master node</strong> (leader/primary) — All write requests from the application must be sent to the master node.</li><li><strong>Slave node</strong> (follower/standby) — Whenever the master node writes data to its local storage, it sends the data to all its followers as part of replication log or change stream. Each follower must update its local storage based on those.</li></ol><p>The system can be configured to apply the master changes either synchronously or asynchronously.</p><p><strong>Synchronous replication</strong></p><p>The master waits until the follower confirms that it has received the write before reporting success to the client. In this case, the follower is guaranteed to copy of data consistent with the master.</p><p>However, the disadvantage is that the master cannot proceed until the follower responds. There could be multiple reasons for that: the follower node crashed, the network is unavailable.</p><p><strong>Asynchronous replication</strong></p><p>The master writes the data to its local storage and responds back to the client. The logs are then propagated to the follower nodes in the background. So, the master can process writes even if all the followers are lagging behind.</p><p>The follower might not have the latest copy of the data and if the master fails — the system might lose the data.</p><blockquote>Synchronous → <strong>strong consistency, lower availability<br></strong>Asynchronous → <strong>high availability, risk of data loss</strong></blockquote><h4>Failure Handling in Replicated Systems</h4><ul><li><strong>Follower failures</strong><br>Each follower keeps a log of data changes it has received from the leader. If the node fails, it knows the exact position in the leader’s replication log (<em>binlog coordinates</em>).</li><li><strong>Leader failures</strong><br>In case of leader failures, one of the follower node has to be promoted to be the new leader. The best candidate would be the follower with the most up-to-date change from the previous leader.<br>If <em>asynchronous replication</em> was setup, the follower might not have all the writes from the previous leader — in which case the client’s durability expectation might be violated.</li></ul><h4><strong>How Replication is Implemented: Log-Based Approaches</strong></h4><ul><li><strong>Statement based replication</strong><br>The leader logs every write statement like insert, update or delete in relational db and the same is forwarded to the followers.<br>Special handling is required for statements with auto-incrementing columns or non-determinstic functions (NOW()).</li><li><strong>Write-ahead log (WAL)<br></strong>The log is a append-only sequence of bytes containing all the writes. The main disadvantage of WAL is that it contains very low-level data i.e which bytes were changed in which disk block. This ties it to the storage engine of the database. So, the follower and the leader must be using the same version of the storage engine.</li><li><strong>Logical log replication</strong><br>This contains the sequence of records describing the writes at row level.<br>This decouples the replication logs from the storage engine implementation.</li></ul><h4>Replication Lag</h4><p>In asynchronous systems, followers may lag behind the leader. This can result in stale reads, where users see outdated data.</p><p>This introduces consistency challenges, especially for user-facing operations. To mitigate these issues, systems provide <strong>client-centric consistency guarantees</strong>.</p><ol><li><strong>Read-After-Write consistency</strong></li></ol><p>Read-after-write consistency ensures that once a user performs a write, subsequent reads reflect that update.</p><p>One simple way to achieve this is by routing reads to the leader, which always has the latest data. However, this approach increases latency and reduces the benefits of read scaling.</p><p>More scalable approaches include:<br>- <em>Sticky sessions</em>: Set flag read_preference = leader <br>- <em>Client maintaining a logical timestamp: </em>Sending headers X-Read-Consistency: strong</p><p>This becomes more challenging when users access the system from multiple devices, as maintaining session affinity or tracking state across devices is harder.</p><p><strong>2. Monotonic reads</strong></p><p>When there is lag between replicas, it is possible that the user might observe data moving backwards in time.</p><p>Without this guarantee, a user might:</p><ol><li>Read from a less-lagging replica</li><li>Then read from a more-lagging replica and see older data</li></ol><p>This can be solved by ensuring each read request from a user reaches the same replica (<em>choosing the replica based on user ID hash</em>).</p><p><strong>3. Consistent Prefix Reads</strong></p><p>This ensures that a user never sees the data <strong><em>out of order</em></strong>. If writes happen in a specific sequence, reads should reflect the same sequence.</p><p>Consider two writes happening in order:</p><ol><li>W1: User posts a comment</li><li>W2: User replies to that comment</li></ol><p>The user should never see W2 before the W1 comment.</p><p>This is a particular <strong>problem</strong> with <strong>partitioned</strong> <strong>databases</strong> — where some partitions are replicated slower than others. <em>This requires a distributed transaction with </em><strong><em>snapshot isolation</em></strong><em> guarantees (details coming up in follow-up article).</em></p><h3>Multi Leader Replication</h3><p>a.k.a <em>master-master</em>, <em>active-active</em></p><p>A setup where more than one node accepts writes. Each leader node also acts as a follower to other leaders.</p><p>Use cases for this include:</p><ul><li>multi-data center operations</li><li>clients with offline operations (where edge node also acts as leader while offline) e.g calendar apps.</li><li>collaborative editing tools like Google doc.</li></ul><p>This type of replication is not very popular because of the challenges including write conflicts, ordering guarantees, and the complexity of conflict resolution strategies (last-write-wins, custom merge logic, CRDTs). Hence it should be avoided when single-leader replication suffices.</p><h3>Leaderless Replication</h3><p>In leaderless replication — there are no designated leaders. The client sends read and write request to several nodes in parallel.</p><p><strong>How does this help?</strong></p><p>Consider a 3-node cluster. A client sends a write to all three nodes, but one node happens to be down. The remaining two nodes accept the write successfully — and since a majority acknowledged it, the write is considered successful.</p><p>Later, the failed node recovers. It missed the write, so it still holds stale data. Now when the client reads, it contacts multiple nodes and may receive different responses — fresh data from two nodes, stale data from the recovered one. To resolve this, each write carries a version number, and the client simply picks the response with the highest version.</p><h4>Quorum</h4><p>Suppose there are n replica. Every write must be confirmed by w nodes to be successful and we must query at least r nodes for each read.</p><p>If we can ensure w + r &gt; n, then we can expect an up-to-date value from the reads [<a href="https://en.wikipedia.org/wiki/Pigeonhole_principle"><em>Pigeonhole Principle</em></a>].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0c-8h8pqoyL_FZTZyqhwBQ.png" /></figure><p><strong>Limitations of quorum</strong></p><ul><li><em>Sloppy quorum</em> — discussed below</li><li>If read and write happen concurrently. The write might be successful on a few nodes only, so different reads can return different data.</li><li>If some nodes crashe mid-write and quorum is not reached, the other nodes that did receive the write hold a value that the crashed nodes don’t — leaving the cluster inconsistent until <em>read-repair</em> or <em>anti-entropy</em> corrects it.</li></ul><h4>Sloppy Quorum</h4><p>Consider some nodes in the cluster become unreachable because of a network partition and quorum cannot be established for any write or read requests. There are 2 options:</p><ol><li>Reject writes or reads &amp; return error to client until the quorum is restored.</li><li>Accept the writes on some other nodes (outside the n designated replicas) to reach the quorum of w nodes. And forward the data to the original nodes once the nodes are reachable again(<a href="https://www.geeksforgeeks.org/system-design/what-is-sloppy-quorum-and-hinted-handoff/"><em>hinted handoff</em></a>)</li></ol><p>The second approach is called sloppy quorum. This is very useful for improving the write availability of the system but might temporarily serve inconsistent data until the hinted handoff completes and the system becomes <em>eventually consistent</em>.</p><h4>Handling stale data</h4><ul><li><strong>Read-Repair: </strong>While reading the data from multiple replicas, the client can detect stale data by comparing the version number. If any replica returns an older version, the client can write the latest data to the stale replicas. This works well for frequently read data. Any infrequently read data may stay stale for a long time.</li><li><strong>Anti-Entropy:</strong> Some systems run a background job which checks the data between replicas and replaces the stale data with newer data. This is an asyncronous operation and might introduce delays.</li></ul><h4>Handling Concurrent Writes</h4><p>In leaderless replication there is no central node to serialise the writes, so if the same key is modified by multiple clients concurrently, their writes might reach different replicas in different order which might leads to system being in inconsistent state.</p><p>Resolving such conflicting values becomes necessary for the eventual consistency of the system.</p><p>There are a few approaches to solve for this:</p><p><strong>Last Write Wins<br></strong>Attach a timestamp to each write and the nodes keep the one with the latest timestamp while discarding the rest. This sounds simple and easy to implement but clock synchronisation acorss nodes in distributed system is never perfect — a writes that happened later in real time might carry an earlier timestamp and get discarded leading to data loss.</p><p><strong>Version Vectors<br></strong>A version number is maintained across each key. The server increments the version number every time a key is written.</p><ul><li>When the client reads a key, it is provided with the latest version number along with all the values which are not overwritten.</li><li>When the client writes the key, it must include version number from prior read along with all the merged values.</li><li>When the server get the write, it can overwrite all the values with the incoming version number or below, but it must keep all the values with a higher version number.</li></ul><p><strong>Example: </strong>A shopping cart with multiple clients (<em>mobile/web</em>)</p><p><em>Step 1:</em> Client A reads server state version:0, values: [] <br><em>Step 2:</em> Client B reads server state version:0, values: []<br><em>Step 3:</em> Client A write version:0, values: [milk] , Server state: version:1, values:[milk]<br><em>Step 4:</em> Client B writes version:0 values: [butter] , Server state: version: 2, values:[milk, butter] <br><em>Step 5:</em> Client A reads again and gets: version: 2, values: [milk, butter] <br><em>Step 6:</em> Client A removes butter and writes again: version: 2, values: [milk] Server know Client A has all information till version 2 and must have discarded <em>butter</em> — so it overwrites the values. version:3, values: [milk]</p><p>The version number in the example above is maintained by a single replica. When multiple replicas are involved, each replica maintains its own version number for each key and that is called a <strong><em>version vector</em></strong>.</p><blockquote>Network partitions are unavoidable in distributed systems — the real choice is between <strong><em>consistency</em></strong> and <strong><em>availability</em></strong> when one occurs.</blockquote><p>Leaderless replication provides high availability — during a network partition it can still accept the writes but with eventual consistency. Whereas single-leader or multi-leader replication provides <strong><em>strong consistency</em></strong> but might not accept writes during failures to shield against inconsistent data.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90555ff5bc6f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Family Finance Analyst AI Agent]]></title>
            <link>https://abhilodha.medium.com/building-a-family-finance-analyst-ai-agent-a8e73af90168?source=rss-6b78bc6a2fe0------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8e73af90168</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Abhishek]]></dc:creator>
            <pubDate>Mon, 23 Feb 2026 16:01:01 GMT</pubDate>
            <atom:updated>2026-02-23T16:01:01.678Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mZXwz-8WaizhhL_u" /><figcaption>Photo by <a href="https://unsplash.com/@fl__q?utm_source=medium&amp;utm_medium=referral">Taiki Ishikawa</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I wanted an AI agent that could analyse a family’s monthly expenses .I started with a prompt.</p><p>No framework. No execution structure. No state model.</p><h3>Phase 1: The Prompt-Based Agent</h3><p><strong>Input</strong>: CSV file with transaction details</p><p><strong>Output</strong>:</p><ul><li>Categorized spending</li><li>Abnormality detection</li><li>Suggestions to reduce cost</li><li>And, a financial summary for the month.</li></ul><p>So, I built something like below:</p><pre>User -&gt; LLM (Analyse Request) -&gt; Tool (Catergorize Expenses) -&gt; LLM (Interpret) -&gt; Tool (Detect Anomalies) -&gt; LLM (Generate insights) -&gt; Response</pre><p>It worked for sample test data with a few transactions.</p><p>But when I started feeding it monthly expense data, it broke.</p><ul><li>It re-categorized the already categorized transaction.</li><li>It got into a reasoning loop</li><li>Debugging required scanning through the logs.</li></ul><h4>The Problem</h4><p>The problem with this prompt-based-agent was the LLM had to remember the state during the execution (as the details were present in the prompt or in the previous output messages). The agent had no state with itself.</p><p>The execution order depended on model’s reasoning. That is probabilistic state management.</p><p>To make it work, I needed to define the:</p><ul><li>input schema</li><li>processing stages</li><li>deterministic execution steps</li><li>termination conditions</li></ul><h3>Agent as a State Machine</h3><p>AI Agent is not just a prompt. It is a state machine with probabilistic reasoning inside it.</p><p>We want every step in the workflow to align with current state of the agent.</p><pre>transactions: List[Transaction]<br>categorized: bool<br>anomalies_detected: bool<br>insights: Optional[str]<br>suggestions: Optional[str]<br>report: Optional[str]</pre><p>Each step should:</p><ol><li>Read the state</li><li>Modify the state</li><li>Transition to next step</li></ol><p>This transforms this agent to a controlled workflow. No guessing, no hidden states.</p><h4>What State Mutation Actually Looks Like</h4><p><strong>Initial State</strong></p><pre>{<br>  transactions: [...],<br>  categorized: False,<br>  anomalies_detected: False,<br>  insights: None,<br>  suggestions: None,<br>  report: None<br>}</pre><p><strong>After Categorization</strong></p><pre>{<br>  transactions: [... with category field added],<br>  categorized: True,<br>  anomalies_detected: False,<br>  insights: None,<br>  suggestions: None,<br>  report: None<br>}</pre><p><strong>After Anomaly Detection</strong></p><pre>{<br>  transactions: [... with category field added],<br>  categorized: True,<br>  anomalies_detected: True,<br>  insights: None,<br>  suggestions: None,<br>  report: None<br>}</pre><h3>Prompt-Based Agent vs Graph-Based Agent</h3><h4>Prompt-based agent</h4><p>The LLM decides:</p><ul><li>What to do next</li><li>whether to call a tool</li><li>whether to stop</li></ul><h4>Graph based agent</h4><p>The graph decides:</p><ul><li>What step run next</li><li>What cannot run yet</li><li>When execution stops</li></ul><p><strong>LLM decides:</strong></p><ul><li>How to execute that step</li></ul><p>Here, the graph orchestrates and the LLM reasons.</p><p>LLM = probabilistic reasoning engine</p><p>Graph = deterministic workflow.</p><blockquote>If LLM controls execution flow, you get a probabilistic workflow. If Graph controls the execution workflow, we build a deterministic orchestration with probabilistic nodes.</blockquote><p>An AI Agent should be state machine orchestrating the workflow with LLM as the reasoning engine.</p><h3>Where LangGraph Fits</h3><p>Now that we understand the agent is a state machine, the next question is: How do we enforce this structure?</p><ul><li>We can manually wire functions.</li><li>or, we can build our own orchestration layer.</li></ul><p>But then you are building the orchestration layer from scratch along with the business logic.</p><p>That’s where LangGraph comes in.</p><p>LangGraph is a framework for managing:</p><ul><li>State</li><li>Transitions</li><li>Execution flow</li><li>Memory</li><li>Termination conditions</li></ul><h4>State as First-class attribute</h4><p>In prompt-based systems, state lives in:</p><ul><li>system prompt,</li><li>conversation history</li><li>tool output</li></ul><p>In LangGraph, state is explicit. Every node in the graph:</p><ul><li>receives the state</li><li>partially modifies the state</li></ul><h4>Execution flow as a Graph</h4><p>Instead of the LLM deciding what to execute next, you define it. The graph decides:</p><ul><li>what to run next</li><li>what cannot be run yet</li><li>when the execution ends</li></ul><p>For example, for the finance agent, we add nodes and edges as:</p><pre>graph.add_node(&quot;categorize&quot;, categorize_transactions)<br>graph.add_node(&quot;detect&quot;, detect_anomalies)<br><br>graph.add_edge(&quot;categorize&quot;, &quot;detect&quot;)</pre><h4>Memory Management</h4><p>There are multiple layer of memory in agentic systems.</p><ol><li>Execution state (Current run)</li><li>Short term conversation memory</li><li>Long term historical memory</li></ol><p>LangGraph provides:</p><ul><li>Checkpointing capabilities</li><li>Explicit state persistence</li></ul><h4>Termination Condition</h4><p>In prompt-based system, the LLM decides when to stop.</p><p>In graph systems, we define an END node.</p><h3>The Core Insight</h3><p>An AI agent is not a prompt.</p><p>It is a state machine orchestrating a workflow — with an LLM acting as a reasoning engine inside controlled steps.</p><p>In order to build production ready systems, we need this segregation of:</p><ul><li>Reasoning (LLM)</li><li>Orchestration (Graph)</li><li>State (Structured Data)</li></ul><p>In the next article, we’ll implement this Finance Analyst Agent using LangGraph and build the full execution graph step by step.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8e73af90168" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot Tricky Questions]]></title>
            <link>https://abhilodha.medium.com/spring-boot-tricky-questions-654a89f50b03?source=rss-6b78bc6a2fe0------2</link>
            <guid isPermaLink="false">https://medium.com/p/654a89f50b03</guid>
            <category><![CDATA[annotations]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[confusion]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <dc:creator><![CDATA[Abhishek]]></dc:creator>
            <pubDate>Sun, 01 Feb 2026 17:29:12 GMT</pubDate>
            <atom:updated>2026-02-01T17:37:59.163Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tYuJ-7fQDAAVVt3D" /><figcaption>Photo by <a href="https://unsplash.com/@hiteshchoudhary?utm_source=medium&amp;utm_medium=referral">Hitesh Choudhary</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>This should work… why doesn’t it?</blockquote><p>If the above thought came to you while writing/debugging your Spring application, this article is for you.</p><p>In this article, we’ll walk through a set of <strong>commonly misunderstood Spring Boot questions</strong> — the kind that surface in production debugging — and understand what’s <em>actually</em> happening under the hood.</p><h4><strong>Question 1:</strong></h4><p>When a configuration class is disabled using @ConditionalOnProperty, how does this affect configuration classes imported via @Import?</p><p>Specifically, if AConfig is excluded because the condition does not match, will the imported BConfig still be processed? Will BService be created and available for injection?</p><pre>@Configuration<br>@ConditionalOnProperty(<br>    prefix = &quot;feature.a&quot;,<br>    name = &quot;enabled&quot;,<br>    havingValue = &quot;true&quot;<br>)<br>@Import(BConfig.class)<br>class AConfig {}</pre><pre>@Configuration<br>class BConfig {<br><br>    @Bean<br>    public BService bService() {<br>        return new BService();<br>    }<br>}</pre><p><strong>Answer: <br></strong>❌ Yes <br>✅ No</p><p>This is because Spring first parses the Configuration files and as it evalutes the @ConditionalOnProperty as false, it skips the Configuration file entirely. It does not process the @Import statement and does not register any beans.</p><pre>AConfig - @ConditionalOnProperrty - ❌ Skipped<br>↓<br>@Import - Never Executed<br>↓<br>BConfig - Never Reached</pre><blockquote>💡 @Import only triggers if the importing config class is active.</blockquote><h4>Question 2:</h4><p>What happens when a configuration class imported via @Import itself is annotated with @ConditionalOnProperty?</p><p>If AConfig is always loaded but BConfig is conditionally disabled, will BConfig still be processed? Will BService bean be created and injected?</p><pre>@Configuration<br>@Import(BConfig.class)<br>class AConfig {}</pre><pre>@Configuration<br>@ConditionalOnProperty(<br>    prefix = &quot;feature.b&quot;,<br>    name = &quot;enabled&quot;,<br>    havingValue = &quot;true&quot;<br>)<br>class BConfig {<br><br>    @Bean<br>    public BService bService() {<br>        return new BService();<br>    }<br>}</pre><p><strong>Answer: <br></strong>❌ Yes <br>✅ No</p><p>AConfig is always processed since it has no conditions. It imports BConfig, but Spring evaluates BConfig&#39;s @ConditionalOnProperty. When feature.b.enabled=false, BConfig is skipped entirely—including its @Bean methods. No BService bean is created, even though the import happened.</p><pre>AConfig - ✅ Processed<br>↓<br>@Import - ✅ Processed<br>↓<br>BConfig - @ConditionalOnProperty - ❌ Skipped </pre><h4>Question 3:</h4><p>Can constructor injection be done for beans which might not be present?</p><p><strong>Answer: <br></strong>✅ Yes <br>❌ No</p><p>By using Optional&lt;T&gt; this can be achieved. There are other ways as well, but we’ll take this approach.</p><pre>@Service<br>public class OrderService {<br>    private final Optional&lt;PromotionService&gt; promoService;<br><br>    public OrderService(Optional&lt;PromotionService&gt; promoService) {<br>        this.promoService = promoService;<br>    }<br><br>    public BigDecimal calculateTotal(Order order) {<br>        BigDecimal total = order.getSubtotal();<br>        promoService.ifPresent(s -&gt; total = s.applyDiscount(total));<br>        return total;<br>    }<br>}</pre><p><strong>But let’s understand why the below fails —</strong> if promo.enabled=false .</p><pre>@Service<br>public class OrderService {<br>    private final PromotionService promoService;<br><br>    public OrderService(PromotionService promoService) {<br>        this.promoService = promoService;<br>    }<br><br>    public BigDecimal calculateTotal(Order order) {<br>        BigDecimal total = order.getSubtotal();<br>        total = promoService.applyDiscount(total);<br>        return total;<br>    }<br>}</pre><pre>@Service<br>@ConditionalOnProperty(name = &quot;promo.enabled&quot;, havingValue = &quot;true&quot;)<br>public class PromotionServiceImpl implements PromotionService {<br>    @Override<br>    public BigDecimal applyDiscount(BigDecimal total) {<br>        return total.multiply(BigDecimal.valueOf(0.9)); <br>    }<br>}</pre><p>This fails because constructor injections promotes immutability using final keyword (which are assigned only once during object creation and cannot be reassigned later). If the PromotionService bean is disabled, Spring won’t find a matching bean while initialising the OrderService , so the constructor parameter would receive null — which would fail fast.</p><h4>Question 4:</h4><p>Does a transaction start when calling a @Transactional method from another method in the same class?</p><pre>@Service<br>public class OrderService {<br><br>    public void placeOrder() {<br>        saveOrder();<br>    }<br><br>    @Transactional<br>    public void saveOrder() {<br>        // Some db operation<br>    }<br>}</pre><p><strong>Answer:<br></strong>❌ Yes <br>✅ No</p><p>When you call orderService.placeOrder , it goes through a proxy (created because the bean has a Transactional advice) and not through the real orderService object.</p><pre>client -&gt; orderServiceProxy -&gt; placeOrder() -&gt; this.saveOrder() [❌ transaction]</pre><p>The orderServiceProxy:</p><ul><li>starts the transaction</li><li>calls the real method</li><li>commits / rolls back the transaction</li></ul><p>But <strong>inside the class</strong>, this.saveOrder() means: <em>Call the method directly on the target object — skip the proxy (</em><em>this means the real object). </em>When the proxy is skipped, there is no transaction applied.</p><p><strong>How to fix this?</strong></p><ol><li>Extract the saveOrder method to a separate service. This ensures the proxy is invoked.</li><li>Move the @Transactional to the placeOrder method.</li><li>Self-injection<br>When @Autowired private OrderService self; is done, Spring injects proxy instance.</li></ol><pre>@Service<br>public class OrderService {<br>    @Autowired private OrderService self;<br>    <br>    public void placeOrder() {<br>        self.saveOrder();<br>    }<br><br>    @Transactional<br>    public void saveOrder() { <br>    // Some db operation<br>    }<br>}</pre><pre>client -&gt; orderServiceProxy -&gt; placeOrder() -&gt; self.saveOrder() -&gt; orderServiceProxy.saveOrder()<br><br>This leads to transaction invocation.</pre><p>❓ Quick Quiz</p><h4>Question 5:</h4><p>What happens to @Transactional on private methods?</p><pre>@Service<br>public class PaymentService {<br><br>    @Transactional<br>    private void processPayment() { <br>    // Some db operation<br>    }<br>}</pre><p><strong>Answer: <br></strong>❌ Yes <br>✅ No</p><p>Transactional is ignored by Spring on private methods.</p><p>This does not produce an error because Java allow annotations on private methods. So this fails silently.</p><p><strong>Why private methods are ignored?</strong></p><p>Spring uses AOP proxies to implement @Transactional. Proxies only intercept public methods. Private methods are inaccessible from outside the class, hence proxy interception is not possible.</p><blockquote>💡 @Transactional → ONLY public methods</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=654a89f50b03" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Really Happens When a Request Hits Your Spring Boot Application]]></title>
            <link>https://abhilodha.medium.com/what-really-happens-when-a-request-hits-your-spring-boot-application-49f3dbfc32f4?source=rss-6b78bc6a2fe0------2</link>
            <guid isPermaLink="false">https://medium.com/p/49f3dbfc32f4</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[filters]]></category>
            <category><![CDATA[interceptors]]></category>
            <category><![CDATA[http-request]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Abhishek]]></dc:creator>
            <pubDate>Wed, 31 Dec 2025 19:07:19 GMT</pubDate>
            <atom:updated>2025-12-31T19:07:19.473Z</atom:updated>
            <content:encoded><![CDATA[<p>We know how to write controllers, services, and repositories for a Spring boot application.<br>But have you wondered <strong>what actually happens when an HTTP request enters the application</strong> and how it moves through different layers.</p><p>In this article, we’ll walk through the <strong>complete request lifecycle in a Spring Boot application</strong>, from the moment a request arrives till the response is sent back.</p><h4>Why Understanding the Request Flow Matters</h4><p>At first, Spring Boot feels simple: define a controller, call a service, maybe invoke a repository, and finally return a response.</p><p>But as applications grow, misunderstandings about request flow lead to:</p><ul><li>Auth checks scattered across different services.</li><li>Logging logic duplicated.</li><li>Incorrect use of filters &amp; interceptors.</li></ul><h3>Servlet Specification vs Spring MVC</h3><h4>What Is the Servlet Specification?</h4><p>The <em>Servlet Specification</em> is a Java standard. It defines <strong>how web servers and Java applications communicate</strong>.</p><p>It answers questions like:</p><ul><li>How is an HTTP request received?</li><li>How a response is sent back?</li><li>How are filters chained?</li></ul><p>It is provided by servlet containers such as:</p><ul><li>Tomcat</li><li>Jetty</li><li>Undertow, etc.</li></ul><blockquote>Spring Boot embeds <strong>Tomcat</strong> by default.</blockquote><h4>What Is Spring MVC?</h4><p>Spring MVC is a <strong>web framework built on top of the Servlet API</strong>.</p><p>It provides:</p><ul><li>@Controller / @RestController</li><li>Interceptors</li><li>JSON (de)serialization</li><li>Validations</li><li>Exception handling</li></ul><blockquote>Spring MVC hides low-level servlet details so you can focus on business logic.</blockquote><h4>DispatcherServlet: The Bridge Between Them</h4><p>DispatcherServlet is the bridge that connects the servlet with the Spring application. It is implemented by Spring MVC.</p><h4>Step 1: The Request Enters the Server</h4><p>When a client sends a HTTP request:</p><ul><li>It is received by <strong><em>Tomcat</em></strong> (or the configured web server)</li><li>Tomcat assigns <strong>one thread from its thread pool</strong></li><li>That thread handles the request from start to finish<br>Concurrent request are handled by Tomcat and passed to Spring for processing. Spring doesn’t create thread for each request.</li></ul><h4>Step 2: Servlet Filters and the Filter Chain</h4><p>Before Spring receives any request, it is passed through a chain of <strong><em>servlet</em></strong> <strong><em>filters</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UwnXuRhNT-r4YbY4fIJFQA.png" /></figure><p>Filters are part of servlet specification &amp; work with raw HTTP request/response.</p><p>Typical Filters:</p><ul><li>Authentication</li><li>Logging</li><li>CORS</li></ul><p><em>Each filter decides whether to forward the request to next filter or stop the request there itself.</em></p><h4>Step 3: DispatcherServlet</h4><p>Once the request clears all the filters, it reaches the DispactherServlet who is responsible for:</p><ul><li>Finding the appropriate Controller</li><li>Applying interceptors</li><li>Handling request &amp; response.</li></ul><p>It has no business logic.</p><h4>Step 4: Interceptors</h4><p>Interceptors are a part of Spring framework. They know which method inside which controller is about to be called.</p><p>There are 3 phases of an interceptor:</p><ul><li><em>preHandle</em> — executes before request reaches the controller.</li><li><em>postHandle</em> — executes after response is returned from the controller.</li><li><em>afterCompletion</em> — executes after the request is finished. This is where you can do any required cleanup.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2eEcOvs8J5WU0Z3vHijP5w.png" /></figure><h4>Step 5: Controller</h4><p>The Controller greets your HTTP request and turns HTTP requests into objects your application understands.</p><p>A controller should be the simplest layer in your application. It should contain <strong><em>no business logic</em></strong>. Its job is to <strong><em>delegate</em></strong> the request to appropriate layer. Controller should remain as thin as possible.</p><h4>Step 6: Service</h4><p>The Service layer contains the core business logic.</p><p>A service should represent <strong>what the application does</strong>, not <em>how</em> requests arrive.</p><h4>Step 7: Repository</h4><p>The Repository layer handles database access.</p><h4>How the Response Travels Back</h4><p>The response flows back through the same layers in reverse:</p><ol><li>Service returns result</li><li>Controller builds response</li><li>Interceptors run post-processing</li><li>Filters process the response</li><li>Response is sent to the client</li></ol><h4>Summary</h4><ul><li>Tomcat manages the HTTP lifecycle and filters, while Spring manages controllers, interceptors, and application logic.</li><li>Threads are handled by Servlet container.</li><li>Filters are controlled by the Servlet Container (Tomcat), Interceptors are controlled by Spring Context.</li><li><strong><em>Service, Repository</em></strong> should be unaware of HttpServletRequest.</li></ul><p>Diagrams created using <a href="https://mermaidlive.site/">https://mermaidlive.site/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49f3dbfc32f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Strategy Design Pattern: Choosing the Right Behaviour at Runtime]]></title>
            <link>https://abhilodha.medium.com/the-strategy-design-pattern-choosing-the-right-behaviour-at-runtime-03db9c05a486?source=rss-6b78bc6a2fe0------2</link>
            <guid isPermaLink="false">https://medium.com/p/03db9c05a486</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[strategy]]></category>
            <category><![CDATA[lld]]></category>
            <dc:creator><![CDATA[Abhishek]]></dc:creator>
            <pubDate>Tue, 30 Dec 2025 09:47:10 GMT</pubDate>
            <atom:updated>2025-12-30T09:47:10.207Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1E0FpIKjYe7gndnA" /><figcaption>Photo by <a href="https://unsplash.com/@wimvanteinde?utm_source=medium&amp;utm_medium=referral">Wim van &#39;t Einde</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Often there are multiple ways to implement a solution in software.</p><p>You might need to calculate prices differently, process payments using various different providers or define difficulty of a level in your game.</p><p>Instead of hardcoding all these variations, we need a way to <em>plug in different behaviours without rewriting our code</em>. That’s exactly what the Strategy Pattern helps us do.</p><h4>The Problem: One Goal, Multiple Ways</h4><p>Imagine you are building an e-commerce application where users can select items and make payments.</p><p>A user has the flexibility to pay via either:</p><ul><li>Credit Card,</li><li>Bank Account,</li><li>Paypal, Stripe, or other Wallet</li></ul><p>For the application, the goal is to accept payment, but internally each payment method might follow a different set of steps.</p><p>A common first instinct is to handle all payment methods using conditionals:</p><pre>if (paymentType.equals(&quot;CREDIT_CARD&quot;)) {<br>    // credit card logic<br>} else if (paymentType.equals(&quot;BANK_ACCOUNT&quot;)) {<br>    // bank account logic<br>} else if (paymentType.equals(&quot;PAYPAL&quot;)) {<br>    // paypal logic<br>}</pre><p>This looks just fine at first. But when new payment methods are added, this if/else block grows and becomes hard to read and harder to maintain. Every new payment method requires changes in the existing code which makes testing harder and might lead to errors.</p><p>Over time, this logic becomes tightly coupled, harder to test, and risky to modify — even for small changes.</p><h4>What is Strategy Pattern?</h4><p>The Strategy Pattern lets you choose the algorithm at runtime. It does so by allowing you to define various ways to perform an operation and encapsulating each of them in a separate class.</p><blockquote>In simple terms: you move each “way of doing something” into its own class and interchange them when needed.</blockquote><p>This allows the algorithm to vary independently from the <strong>clients</strong> that use it, enabling the system to choose or switch behaviours dynamically at runtime.</p><h4>Example: Payment Method Selection</h4><p>The checkout service of an e-commerce application allows user to process payments via different payment methods. Each payment method might have a different process but the goal is to capture the payment for the application.</p><p>We’ll refactor the payment logic using the Strategy Pattern.</p><p><strong>Step 1: Define the strategy interface</strong></p><pre>public interface PaymentStrategy {<br>    void pay(double amount);<br>}</pre><p><strong>Step 2: Implement concrete strategies</strong></p><ul><li><em>Credit Card Payment</em></li></ul><pre>public class CreditCardPayment implements PaymentStrategy {<br><br>    @Override<br>    public void pay(double amount) {<br>        System.out.println(&quot;Paid &quot; + amount + &quot; using Credit Card&quot;);<br>    }<br>}</pre><ul><li><em>Bank Account</em></li></ul><pre>public class BankAccountPayment implements PaymentStrategy {<br><br>    @Override<br>    public void pay(double amount) {<br>        System.out.println(&quot;Paid &quot; + amount + &quot; using Bank Account&quot;);<br>    }<br>}</pre><ul><li><em>Paypal</em></li></ul><pre>public class PaypalPayment implements PaymentStrategy {<br><br>    @Override<br>    public void pay(double amount) {<br>        System.out.println(&quot;Paid &quot; + amount + &quot; using Paypal&quot;);<br>    }<br>}</pre><p><strong>Step 3: Create the context</strong></p><p>The context uses a strategy to process the payment but is unaware of the actual implementation.</p><pre>public class CheckoutService {<br><br>    private PaymentStrategy paymentStrategy;<br><br>    public CheckoutService(PaymentStrategy paymentStrategy) {<br>        this.paymentStrategy = paymentStrategy;<br>    }<br><br>    public void processPayment(double amount) {<br>        paymentStrategy.pay(amount);<br>    }<br>}</pre><p><strong>Step 4: Choose the strategy at Runtime</strong></p><pre>public class Application {<br><br>    public static void main(String[] args) {<br>        PaymentStrategy strategy = new CreditCardPayment();<br>        CheckoutService checkout = new CheckoutService(strategy);<br><br>        checkout.processPayment(1500.00);<br>    }<br>}</pre><p><em>In real applications, this choice might come from user input, configuration, or dependency injection.</em></p><p><em>Very often, this responsibility is delegated to a </em><em>Factory, whose sole job is to decide which strategy to create based on the given context.</em></p><h4>So what did we actually gain?</h4><p>As from the example above, switching to a different payment method requires no changes to CheckoutService.</p><ul><li>Adding a new payment method means adding a new class</li><li>No changes to existing code</li><li>Each strategy is a small, focused class which has a single responsibility.</li></ul><h4>Pros &amp; Cons</h4><p><strong>Pros</strong></p><ul><li>Remove complex if/else blocks</li><li>Encourages clean, modular design</li><li>Follows <em>Single Responsibility</em> principle.</li></ul><p><strong>Cons</strong></p><ul><li>Increased number of classes, which can feel overwhelming in very small systems.</li></ul><h4>Real — World Examples</h4><ul><li><em>Pricing &amp; discount calculations<br></em>Different discounts like promotions, vouchers, coupons.</li><li><em>Sorting algorithms</em></li><li><em>Compression utilities</em><br>Offering different file formats like ZIP, TAR, GZIP, etc.</li><li><em>Game behaviours</em><br>Example: Character can move by walking, running, crawling, etc.</li></ul><p>All of these share the same idea: the <em>goal remains the same</em>, but the <em>behaviour changes</em>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=03db9c05a486" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Adapter Design Pattern: Making Incompatible Systems Talk]]></title>
            <link>https://abhilodha.medium.com/the-adapter-design-pattern-making-incompatible-systems-talk-91cae288ac79?source=rss-6b78bc6a2fe0------2</link>
            <guid isPermaLink="false">https://medium.com/p/91cae288ac79</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[adapter-pattern]]></category>
            <category><![CDATA[lld]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Abhishek]]></dc:creator>
            <pubDate>Mon, 29 Dec 2025 09:47:40 GMT</pubDate>
            <atom:updated>2025-12-29T09:53:11.893Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="A USB-C to 3.5 mm adapter connecting ipod to a modern laptop" src="https://cdn-images-1.medium.com/max/1024/0*cKzzaJN4mKSgs61i" /><figcaption>Photo by <a href="https://unsplash.com/@docs_eng?utm_source=medium&amp;utm_medium=referral">Thorsten Konersmann</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>The Problem</h4><p>You love your wired earphones. They sound great and are really comfortable. It has a 3.5 mm jack.</p><p>Then you decide to buy a new phone of your liking. But it only comes with a USB-C port, no headphone jack.</p><p>Now you are left with the following choices:</p><ul><li>buy a new earphone which is compatible with your new phone. (<em>moderately expensive</em>)</li><li>buy a new phone which has a headphone jack (<em>expensive</em>)</li><li>buy an adapter which sits in between your earphones and your phone. (<em>least expensive</em>)</li></ul><p>And that’s the problem we often run into in software development — two things working well on their own, but are not compatible with each other.</p><blockquote>👉 This is exactly what the <strong><em>Adapter Design Pattern</em></strong> solves.</blockquote><h4>What is the Adapter Pattern?</h4><p>The adapter pattern is a structural design pattern in software engineering that allows two incompatible interfaces to work together. It acts as a bridge between different interfaces, enabling them to communicate without modifying their existing code.</p><h4>Example: Adapting a Legacy Stock Price API</h4><p>You are building a modern service which works with stock prices. Your system expects data in JSON format as below:</p><pre>{&quot;STOCK_TICKER&quot; : 12.45}</pre><p>But you actually have a legacy stock price API which returns data in XML and you can’t modify this.</p><pre>&lt;stock&gt;<br>  &lt;ticker&gt;STOCK_TICKER&lt;/ticker&gt;<br>  &lt;price&gt;12.45&lt;/price&gt;<br>&lt;/stock&gt;</pre><p>The adapter pattern comes in handy for this scenario.</p><h4>The legacy stock price API (unmodifiable for your use case)</h4><pre>public class LegacyStockAPI {<br><br>    public String fetchStockPriceXml(String ticker) {<br>        double price = fetchStockPrice(ticker);<br>        return &quot;&lt;stock&gt;&quot; +<br>               &quot;&lt;ticker&gt;&quot; + ticker + &quot;&lt;/ticker&gt;&quot; +<br>               &quot;&lt;price&gt;&quot; + String.valueOf(price) + &quot;&lt;/price&gt;&quot; +<br>               &quot;&lt;/stock&gt;&quot;;<br>    }<br>}</pre><h4>Step 1: Define the target interface (what your service expects)</h4><pre>public interface StockPriceService {<br>    StockPrice getPrice(String ticker);<br>}</pre><pre>//Assuming getter and setter<br>public class StockPrice {<br>    private String ticker;<br>    private double price;<br><br>    public StockPrice(String ticker, double price) {<br>        this.ticker = ticker;<br>        this.price = price;<br>    }<br>}</pre><h4>Step 2: Create the adapter</h4><pre>public class StockPriceAdapter implements StockPriceService {<br><br>    private LegacyStockAPI legacyStockAPI;<br><br>    public StockPriceAdapter(LegacyStockAPI legacyStockAPI) {<br>        this.legacyStockAPI = legacyStockAPI;<br>    }<br><br>    @Override<br>    public StockPrice getPrice(String ticker) {<br>        String xmlResponse = legacyStockAPI.fetchStockPriceXml(ticker);<br><br>        String priceValue = xmlResponse<br>                .split(&quot;&lt;price&gt;&quot;)[1]<br>                .split(&quot;&lt;/price&gt;&quot;)[0];<br><br>        double price = Double.parseDouble(priceValue);<br><br>        return new StockPrice(ticker, price);<br>    }<br>}</pre><p>This does the following:</p><ul><li>Uses the legacy API internally</li><li>Parses the XML response to domain object.</li></ul><h4>Step 3: Your Application invokes StockPriceService</h4><pre>public class YourApplication {<br><br>    public static void main(String[] args) {<br>        StockPriceService stockService = new StockPriceAdapter(new LegacyStockAPI());<br><br>        StockPrice appleStock = stockService.getPrice(&quot;AAPL&quot;);<br><br>        System.out.println(<br>            appleStock.getTicker() + &quot; price: &quot; + appleStock.getPrice()<br>        );<br>    }<br>}</pre><p>What happened here:</p><ul><li>YourApplication interacts with StockPriceService</li><li>The adapter translates the request</li><li>LegacyStockAPI remains untouched.</li></ul><blockquote>The adapter here made incompatible interfaces work together.</blockquote><h4>Ways to implement Adapter</h4><p>There are 2 ways in which adapter pattern could be implemented.</p><ul><li>Object Adapter</li><li>Class Adapter</li></ul><p><strong><em>Object Adapter</em></strong></p><p>Implemented in our example above.</p><ul><li>Provide more flexibility &amp; is easy to extend.</li><li>Uses Composition over Inheritance</li></ul><p><strong><em>Class Adapter</em></strong></p><p>Here, the adapter</p><ul><li><em>extends</em> the legacy service (LegacyStockAPI) and</li><li><em>implements</em> the target interface (StockPriceService)</li></ul><p>This makes the adapter a sub type of the legacy service and creates tight coupling between adapter &amp; legacy service. Hence this is not a very common implementation of adapter pattern.</p><h4>Pros &amp; Cons</h4><h4>Pros</h4><ul><li><em>Reuses existing code </em>— stable existing legacy system can be used as is.</li><li><em>Encourages loose coupling </em>— by using composition</li></ul><h4>Cons</h4><ul><li>Adds extra layer</li><li>Can be overused</li></ul><blockquote>When using Adapters, make sure they are thin and should not contain any business logic.</blockquote><h4>Real-World Examples</h4><ul><li><em>Database drivers (JDBC, ODBC)</em><br>Application talks to standard interfaces while the adapters handle various providers.</li><li><em>Payment gateways</em><br>Paypal, Stripe, Apple Pay adapters are used to interact with respective services but provide a common interface. <br><em>If you have multiple payment methods and you need to choose one at runtime, </em><em>Strategy Pattern should be used.</em></li><li><em>Logging frameworks<br></em>SLF4J adapters allow switching between Log4j, Logback.</li><li><em>Legacy Service Integrations</em><br>XML based SOAP services integrated with REST services using adapter.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91cae288ac79" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>