<?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 Jatin mamtora on Medium]]></title>
        <description><![CDATA[Stories by Jatin mamtora on Medium]]></description>
        <link>https://medium.com/@jatinumamtora?source=rss-24bbf2ff7048------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*CfHpvRwHn2XiAU0inLsvSw.jpeg</url>
            <title>Stories by Jatin mamtora on Medium</title>
            <link>https://medium.com/@jatinumamtora?source=rss-24bbf2ff7048------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 21:13:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jatinumamtora/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[Dissecting a Breakthrough in Shortest Path Algorithms]]></title>
            <link>https://medium.com/@jatinumamtora/dissecting-a-breakthrough-in-shortest-path-algorithms-64091721b696?source=rss-24bbf2ff7048------2</link>
            <guid isPermaLink="false">https://medium.com/p/64091721b696</guid>
            <category><![CDATA[shortest-path]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[datastrucutre]]></category>
            <category><![CDATA[research]]></category>
            <dc:creator><![CDATA[Jatin mamtora]]></dc:creator>
            <pubDate>Sun, 17 Aug 2025 17:13:35 GMT</pubDate>
            <atom:updated>2025-08-17T17:13:35.413Z</atom:updated>
            <content:encoded><![CDATA[<p>Finding the shortest path in a network is a fundamental problem in computer science. Think of Google Maps finding the fastest route to your destination or a logistics company optimizing delivery routes. For decades, <strong>Dijkstra’s algorithm</strong> has been the gold standard for solving this problem, but a new research paper is challenging its throne by proposing a faster, more strategic approach. (<a href="https://arxiv.org/abs/2504.17033">Link</a>)</p><h3>Why Dijkstra’s is Great, and What the New Algorithm Does Differently</h3><h4>Dijkstra’s: The Meticulous Planner</h4><p>Imagine you’re at your home and you want to visit every single friend in your city, taking the quickest possible route to each one.</p><p>Dijkstra’s algorithm is like a highly methodical planner. It finds the shortest path by following these steps:</p><ol><li><strong>Start at Home</strong>: You begin at your starting point and set your travel time to 0. All other friends’ houses are initially considered “infinitely” far away.</li><li><strong>Go to the Closest Friend</strong>: You always pick the friend’s house that is currently closest to you that you haven’t visited yet.</li><li><strong>Update Your Map</strong>: Once you get there, you check if you’ve found a new, shorter way to get to any of your other unvisited friends. If you have, you update your mental map.</li><li><strong>Repeat</strong>: You repeat this process — always visiting the single closest unvisited friend and updating your map — until you’ve visited everyone.</li></ol><p>This “always pick the closest” method is simple, reliable, and guaranteed to find the shortest path. But here’s the catch: the time you spend constantly checking your list of friends to find the very next closest one is the most time-consuming part. In the world of algorithms, this repeated sorting is known as the <strong>“<em>sorting</em> <em>barrier</em>,”</strong> and it limits how fast Dijkstra’s can be on a massive scale.</p><h4>The New Algorithm: The “Group and Conquer” Strategist</h4><p>The new algorithm, as described in the research paper titled <strong>“Breaking the Sorting Barrier for Directed Single-Source Shortest Paths,”</strong> takes a different approach. Instead of a one-by-one, meticulous search, it uses a smarter, more strategic method to get the job done faster.</p><p>Imagine you’re a logistics manager. You don’t have time to meticulously plan the route to every single one of a hundred stores one-by-one. Instead, you’d do this:</p><ol><li><strong>Identify Key Hubs</strong>: You first identify a few key “hubs” or “pivots” — major locations close to highways or centrally located. These aren’t necessarily the single closest destinations, but they are great starting points for a lot of deliveries.</li><li><strong>Launch “Mini-Searches”</strong>: From these hubs, you perform a quick, limited search to all the nearby stores. This is a rapid-fire check that gets you an approximate shortest route to many destinations at once, without a full-blown calculation.</li><li><strong>Eliminate and Focus</strong>: Based on these mini-searches, you’ve now eliminated a huge number of potential routes and can focus on a much smaller, more manageable group of remaining stores.</li><li><strong>Repeat</strong>: You repeat this process of finding new hubs, launching mini-searches, and reducing the number of stores until you’ve completed all your deliveries.</li></ol><p>This “group and conquer” strategy is what allows the new algorithm to be faster. By avoiding the constant, costly sorting of a huge list of destinations, it bypasses the “sorting barrier” that holds Dijkstra’s back.</p><p>The paper’s algorithm is built on a recursive function and a special sub-routine. Let’s break down the key technical components mentioned in the pseudocode.</p><h4>The Main Algorithm: SSSP-Rec (Single-Source Shortest Path - Recursive)</h4><p>This is the high-level control function. It works on the principle of <strong>divide-and-conquer</strong>.</p><ul><li><strong>Pseudocode:</strong> SSSP-Rec(G, w)</li><li><strong>What it does:</strong> It takes a graph G and a distance value w.</li><li><strong>Base Case:</strong> If the graph has a small number of vertices (|V| is small), the function stops the recursion and uses a fast, simple algorithm to solve the problem directly. This prevents unnecessary overhead on small sub-problems.</li><li><strong>Recursive Step:</strong> If the graph is large, it does the following:</li><li>It picks a handful of “pivots” (our hubs).</li><li>It uses its core engine, <strong>BMSSP</strong> (explained next), to perform a limited search from these pivots.</li><li>It then makes a recursive call to SSSP-Rec on smaller, independent subsets of the graph.</li></ul><p>This recursive breakdown allows the algorithm to process the graph in chunks, avoiding the sorting bottleneck that affects the entire graph at once.</p><h4>The Core Engine: BMSSP (Bounded Multi-Source Shortest Paths)</h4><p>This is the workhorse of the algorithm and the key to its speed. It is a sub-routine that performs a fast, limited “mini-search” from a set of sources.</p><ul><li><strong>Pseudocode:</strong> BMSSP(G, S, w)</li><li><strong>What it does:</strong> It takes a graph G, a set of source vertices S (our pivots), and a distance &quot;budget&quot; w.</li><li><strong>Initialization:</strong> It sets the distance of each source in S to 0 and all other distances to infinity.</li><li><strong>Relaxation Loop:</strong> It repeatedly finds the closest vertex among its current candidates and updates the distances of its neighbours. This is a <strong>Bellman-Ford-<em>like</em> relaxation process</strong>, which is typically slower than Dijkstra’s but doesn’t require a constantly sorted list.</li><li><strong>The “Bounded” Part:</strong> The most important part is that this loop is <strong>bounded</strong>. It only runs as long as the current minimum distance is within the budget w. This ensures that the algorithm doesn&#39;t waste time on a full, exhaustive search, which is why it&#39;s so efficient.</li></ul><h4>The Relaxed Heap</h4><p>The paper also relies on a specialized data structure called a <strong>Relaxed Heap</strong>. While the pseudocode doesn’t detail its implementation, its purpose is critical.</p><ul><li><strong>What it is:</strong> It’s a type of priority queue that’s designed for speed. In a normal priority queue, updating an element’s value (known as a “decrease-key” operation) can be slow because it requires re-sorting.</li><li><strong>Why it’s Crucial:</strong> The BMSSP algorithm performs many &quot;relaxations,&quot; which are essentially &quot;decrease-key&quot; operations. The relaxed heap is designed to make these operations incredibly fast, providing the performance boost needed to make the entire algorithm work efficiently.</li></ul><p>By combining this specialised heap with its recursive, multi-source approach, the researchers have managed to break the O(m + n log n) time bound of Dijkstra&#39;s algorithm, proving that faster alternatives are possible.<br><strong>Note</strong>: This is based on my understanding of the paper. Suggestions and feedback are welcome.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64091721b696" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kafka: More than just a simple MQ]]></title>
            <link>https://medium.com/@jatinumamtora/kafka-more-than-just-a-simple-mq-1b83cac5d68c?source=rss-24bbf2ff7048------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b83cac5d68c</guid>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[message-queue]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Jatin mamtora]]></dc:creator>
            <pubDate>Mon, 04 Aug 2025 16:53:30 GMT</pubDate>
            <atom:updated>2025-08-04T16:54:09.383Z</atom:updated>
            <content:encoded><![CDATA[<p>There are countless systems grapple with the ephemeral nature of messages. Traditional Message Queues (MQs) like RabbitMQ, while excellent for transient task dispatch and workload distribution, often treat messages as fleeting moments — once consumed, they’re gone. This works for many scenarios, but what happens when a consumer crashes, multiple teams need the same data, or you suddenly need to reprocess historical events for a new analytics pipeline? This is where Apache Kafka shines, fundamentally re-architecting how we perceive and manage data streams.</p><p>Kafka doesn’t just queue messages; it transforms them into <strong>permanent, distributed records stored in an immutable, append-only log</strong>. This paradigm shift unlocks a powerful set of capabilities that are simply not possible with transient MQs.</p><h3>The Core Difference: Permanent Records vs. Fleeting Messages</h3><p>Let’s break down the fundamental distinction:</p><p><strong>Transient MQs (e.g., RabbitMQ):</strong></p><ul><li><strong>Message Deletion:</strong> Messages are typically removed from the queue once a consumer successfully acknowledges their processing. This “fire-and-forget” model works well for task queues where a message’s utility is exhausted after a single processing.</li><li><strong>Consumer Responsibility:</strong> The MQ is responsible for delivering the message to <em>a</em> consumer. If that consumer crashes before processing and acknowledging, the message might be redelivered (depending on configurations like acknowledgements and message durability), but the concept of “replaying” a stream for multiple, independent consumers is not inherent to their design.</li><li><strong>Limited Historical Access:</strong> Once consumed, the message is effectively gone from the queue. Retrieving past messages for new applications or analytics is often impossible or requires complex workarounds (e.g., archiving to separate storage).</li></ul><p><strong>Kafka:</strong></p><ul><li><strong>Permanent Log:</strong> Kafka treats each topic as a <strong>permanent, ordered, immutable log of records</strong>. When a producer publishes a message (or “event”), it’s appended to the end of a topic’s partition. This message remains in the log for a configurable retention period (e.g., days, weeks, or even indefinitely), regardless of whether it has been consumed.</li><li><strong>Consumer Offset Tracking:</strong> Consumers don’t “delete” data. Instead, they <strong>mark their position (offset)</strong> in this continuous stream. Each consumer group independently tracks its own offset. This is a game-changer.</li><li><strong>Distributed Ledger:</strong> This log is distributed across multiple Kafka brokers and further divided into <strong>partitions</strong>. Each partition is replicated across multiple brokers to ensure fault tolerance and high availability. So, the “permanence” is not just on one disk but redundantly stored across a distributed cluster.</li></ul><h3>A Deeper Dive into Kafka’s Permanent Record Management</h3><p>Imagine a Kafka topic named user_activity. Every click, login, search, or purchase a user makes becomes an event appended to this topic.</p><ol><li><strong>Topics and Partitions:</strong> A Kafka topic is a logical category or feed name to which records are published. To enable scalability and parallelism, topics are divided into <strong>partitions</strong>. Each partition is an ordered, immutable sequence of records that is continually appended to.</li></ol><ul><li><strong>Ordering within a Partition:</strong> Messages within a single partition are strictly ordered by the order they were appended. Kafka guarantees this order.</li><li><strong>Distributed Storage:</strong> These partitions are distributed across the Kafka brokers in a cluster. A broker holds a portion of the data for one or more topics.</li><li><strong>Replication for Durability:</strong> To prevent data loss and ensure high availability, each partition can have multiple <strong>replicas</strong>. These replicas are copies of the partition’s data on different brokers. If a broker fails, other brokers with replicas can seamlessly take over, ensuring continuous data availability.</li></ul><p><strong>2. Producers and Consumers:</strong></p><ul><li><strong>Producers:</strong> Applications that publish (write) events to Kafka topics. They choose which partition to send the message to (e.g., based on a message key for consistent ordering).</li><li><strong>Consumers:</strong> Applications that subscribe to (read) events from topics. The key here is the <strong>consumer group</strong>. Multiple consumers can form a consumer group, and within that group, each partition is consumed by exactly one consumer. This ensures that messages within a partition are processed in order by that group.</li><li><strong>Offset Management:</strong> Crucially, consumers in Kafka manage their own “offset” — the pointer to the last message they’ve read in a partition. This offset is periodically committed back to Kafka (typically to an internal __consumer_offsets topic).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nuvZLmdlBTJ7TvBuNoemnA.png" /><figcaption>Disclaimer: This is a simplified representation proper architecture diagram would involve more detailed components like ZooKeeper/KRaft for metadata, and clearer network connections.</figcaption></figure><p><strong>Explanation of the diagram:</strong></p><ul><li><strong>Producer:</strong> Sends messages to “Topic A”.</li><li><strong>Kafka Cluster:</strong> Consists of multiple brokers. Here, Broker 1 is the leader for Partition 0 of Topic A, and Broker 2 is the leader for Partition 1. They also hold follower replicas of each other’s partitions, ensuring data redundancy.</li><li><strong>Partitions (P0, P1):</strong> Each partition holds an ordered log of messages.</li><li><strong>Consumer Groups (X, Y, Z): </strong>Each consumer group represents a distinct logical application or team that wants to consume the data.</li><li>Each group maintains its own independent set of offsets for each partition.</li><li>For instance, Consumer Group X has read up to message 2 in Partition 0, while Consumer Group Y has read up to message 5. This allows different applications to consume the same data at their own pace, without interfering with each other.</li></ul><h3>How Kafka Handles Failures: The Power of Rewind and Replay</h3><p>This offset-based, permanent log approach is crucial for robust failure recovery and new use cases:</p><ol><li><strong>Consumer Crash and Recovery:</strong></li></ol><ul><li>If a consumer instance crashes, it doesn’t lose its “place.” When it restarts (or another consumer in the same group takes over its partitions during a rebalance), it simply resumes reading from the <strong>last committed offset</strong>.</li><li>There’s no need for the Kafka broker to “re-send” messages because the messages are never deleted from the log by consumers. The consumer simply picks up where it left off. This makes consumer recovery incredibly resilient and straightforward.</li></ul><p><strong>2. Rewind and Replay for Bug Fixes or New Logic:</strong></p><ul><li>This is where Kafka truly shines beyond traditional MQs. Imagine you discover a bug in your payment processing consumer that incorrectly calculated a fee for transactions over the last week.</li><li>With a traditional MQ, those “incorrectly processed” messages would be long gone.</li><li>With Kafka, you can simply <strong>rewind the offset of your payment processing consumer group</strong> to the beginning of the problematic period (e.g., one week ago).</li><li>The consumer will then <strong>replay</strong> all the messages from that point forward, allowing you to re-process them with the corrected logic. This is like a “time machine” for your data. This is invaluable for data integrity, auditing, and ensuring correctness in event-driven systems.</li></ul><p><strong>3. New Analytics Pipelines and Backfilling:</strong></p><ul><li>Another powerful use case is creating new analytics pipelines or introducing new business logic. Suppose you decide to analyze user behavior for a new feature launched three months ago, but your existing systems only stored aggregates.</li><li>With Kafka, you can spin up a <strong>brand new consumer group</strong> for this specific analytics task. This new group can start consuming from the very beginning of the user_activity topic (or a specific timestamp) and process all historical data.</li><li>This allows you to “backfill” your analytics database or data warehouse with historical information without impacting any existing consumers. It turns your Kafka topics into a durable source of truth for all your data needs, both real-time and historical.</li></ul><h3>Real-World Architectures: Netflix, Uber, and LinkedIn</h3><p>These tech giants leverage Kafka’s unique properties to power their core services:</p><h4>Netflix: Real-time Data Pipelines and Microservices Communication</h4><ul><li><strong>Event Sourcing:</strong> Netflix heavily uses Kafka for event sourcing, where every state change in their massive distributed systems is captured as an immutable event in Kafka. This provides a complete audit trail and allows for easy reconstruction of application state.</li><li><strong>Real-time Analytics:</strong> Data streams from various services (user activity, streaming events, system metrics) are ingested into Kafka topics, providing a backbone for real-time analytics, personalization, and monitoring.</li><li><strong>Decoupled Microservices:</strong> Kafka acts as a central nervous system for their microservices architecture, enabling loosely coupled communication. Services publish events to topics, and other services subscribe to those events without direct dependencies.</li><li><strong>Example (Simplified Netflix Data Flow):</strong></li><li>User clicks “Play” -&gt; Event published to playback_events topic.</li><li>Recommendation service consumes playback_events to update user profiles and recommend content.</li><li>Billing service consumes playback_events to track viewing for billing purposes.</li><li>Analytics team can replay playback_events to understand user engagement patterns over time.</li></ul><h4>LinkedIn: The Birthplace of Kafka — Real-time Data Pipelines and Stream Processing</h4><ul><li><strong>LinkedIn’s Origin:</strong> Kafka was originally developed at LinkedIn to handle their massive stream of data (user activity, system logs, operational metrics) in a scalable and fault-tolerant manner.</li><li><strong>Activity Feeds:</strong> Kafka powers LinkedIn’s real-time activity feeds, ensuring that updates from connections are delivered promptly.</li><li><strong>Operational Metrics and Log Aggregation:</strong> All system logs and metrics are streamed into Kafka, providing a unified real-time view of their infrastructure’s health and performance.</li><li><strong>Data Integration:</strong> Kafka acts as a central hub for integrating data across various internal systems and data stores.</li><li><strong>Stream Processing:</strong> LinkedIn heavily uses Kafka Streams and other stream processing frameworks to build complex real-time data transformations and analytics on top of their Kafka data.</li><li><strong>Example (Simplified LinkedIn Architecture):</strong></li><li>User posts update -&gt; user_updates Kafka topic.</li><li>News feed service consumes user_updates to deliver relevant content to users&#39; feeds.</li><li>Search indexing service consumes user_updates to keep search indexes up-to-date.</li><li>Compliance and auditing teams can access the immutable user_updates log for regulatory requirements.</li></ul><h3>Conclusion</h3><p>Kafka fundamentally shifts from transient messages to a permanent, distributed log. This allows consumers to recover from failures by resuming from their last read position and enables powerful use cases like replaying historical data. This resilience and durability make Kafka the ideal backbone for modern event-driven architectures.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b83cac5d68c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Unsung Hero of Search: A Deep Dive into the Inverted Index]]></title>
            <link>https://medium.com/@jatinumamtora/the-unsung-hero-of-search-a-deep-dive-into-the-inverted-index-be452d15a5d6?source=rss-24bbf2ff7048------2</link>
            <guid isPermaLink="false">https://medium.com/p/be452d15a5d6</guid>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[database-design]]></category>
            <category><![CDATA[search-engines]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[index]]></category>
            <dc:creator><![CDATA[Jatin mamtora]]></dc:creator>
            <pubDate>Sun, 27 Jul 2025 13:48:55 GMT</pubDate>
            <atom:updated>2025-07-27T13:48:55.945Z</atom:updated>
            <content:encoded><![CDATA[<p><em>From Google to your database, understand the data structure that makes finding anything, anywhere, instant.</em></p><p>Ever paused to wonder how Google can sift through trillions of web pages in less time than it takes to blink? Or how your favourite e-commerce site instantly finds that one specific product among millions? You type “lazy dog,” and in a flash, you get exactly what you’re looking for.</p><p>This isn’t magic. It’s one of the most brilliant, yet fundamentally simple, data structures ever conceived: the<strong> Inverted Index.</strong></p><h3>The Library Book Analogy</h3><p>Before we touch a single line of code, let’s imagine you have a small library of three books.</p><ul><li>Book 1: “The quick brown fox jumped over the lazy dog.”</li><li>Book 2: “The lazy dog slept in the sun.”</li><li>Book 3: “A quick brown cat sleeps in the sun.”</li></ul><p>Now, I ask you to find all the books that contain the word “lazy”.</p><p>What would you <em>not</em> do? You wouldn’t read Book 1 from start to finish, then Book 2, then Book 3. That’s slow and inefficient. This “scan everything” approach is what a database does without a proper index.</p><p>Instead, you’d instinctively do what your brain is great at: you’d create a mental index. It would look something like the index at the back of a textbook.</p><pre><br>+--------+--------------------+<br>|  Word  | Appears in Book(s) |<br>+--------+--------------------+<br>| a      |                  3 |<br>| brown  |               1, 3 |<br>| cat    |                  3 |<br>| dog    |               1, 2 |<br>| fox    |                  1 |<br>| in     |               2, 3 |<br>| jumped |                  1 |<br>| lazy   |               1, 2 |<br>| over   |                  1 |<br>| quick  |               1, 3 |<br>| slept  |                  2 |<br>| sleeps |                  3 |<br>| sun    |               2, 3 |<br>| the    |               1, 2 |<br>+--------+--------------------+</pre><p>You’ve just built an Inverted Index !!!</p><p>It’s “inverted” because instead of mapping a document to the words it contains (Document -&gt; Words), it maps each word to the documents it appears in (Word -&gt; Documents).</p><p>With this index, answering “Which books contain ‘lazy’?” is instantaneous. You just look up “lazy” and get your answer: Book 1 and Book 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y7MfyEQd0aqn2KjGwNoQSQ.png" /></figure><h3>From Analogy to Algorithm: How It’s Built</h3><p>Building this index involves a few key steps. Let’s formalize our little library example.</p><ol><li>Collect Documents: First, we gather our data. In our case, it’s our three sentences. We’ll give them IDs: Document 1, Document 2, and Document 3.</li><li>Tokenization &amp; Normalization: Computers are literal. “The” and “the” are different things to them. So, we clean up our text.</li></ol><ul><li><strong>Tokenize</strong>: We break each document into individual words, or “tokens.” We usually split by spaces and punctuation. (&quot;The&quot;, &quot;quick&quot;, &quot;brown&quot;, &quot;fox&quot;...)</li><li><strong>Normalize</strong>: We convert everything to a standard format, like lowercase. (&quot;the&quot;, &quot;quick&quot;, &quot;brown&quot;, &quot;fox&quot;...). We might also perform more advanced steps like <em>stemming</em> (reducing words to their root, like &quot;jumped&quot; -&gt; &quot;jump&quot;) or removing common <em>stop words</em> (&quot;the,&quot; &quot;a,&quot; &quot;in&quot;).</li></ul><p>3. Create the Index: We iterate through each token in every document and. build our map. For each word, we record the ID of the document it came from. The list of document IDs associated with a word is called a postings list.</p><p>This is the core process that powers engines like Elasticsearch, Apache Lucene, and the full-text search capabilities in databases like PostgreSQL.</p><h3>Let’s Get Our Hands Dirty: A Simple Java Implementation</h3><p>Theory is great, but code makes it real. Here is a simple, clean Java implementation of an Inverted Index. It demonstrates the entire process: adding documents, tokenizing, indexing, and searching.</p><pre>import java.util.*;<br><br>/**<br> * A simple implementation of an Inverted Index.<br> */<br>public class InvertedIndex {<br><br>    // The core data structure for the inverted index.<br>    // It maps each term (String) to a set of document IDs (Integer) where the term appears.<br>    private final Map&lt;String, Set&lt;Integer&gt;&gt; index = new HashMap&lt;&gt;();<br><br>    // A simple store for the documents themselves, mapping a document ID to its content.<br>    private final Map&lt;Integer, String&gt; documents = new HashMap&lt;&gt;();<br><br>    // Counter to assign a unique ID to each new document.<br>    private int nextDocId = 0;<br><br>    /**<br>     * Adds a document to the index.<br>     * This method performs tokenization and basic normalization (lowercase).<br>     *<br>     * @param text The content of the document to add.<br>     */<br>    public void addDocument(String text) {<br>        // Assign a new, unique ID to the document and store its content.<br>        int docId = nextDocId;<br>        documents.put(docId, text);<br><br>        // --- Tokenization and Normalization ---<br>        // 1. Convert to lowercase.<br>        // 2. Split the text into words (tokens) using whitespace and punctuation as delimiters.<br>        String[] tokens = text.toLowerCase().split(&quot;\\W+&quot;);<br><br>        // --- Indexing ---<br>        // For each token, add the current document ID to its postings list in the index.<br>        for (String token : tokens) {<br>            if (token.isEmpty()) {<br>                continue;<br>            }<br>            // If the token is not yet in the index, a new HashSet is created.<br>            // Then, the current docId is added to the set for that token.<br>            index.computeIfAbsent(token, k -&gt; new HashSet&lt;&gt;()).add(docId);<br>        }<br><br>        // Increment the ID for the next document.<br>        nextDocId++;<br>    }<br><br>    /**<br>     * Searches the index for documents containing all the words in the query.<br>     *<br>     * @param query The search query string (e.g., &quot;quick brown&quot;).<br>     * @return A Set of documents that match the query.<br>     */<br>    public Set&lt;String&gt; search(String query) {<br>        // --- Query Processing ---<br>        // Tokenize the query string just like the documents.<br>        String[] queryTokens = query.toLowerCase().split(&quot;\\W+&quot;);<br>        Set&lt;String&gt; resultDocuments = new HashSet&lt;&gt;();<br><br>        if (queryTokens.length == 0 || queryTokens[0].isEmpty()) {<br>            return resultDocuments; // Return empty set if query is empty<br>        }<br><br>        // --- Search Execution ---<br>        // 1. Get the postings list for the *first* term in the query.<br>        // This initializes our set of potential results.<br>        Set&lt;Integer&gt; resultSet = new HashSet&lt;&gt;(index.getOrDefault(queryTokens[0], Collections.emptySet()));<br><br>        // 2. For all subsequent terms, find the intersection.<br>        // The `retainAll` method keeps only the elements that are in both sets.<br>        for (int i = 1; i &lt; queryTokens.length; i++) {<br>            String token = queryTokens[i];<br>            if (token.isEmpty()) {<br>                continue;<br>            }<br>            resultSet.retainAll(index.getOrDefault(token, Collections.emptySet()));<br>        }<br><br>        // --- Result Retrieval ---<br>        // Convert the final set of document IDs back to the original document content.<br>        for (Integer docId : resultSet) {<br>            resultDocuments.add(documents.get(docId));<br>        }<br><br>        return resultDocuments;<br>    }<br><br>    /**<br>     * Main method to demonstrate the InvertedIndex functionality.<br>     */<br>    public static void main(String[] args) {<br>        InvertedIndex searchEngine = new InvertedIndex();<br><br>        // Add the example documents from our discussion. (doc IDs will be 0, 1, 2)<br>        searchEngine.addDocument(&quot;The quick brown fox jumped over the lazy dog.&quot;);<br>        searchEngine.addDocument(&quot;The lazy dog slept in the sun.&quot;);<br>        searchEngine.addDocument(&quot;A quick brown cat sleeps in the sun.&quot;);<br><br>        // Perform a search for &quot;quick brown&quot;<br>        System.out.println(&quot;Searching for: &#39;quick brown&#39;&quot;);<br>        Set&lt;String&gt; results = searchEngine.search(&quot;quick brown&quot;);<br><br>        // Print the results<br>        if (results.isEmpty()) {<br>            System.out.println(&quot;No documents found.&quot;);<br>        } else {<br>            System.out.println(&quot;Found in documents:&quot;);<br>            results.forEach(doc -&gt; System.out.println(&quot;- \&quot;&quot; + doc + &quot;\&quot;&quot;));<br>        }<br>        <br>        System.out.println(&quot;\n----------------------------------\n&quot;);<br><br>        // Perform a search for &quot;lazy dog sun&quot;<br>        System.out.println(&quot;Searching for: &#39;lazy dog sun&#39;&quot;);<br>        results = searchEngine.search(&quot;lazy dog sun&quot;);<br><br>        // Print the results<br>        if (results.isEmpty()) {<br>            System.out.println(&quot;No documents found.&quot;);<br>        } else {<br>            System.out.println(&quot;Found in documents:&quot;);<br>            results.forEach(doc -&gt; System.out.println(&quot;- \&quot;&quot; + doc + &quot;\&quot;&quot;));<br>        }<br>    }<br>}</pre><h3>Code Breakdown: The Magic of retainAll</h3><p>The addDocument method does exactly what we described: tokenizes, normalizes, and maps words to document IDs. But the real elegance is in the search method.</p><p>How do we handle a multi-word query like “lazy dog”?</p><ol><li>Look up “lazy” -&gt; get postings list {0, 1}.</li><li>Look up “dog” -&gt; get postings list {0, 1}. (In our example, they are the same)</li><li>Find the intersection of these two sets — the documents that appear in <em>both</em> lists. The intersection of {0, 1} and {0, 1} is {0, 1}.</li></ol><p>Now, for “lazy dog sun”:</p><ol><li>Look up “lazy” -&gt; {0, 1}</li><li>Look up “dog” -&gt; {0, 1}</li><li>Look up “sun” -&gt; {1, 2}</li></ol><p>The search logic does this:</p><ul><li>Start with the set for “lazy”: {0, 1}</li><li>Intersect with the set for “dog”: resultSet.retainAll({0, 1}) -&gt; resultSet is still {0, 1}</li><li>Intersect with the set for “sun”: resultSet.retainAll({1, 2}) -&gt; resultSet becomes {1}</li></ul><p>The final result is Document 1 (&quot;The lazy dog slept in the sun.&quot;), which is the only document containing all three words. The retainAll method in Java is a beautifully efficient way to perform this set intersection.</p><h3>Beyond the Basics</h3><p>A simple inverted index is powerful, but professional systems add more layers:</p><ul><li><strong>Relevance and Scoring</strong> (TF-IDF, BM25): How do you rank the results? An index can also store the frequency of a term in a document (Term Frequency) and across the entire collection (Inverse Document Frequency). These metrics help score documents, so the most relevant ones appear first.</li><li><strong>Positional Information</strong>: To handle phrase searches (e.g., finding &quot;quick brown fox&quot; in that exact order), the index must also store the position of each word within the document. The postings list might look like fox: {Doc1: }.</li><li><strong>Scalability and Distribution</strong>: For web-scale data, a single index is not feasible. The index is broken up (sharded) and distributed across many machines, with results being aggregated from all shards.</li><li><strong>Index Compression</strong>: These indexes can become enormous. Clever compression techniques are used to reduce their size on disk and in memory without sacrificing too much speed.</li></ul><h3>Conclusion</h3><p>The Inverted Index is a testament to the power of simple ideas. By flipping our perspective — from looking at documents to looking at words — we unlock the ability to search vast oceans of data in an instant.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be452d15a5d6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Write-Ahead Logging (WAL) in Database Engines & Recovery.]]></title>
            <link>https://medium.com/@jatinumamtora/a-deep-dive-into-write-ahead-logging-wal-in-database-engines-recovery-71f6d98f0e23?source=rss-24bbf2ff7048------2</link>
            <guid isPermaLink="false">https://medium.com/p/71f6d98f0e23</guid>
            <category><![CDATA[recovery]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[write-ahead-logging]]></category>
            <category><![CDATA[logging]]></category>
            <category><![CDATA[database-design]]></category>
            <dc:creator><![CDATA[Jatin mamtora]]></dc:creator>
            <pubDate>Sun, 06 Jul 2025 05:36:52 GMT</pubDate>
            <atom:updated>2025-08-04T16:58:30.975Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction: The Unsung Hero of Data Durability</h3><p>Imagine a critical transaction completing successfully, only for the system to crash moments later. Without robust mechanisms, that completed transaction, and potentially all subsequent data, could be lost forever. This is where <strong>Write-Ahead Logging (WAL)</strong> emerges as an unsung hero, a fundamental technique ensuring that even in the face of system failures, your data remains consistent and durable.</p><p>WAL is a cornerstone of modern relational database management systems (RDBMS) like PostgreSQL, MySQL (with InnoDB), Oracle, and SQL Server, as well as NoSQL databases like MongoDB (with WiredTiger) and Apache Cassandra (for commit log). Its core principle is simple yet profoundly effective: <strong><em>before any data modification is applied to the actual database files on disk, the change must first be recorded in a persistent log file.</em></strong> This ensures that even if a system crashes at any point, the database can reconstruct its state and recover all committed transactions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*_BVw40vMZQNUZNdz-MwlRg.png" /></figure><h3>The WAL Principle: “Before Data, Write Log”</h3><p>The <strong>Write-Ahead Logging (WAL) principle</strong> dictates that all changes to data must be written to a log file <em>before</em> they are applied to the actual data files on disk. This is a crucial rule for ensuring atomicity and durability <br>(the ‘A’ and ‘D’ in ACID properties).</p><p>Here’s how it generally works:</p><ul><li><strong>Transaction Starts:</strong> A transaction begins, and any modification it intends to make to the data is not immediately written to the main data files.</li><li><strong>Log Record Generation:</strong> For every modification (e.g., INSERT, UPDATE, DELETE), a <strong>log record</strong> is generated. This log record contains enough information to redo or undo the operation. Typical information in a log record includes:</li><li><strong>Transaction ID (TxID):</strong> Identifies the transaction performing the change.</li><li><strong>Log Sequence Number (LSN):</strong> A unique, monotonically increasing identifier for the log record, indicating its position in the log.</li><li><strong>Page ID:</strong> The identifier of the database page being modified.</li><li><strong>Redo Information:</strong> The new value or the operation needed to re-apply the change during recovery (e.g., “set byte 100 on page X to value Y”).</li><li><strong>Undo Information (Optional, but common in ARIES):</strong> The old value or the operation needed to revert the change during recovery (e.g., “set byte 100 on page X to old_value Z”).</li><li><strong>Log Flush:</strong> Before the transaction is considered “committed,” or before any dirty data page is written to disk, the log records corresponding to that transaction <em>must</em> be physically written (flushed) to the persistent WAL file on stable storage (disk). This is often achieved by performing a fsync() or equivalent operation on the log file.</li><li><strong>Data Page Write:</strong> Only <em>after</em> the log records for a change are safely on disk, the actual modified data page in the buffer pool (an in-memory cache) can be written back to its corresponding location in the main data files on disk.</li></ul><p>This sequence guarantees that if a system crash occurs before a modified data page is written to disk, the corresponding log records are already safely stored. Upon recovery, the database can read these log records and re-apply (redo) the changes, effectively bringing the database back to a consistent state.</p><h3>Log Sequence Number (LSN) Management</h3><p>The <strong>Log Sequence Number (LSN)</strong> is a fundamental concept in WAL. It’s a byte offset within the log file that uniquely identifies a log record. LSNs are strictly increasing, meaning a later log record always has a higher LSN than an earlier one.</p><p>Key aspects of LSN management:</p><ul><li><strong>Monotonically Increasing:</strong> Each new log record is assigned an LSN greater than the previous one. This creates a logical ordering of all database operations.</li><li><strong>Page LSNs:</strong> Every data page in the database has an associated LSN, often stored within the page header. This pageLSN indicates the LSN of the most recent log record that modified that specific page.</li><li><strong>Recovery Point:</strong> The LSN acts as a pointer during recovery. When the database crashes, it needs to find a starting point in the log to begin recovery. This starting point is often determined by the checkpointLSN (discussed next).</li><li><strong>Durability Guarantees:</strong> When a transaction commits, the system waits for its commit log record (and all preceding records) to be flushed to disk. The commitLSN of the transaction provides a durable point.</li><li><strong>Concurrency Control Integration:</strong> LSNs are also crucial for concurrency control. Lock managers and other mechanisms might use LSNs to ensure correct ordering of operations and to handle conflicts.</li></ul><h3>Checkpoints: Bringing Order to the Log Chaos</h3><p>While WAL provides durability, continuously appending to an ever-growing log file would eventually consume all disk space and make recovery prohibitively long. This is where <strong>checkpointing</strong> comes in.</p><h3>The Role of Checkpoints</h3><p>A <strong>checkpoint</strong> is a mechanism to periodically minimize the amount of work required during crash recovery. Without checkpoints, the database would have to scan the entire log file from the very beginning of time to redo or undo all transactions. This is inefficient and time-consuming.</p><p>During a checkpoint process, the database system:</p><ul><li><strong>Writes Dirty Pages to Disk:</strong> All modified (dirty) pages currently in the buffer pool are flushed to their permanent locations on disk. This significantly reduces the number of pages that might need redoing during recovery.</li><li><strong>Records Current State:</strong> The system records metadata about the current state of the database, including:</li><li><strong>checkpointLSN:</strong> The LSN of the most recent log record written when the checkpoint started. This LSN marks the beginning of the log scan for recovery purposes. Any log records with LSNs lower than checkpointLSN are guaranteed to have their changes reflected in the data files on disk.</li><li><strong>Active Transactions:</strong> A list of transactions that were active (not yet committed or aborted) at the time of the checkpoint.</li><li><strong>Dirty Page Table (DPT):</strong> A list of pages that were dirty at the time of the checkpoint, along with their recLSN (Recovery LSN), which is the LSN of the first log record that made the page dirty.</li><li><strong>Updates Master Record:</strong> This checkpoint information is typically written to a special “master record” in a well-known location on disk, often near the beginning of the log or in a dedicated file.</li></ul><p>The primary goal of a checkpoint is to reduce the “recovery window” — the portion of the log that needs to be processed during crash recovery. By forcing dirty pages to disk and recording the state, the database can start recovery from the checkpointLSN instead of the beginning of the log.</p><h3>Types of Checkpoints</h3><p>Checkpoints can be triggered in various ways:</p><ul><li><strong>Fuzzy Checkpoints:</strong> These are the most common type. Instead of pausing all database activity, dirty pages are flushed to disk in the background while normal operations continue. This minimizes disruption to active transactions but requires careful handling during recovery.</li><li><strong>Consistent Checkpoints:</strong> These require pausing or quiescing all database activity to ensure that all dirty pages are written to disk and a consistent snapshot is taken. They are simpler for recovery but incur significant downtime and are less common in high-performance OLTP systems.</li><li><strong>Interval-Based Checkpoints:</strong> Triggered after a certain amount of time has passed.</li><li><strong>Log-Size Based Checkpoints:</strong> Triggered after a certain amount of log data has been generated.</li><li><strong>User-Initiated Checkpoints:</strong> Explicitly invoked by a database administrator.</li></ul><h3>Crash Recovery: Bringing the Database Back to Life with ARIES</h3><p>The real power of WAL is unleashed during <strong>crash recovery</strong>. The goal is to bring the database to a consistent state, reflecting all transactions that were committed before the crash and undoing any uncommitted transactions. The <strong>ARIES (Algorithm for Recovery and Isolation Exploiting Semantics)</strong> algorithm is a widely adopted and robust recovery scheme.</p><h3>The ARIES Recovery Algorithm</h3><p>ARIES is a “redo/undo/no-force” logging and recovery algorithm.</p><ul><li><strong>Redo/Undo:</strong> It uses log records to both redo (re-apply) committed changes and undo (reverse) uncommitted changes.</li><li><strong>No-Force:</strong> It doesn’t force all dirty pages to disk at every commit. Instead, it relies on checkpoints and the WAL principle to ensure durability.</li></ul><p>ARIES operates in three main phases during recovery:</p><ol><li><strong>Analysis Phase:</strong></li></ol><ul><li><strong>Scan Forward:</strong> The recovery manager starts by scanning the log forward from the checkpointLSN (obtained from the master record).</li><li><strong>Reconstruct Active Transaction Table (ATT):</strong> It identifies all transactions that were active at the time of the crash (i.e., they started before the crash but had no commit/abort record).</li><li><strong>Reconstruct Dirty Page Table (DPT):</strong> It identifies all pages that were dirty in memory when the crash occurred, along with their recLSN (the LSN of the first log record that made that page dirty since the last time the page was flushed to disk).</li><li><strong>Find Redo LSN:</strong> The lowest recLSN from the reconstructed DPT is identified. This is the starting point for the Redo phase (often called the redoLSN).</li></ul><p><strong>2. Redo Phase (Repeating History):</strong></p><ul><li><strong>Scan from </strong><strong>redoLSN:</strong> The log is scanned forward from the redoLSN (found in the Analysis phase).</li><li><strong>Re-apply all Changes:</strong> For every log record encountered (both committed and uncommitted transactions):</li><li>If the pageLSN on the affected data page (on disk) is <em>less than</em> the LSN of the current log record, it means the change described by the log record was <em>not</em> written to disk before the crash. In this case, the change is re-applied (redone) to the page in memory.</li><li>If the pageLSN on disk is <em>greater than or equal to</em> the LSN of the current log record, it means the change was already on disk. The log record is skipped for redo.</li><li><strong>Update LSNs:</strong> The pageLSN of the modified page in memory is updated to the LSN of the redone log record. The goal of this phase is to bring the database to the exact state it was in at the time of the crash. This process repeats history, ensuring that all changes, whether committed or uncommitted, are applied.</li></ul><p><strong>3. Undo Phase:</strong></p><ul><li><strong>Rollback Uncommitted Transactions:</strong> After redoing history, the database is in the state it was at the moment of the crash. Now, the effects of any transactions that were active (uncommitted) at the time of the crash must be undone.</li><li><strong>Scan Backward:</strong> The undo phase scans the log <em>backward</em> from the LSNs of the latest operations of active transactions identified in the Analysis phase.</li><li><strong>Undo Changes:</strong> For each log record encountered that belongs to an uncommitted transaction, the operation described by its undo information is performed.</li><li><strong>Write Compensation Log Records (CLRs):</strong> For every undo operation, a special <strong>Compensation Log Record (CLR)</strong> is written to the log. A CLR describes an undo operation and contains a UndoNextLSN field pointing to the next log record that needs to be undone for that transaction. CLRs are themselves idempotent and never undone. This ensures that if the system crashes during the undo phase, recovery can simply redo the CLRs.</li><li><strong>Abort Transaction:</strong> Once all operations for an uncommitted transaction are undone, an abort log record is written for that transaction.</li></ul><p>This three-phase approach makes ARIES very robust. It can handle multiple crashes, including crashes during recovery itself, thanks to CLRs and the pageLSN mechanism.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tSIh4ByzZ0tshrVF60fsvg.png" /></figure><h3>Dirty Page Tracking and Buffer Pool Management</h3><p>The <strong>buffer pool</strong> (also known as the data cache) is a crucial component in database systems. It’s an in-memory cache that holds copies of data pages from disk. When a database needs to read or write a page, it first checks if the page is already in the buffer pool.</p><p>WAL integrates tightly with buffer pool management:</p><ul><li><strong>Dirty Pages:</strong> When a page in the buffer pool is modified, it becomes “dirty.” The database system tracks these dirty pages.</li><li><strong>recLSN (Recovery LSN):</strong> For each dirty page, the system stores its recLSN. This recLSN is the LSN of the <em>earliest</em> log record that modified this page since it was last written to disk. This is vital during recovery for the Redo phase to know if a change needs to be re-applied.</li><li><strong>No-Force Policy:</strong> The “no-force” aspect of ARIES means that dirty pages are not immediately written to disk when a transaction commits. Instead, they are flushed periodically during checkpoints or when the buffer pool needs space (e.g., using a LRU-like policy). This reduces disk I/O and improves performance.</li></ul><p><strong>Steal/No-Steal Policy:</strong></p><ul><li><strong>Steal:</strong> A database system uses a “steal” policy if it allows a dirty page to be written to disk <em>before</em> the transaction that dirtied it commits. This is common in ARIES, as it allows buffer pool pages to be reused quickly, but it means that the undo mechanism must be robust enough to handle uncommitted changes on disk.</li><li><strong>No-Steal:</strong> A “no-steal” policy prevents dirty pages from being written to disk until the transaction that dirtied them commits. This simplifies undo but can lead to larger buffer pool requirements and potentially more blocking. ARIES typically uses “steal, no-force” for maximum concurrency and performance.</li></ul><h3>Parallel Recovery Techniques: Speeding Up the Reboot</h3><p>For very large databases, or databases with high transaction throughput, traditional single-threaded recovery can take an unacceptably long time. <strong>Parallel recovery techniques</strong> are designed to reduce this downtime.</p><h3>The Need for Speed</h3><p>The primary motivation for parallel recovery is to minimize the Mean Time To Recovery (MTTR) after a crash. As databases grow in size and complexity, and as the volume of log data increases, a serial recovery process becomes a bottleneck.</p><h3>How Parallel Recovery Works</h3><p>Parallel recovery typically involves parallelizing the Redo phase and, sometimes, the Undo phase.</p><p><strong>Parallel Redo:</strong></p><ul><li><strong>Log Partitioning:</strong> The log file can be logically or physically partitioned. Multiple threads or processes can then concurrently scan different segments of the log during the Redo phase.</li><li><strong>Page Parallelism:</strong> Even if the log is scanned serially, different redo threads can operate on different data pages. As log records are processed, a thread might identify a page to be redone. If that page is not currently being processed by another thread, the redo operation can proceed in parallel.</li><li><strong>LSN-based Ordering:</strong> The key challenge is maintaining the correct LSN order for updates to the <em>same</em> page. This often involves per-page locks or atomic operations on the pageLSN to ensure that a later log record&#39;s change isn&#39;t applied before an earlier one on the same page.</li></ul><p><strong>Parallel Undo:</strong></p><ul><li>Parallelizing the undo phase is more complex due to dependencies between undo operations (e.g., a CLR’s UndoNextLSN chain). However, it can be achieved by partitioning active transactions among different undo threads, with careful coordination to manage page contention.</li><li><strong>Batching:</strong> Log records can be batched and processed in parallel before applying changes to pages.</li></ul><p>Challenges in implementing parallel recovery include:</p><ul><li><strong>Synchronization:</strong> Ensuring correct ordering of operations and preventing race conditions when multiple threads modify shared data structures (like the DPT or data pages).</li><li><strong>Resource Contention:</strong> Managing contention for CPU, I/O, and memory resources among recovery threads.</li><li><strong>Complexity:</strong> The algorithms for parallel recovery are significantly more complex than their serial counterparts.</li></ul><p>Modern database systems use sophisticated parallel recovery techniques to minimize downtime and provide high availability.</p><h3>Conclusion: The Foundation of Reliable Data</h3><p>Write-Ahead Logging (WAL) is key to database durability and consistency, ensuring changes are logged before they’re applied. Through mechanisms like LSNs, buffer pools, and ARIES recovery, WAL enables reliable crash recovery. As data demands grow, WAL remains vital to high-performance systems. Understanding it is essential for anyone in data management.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71f6d98f0e23" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Deep Dive into Zero-Copy Networking and io_uring]]></title>
            <link>https://medium.com/@jatinumamtora/a-deep-dive-into-zero-copy-networking-and-io-uring-78914aa24029?source=rss-24bbf2ff7048------2</link>
            <guid isPermaLink="false">https://medium.com/p/78914aa24029</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[iouring]]></category>
            <category><![CDATA[performance-engineering]]></category>
            <category><![CDATA[zero-copy]]></category>
            <category><![CDATA[kernel]]></category>
            <dc:creator><![CDATA[Jatin mamtora]]></dc:creator>
            <pubDate>Sun, 29 Jun 2025 01:32:42 GMT</pubDate>
            <atom:updated>2025-06-29T04:07:32.388Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Silent Performance Killer: Why Your App Might Be Slower Than You Think !!!</h3><p>In the high-stakes world of modern software, speed isn’t just a feature; it’s a fundamental requirement. There’s a sneaky culprit often lurking in the shadows, silently choking your application’s performance: <strong>Inefficient Input/Output (I/O) operations.</strong></p><p><strong>Think about it:</strong> every time your application reads data from a file, writes to a database, or sends information over a network, it’s performing an I/O operation. Traditionally, these operations involve a lot of overhead — specifically, redundant data copying and constant “context switches” between your application’s world (user space) and the operating system’s world (kernel space). Each of these steps eats up precious CPU cycles and memory bandwidth, acting like speed bumps on the superhighway of your data.</p><pre>+-------------+    +-------------+    +--------------+    +------------+<br>| Application | -&gt; | Syscall     | -&gt; | Kernel Buffer| -&gt; | Device I/O |<br>| (User Space)|    | (Context)   |    | (Kernel)     |    | (Disk/Net) |<br>+-------------+    +-------------+    +--------------+    +------------+<br>       ^                                                      |<br>       |&lt;---------------- Context Switch Back ----------------|</pre><p>This problem becomes even more acute in today’s high-speed network environments. your CPU spends most of its time just shuffling data around rather than actually processing it, that powerful link becomes a bottleneck, and your application can’t keep up.</p><p>Enter <strong>Zero-Copy Networking</strong> and <strong>io_uring</strong>. These aren&#39;t just buzzwords; they&#39;re revolutionary approaches designed to fundamentally transform how Linux handles I/O, promising to unlock unprecedented levels of performance. Let&#39;s peel back the layers and see how.</p><h3>Demystifying Zero-Copy: The Art of Not Copying</h3><p>The name “zero-copy” might sound like magic, but it’s pure engineering elegance. At its core, zero-copy is about moving data between different parts of your system <strong>without the CPU having to perform the actual copying.</strong></p><h3>The Problem: Traditional I/O’s Memory Dance</h3><p>To truly appreciate zero-copy, let’s visualize the “dance” data performs in a traditional I/O operation, like sending a file over the network:</p><ol><li><strong>User App to Kernel:</strong> Your application calls read(). The CPU copies data from a kernel buffer (where it landed from the disk) into your application&#39;s buffer.</li><li><strong>Kernel to User App:</strong> Your application calls write(). The CPU copies data from your application&#39;s buffer into a kernel &quot;socket&quot; buffer.</li><li><strong>Kernel to NIC:</strong> Finally, the CPU might copy data from the socket buffer to the Network Interface Card (NIC) for transmission.</li></ol><p><strong>The result?</strong> Multiple redundant CPU copies and frequent, costly “context switches” between user and kernel space. Each copy adds latency and consumes valuable CPU cycles and memory bandwidth.</p><h3>The Solution: Smart Moves with DMA and Memory Mapping</h3><p>Zero-copy techniques primarily leverage two powerful mechanisms:</p><ul><li><strong>Direct Memory Access (DMA):</strong> This is the superhero of data movement. DMA controllers are specialized hardware components that allow peripherals (like your NIC or disk controller) to directly access system memory <em>without</em> involving the CPU. Data flows straight from the device to memory, or memory to the device, like a dedicated express lane.</li><li><strong>Memory-Mapping (MMU):</strong> Imagine two people needing to read the same book. Instead of making two copies, they agree to read from the <em>same physical book</em>. Memory mapping works similarly: it allows different virtual memory addresses (e.g., one in user space, one in kernel space) to point to the <strong>same physical memory location</strong>. This means data can be “shared” without being copied.</li></ul><h3>Linux’s Journey Towards Zero-Copy: A Brief History</h3><p>Linux has been on a continuous quest for I/O efficiency, leading to several zero-copy advancements:</p><ul><li><strong>mmap() (Memory Map):</strong> An early step. It allows a file&#39;s content in the kernel&#39;s page cache to be directly mapped into your application&#39;s address space. This eliminates one CPU copy (kernel buffer to user buffer) for reading files. However, data still often needs to be copied into a socket buffer for network sends.</li><li><strong>sendfile() (Streamlined File Transfer):</strong> Introduced for direct file-to-socket transfers. It replaced separate read() and write() calls with a single system call. This eliminates two context switches and avoids copying data into user space at all! Modern NICs can even use &quot;DMA Gather Copy&quot; to grab data directly from the kernel buffer, potentially eliminating another CPU copy.</li><li><strong>MSG_ZEROCOPY (Socket Optimization):</strong> A socket option aimed at reducing copies for network transmission. While effective, io_uring&#39;s approach has proven to be significantly more performant, especially with &quot;fixed&quot; buffers.</li></ul><p>These techniques were crucial, but they often tackled specific bottlenecks. They were incremental improvements. Now, let’s talk about the game-changer: io_uring.</p><h3>io_uring: Linux&#39;s Asynchronous I/O Powerhouse</h3><p>io_uring isn&#39;t just another I/O API; it&#39;s a fundamental rethinking of how applications interact with the Linux kernel for I/O. It was designed from the ground up to overcome the limitations of older interfaces like epoll and the notoriously tricky &quot;Linux AIO&quot;.</p><h3>Why We Needed a New Ring: The epoll Problem</h3><p>Before io_uring, epoll was the go-to for high-concurrency I/O. It&#39;s &quot;readiness-based,&quot; meaning it tells you <em>when</em> a file descriptor (like a network socket) is ready for I/O (e.g., data arrived, or you can write). But you still had to make a separate read() or write() system call to <em>actually</em> perform the I/O. This meant:</p><ul><li><strong>Multiple System Calls:</strong> Each I/O operation still required multiple system calls and context switches.</li><li><strong>“Is it Ready?” vs. “It’s Done!”:</strong> epoll just tells you it&#39;s ready; io_uring tells you it&#39;s <em>done</em>. This completion-based model is far more efficient.</li></ul><p>io_uring sweeps these issues away, providing a truly asynchronous, high-performance API that works consistently across <em>all</em> types of I/O – cached files, direct-access files, and even blocking sockets.</p><h3>The Core Architecture: Two Rings to Rule Them All</h3><p>The magic of io_uring lies in its name: <strong>two circular &quot;ring buffers&quot; shared directly between user space and kernel space.</strong></p><ul><li><strong>Submission Queue (SQ):</strong> Your application writes I/O requests (called <strong>SQEs — Submission Queue Entries</strong>) into this ring. Think of it as your “to-do list” for the kernel. The kernel then reads and processes these requests.</li><li><strong>Completion Queue (CQ):</strong> The kernel writes the results of completed I/O operations (called <strong>CQEs — Completion Queue Events</strong>) into this ring. This is where your application checks for “done” notifications.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*n0z1f6-YlD4LHK3H" /><figcaption>io-uring</figcaption></figure><p>This shared memory design is revolutionary. Instead of costly system calls for every interaction, user space and kernel space can communicate almost directly, largely avoiding data copies and context switches.</p><h3>How It Works: SQEs and CQEs</h3><p>The io_uring workflow is elegant and powerful:</p><ol><li><strong>Setup:</strong> You create an io_uring instance and mmap() (memory map) its SQ and CQ buffers into your application&#39;s memory.</li><li><strong>Crafting Requests (SQEs):</strong> For each I/O operation (e.g., reading a file), you prepare an io_uring_sqe structure. This structure contains all the details:</li></ol><ul><li>opcode: What kind of operation (e.g., IORING_OP_READ).</li><li>fd: The file descriptor.</li><li>addr, len, off: Buffer address, length, and file offset.</li><li>user_data: <strong>Crucially</strong>, a unique value you provide. This value is returned with the completion, allowing you to link a completion back to its original request.</li></ul><p><em>(While you can manually fill </em><em>struct io_uring_sqe, libraries like </em><em>liburing provide helpful wrappers like </em><em>io_uring_prep_read() that simplify this.)</em></p><p>3. <strong>Batching and Submission:</strong> You can add <em>many</em> SQEs to the ring without immediately telling the kernel. Once you have a batch ready, you make a single io_uring_enter() system call. This one syscall tells the kernel: &quot;Hey, I&#39;ve got a bunch of work for you!&quot;</p><p>4. <strong>Reaping Results (CQEs):</strong> The kernel processes your requests. When an operation finishes, it places a io_uring_cqe (Completion Queue Event) into the CQ. This CQE contains:</p><ul><li>user_data: Your unique ID, so you know which request finished.</li><li>res: The result. A positive value means success (e.g., bytes read); a negative value is an error (like errno but directly in res).</li><li>flags: Additional info.</li></ul><p><em>(Important: Operations can complete in any order, so </em><em>user_data is vital for tracking.)</em></p><p>5.<strong> Submission Queue Polling (SQPOLL): The “Zero System Call” Mode:</strong> For the absolute highest throughput, io_uring offers an optional SQPOLL mode. A kernel thread continuously <em>polls</em> the SQ for new entries. In this mode, if you have a steady stream of I/O, your application might not need to make <em>any</em> system calls to submit new requests – just manipulate the shared ring buffers directly!</p><h3>True Zero-Copy: Pinning Memory for Direct Hardware Access</h3><p>While shared rings reduce system call overhead, true zero-copy is achieved through <strong>memory registration</strong>. This tells the kernel: “Hey, this memory isn’t going anywhere; you can directly access it!”</p><ul><li><strong>io_uring_register_buffers(): Pinning Your Memory:</strong> You can register pre-allocated user-space memory buffers (e.g., from malloc or mmap) with the kernel. The kernel &quot;pins&quot; these memory pages, preventing them from being swapped out, and establishes a fixed mapping.</li><li><strong>Using Fixed Buffers (</strong><strong>IORING_OP_READ_FIXED, </strong><strong>IORING_OP_WRITE_FIXED):</strong> Once registered, you reference these buffers by their index in your SQEs. The kernel now has direct, pinned access to this memory. This eliminates the need for repeated mapping or copying for each I/O operation. Data can flow directly between your hardware (disk, NIC) and your registered user memory without CPU intervention!</li><li><strong>Buffer Lifecycle:</strong> Remember, registered buffers must remain valid until all operations using them are complete. io_uring provides mechanisms to track this.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mVBmKqiU0TiTokMHFJsR1w.png" /></figure><p>This “fixed” approach is a key reason io_uring&#39;s zero-copy can outperform older methods. It&#39;s not just about avoiding <em>copies</em>, but also avoiding the <em>setup and teardown</em> of memory mappings for every single I/O.</p><h3>Kernel Bypass and io_uring: A Symbiotic Relationship?</h3><p>When performance is paramount, discussions often turn to “kernel bypass” — techniques to circumvent the operating system’s traditional I/O stack. io_uring plays a fascinating role here, offering a hybrid approach.</p><h3>The Allure of Kernel Bypass: Why Go Around the Kernel?</h3><p>The kernel’s network stack is robust and general-purpose, but it comes with overheads: context switches, multiple data copies, interrupt processing, and queuing delays. For applications demanding absolute maximum throughput (e.g., millions of packets per second), these overheads become prohibitive.</p><p><strong>Traditional Kernel Bypass Players:</strong></p><ul><li><strong>DPDK (Data Plane Development Kit):</strong> A powerful framework that takes over a network card, moving its driver into user space. It offers extreme speed but means the kernel no longer “sees” traffic on that NIC, leading to operational complexities.</li><li><strong>Netmap, Snabbswitch, PF_RING ZC, OpenOnload:</strong> Other specialized solutions, often involving kernel modules or user-space drivers to achieve similar bypass.</li></ul><p><strong>These methods typically require dedicating an entire NIC to the bypass application.</strong></p><h3>io_uring&#39;s Approach: Zero-Copy Networking with IORING_OP_RECV_ZC and IORING_OP_SEND_ZC</h3><p>io_uring extends its zero-copy magic to networking with explicit operations:</p><ul><li><strong>IORING_OP_SEND_ZC (Zero-Copy Send):</strong> This allows truly asynchronous, zero-copy network sends. Combined with registered buffers, data can be transmitted directly from user memory to the NIC without any intermediate CPU copies.</li><li><strong>Zero-Copy Receive (ZC Rx):</strong> This feature aims to deliver incoming packet data directly into user-space memory, eliminating kernel-to-user copies on the receive path. It often requires specific NIC hardware features (like header/data split) to work efficiently.</li></ul><p><strong>A Key Distinction:</strong> Unlike full kernel bypass solutions like DPDK, io_uring ZC Rx <em>still processes packet headers through the kernel&#39;s TCP stack</em>. This means the kernel retains its role in managing the network connection and protocol headers, even as the payload bypasses copying.</p><p>io_uring offers a &quot;hybrid bypass.&quot; It provides significant performance gains while remaining integrated within the Linux kernel. This makes it more convenient and less intrusive than full bypass solutions. While DPDK might still offer the absolute maximum raw speed in certain niche scenarios, io_uring is rapidly closing the gap, making it an increasingly attractive option for high performance with better system compatibility and manageability. The choice depends on whether you need absolute raw throughput (DPDK) or high performance with better kernel integration (io_uring).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*52sZTy_nvZ816iRJmHZX_Q.png" /></figure><h3>The Speed Test: io_uring vs. epoll/select</h3><p>So, is io_uring always faster? Not necessarily, but it definitely offers a path to superior performance under the right conditions.<br>The Nuance of “Free Performance”</p><p>Initial excitement around io_uring led to claims of &quot;free&quot; 60% or even 99% performance gains. However, real-world benchmarks show a more nuanced picture. The benefits aren&#39;t always automatic.</p><p>Key factors influencing io_uring&#39;s performance:</p><ol><li><strong>System Call Context Switching Overhead (</strong><strong>s):</strong> The time it takes to switch between user and kernel space. This is a significant cost, especially with modern CPU vulnerability mitigations enabled (which can increase s from ~230ns to ~700ns!).</li><li><strong>Kernel-Side Logic Overhead (</strong><strong>w):</strong> The actual time the kernel spends performing the I/O operation (e.g., send() or recv()).</li><li><strong>io_uring Framework Overhead (</strong><strong>o):</strong> The internal overhead of io_uring itself.</li><li><strong>io_uring Batch Quantity (</strong><strong>n):</strong> <strong>This is the biggest differentiator!</strong> The number of io_uring operations you submit in a single io_uring_enter() call.</li></ol><h3>Where io_uring Truly Shines: Batching is King!</h3><ul><li><strong>Low Batch Size (</strong><strong>n=1):</strong> If you only submit one operation at a time, io_uring can actually be <em>slower</em> than epoll. Why? Because io_uring has some internal overhead (o) that might be greater than epoll&#39;s kernel logic overhead (w) for a single operation. You&#39;re losing the primary benefit: amortizing syscall cost.</li><li><strong>High Batch Size (</strong><strong>n &gt; 1):</strong> This is where io_uring sings! When you submit many operations (n is large) in a single io_uring_enter() call, the cost of that one system call (s) is spread across all those operations. This &quot;amortization&quot; effect drastically reduces the per-operation overhead, making io_uring significantly faster than epoll. The more you batch, the better io_uring looks.</li><li><strong>CPU Vulnerability Mitigations:</strong> Since these mitigations increase the cost of context switching (s), io_uring&#39;s ability to reduce or eliminate s (via batching or SQ polling) becomes even more critical. In these environments, io_uring shows even greater gains.</li></ul><p><strong>Real-World Wins:</strong></p><ul><li><strong>High IOPS:</strong></li><li><strong>Extreme Throughput</strong></li><li><strong>Lower Latency</strong></li></ul><p>The takeaway: io_uring isn&#39;t a silver bullet that magically makes everything faster. Its performance superiority is highly dependent on your workload, especially your ability to batch requests. For high-concurrency, high-throughput applications, it&#39;s a game-changer. For simple, unbatched I/O, epoll might still be competitive. Always benchmark for your specific use case!</p><h3>Real-World Implementation Challenges and Best Practices</h3><p>While io_uring promises immense power, adopting it isn&#39;t without its complexities. It&#39;s a new frontier that requires developers to learn new paradigms.</p><h3>The Learning Curve: Navigating a New API</h3><p>io_uring introduces a fundamentally different way of thinking about I/O. The raw interface is low-level and complex.</p><ul><li><strong>liburing is Your Friend:</strong> Fortunately, the liburing user-space library exists to abstract away much of this complexity. It&#39;s the recommended way for most developers to interact with io_uring. Even with liburing, a conceptual shift is needed from traditional synchronous or readiness-based I/O to a truly asynchronous, completion-based model.</li></ul><h3>Kernel Version Dependencies: Keep Your Kernel Fresh!</h3><p>io_uring is a rapidly evolving Linux kernel subsystem, first introduced in kernel 5.1. Many advanced features (like accept() in io_uring, or zero-copy networking) were added in later kernel versions. You&#39;ll need to ensure your deployment environment runs a sufficiently recent kernel to use the features you need.</p><h3>Conclusion: The Future of High-Performance I/O on Linux</h3><p>io_uring isn&#39;t just an improvement; it&#39;s a fundamental shift in Linux I/O. Its innovative design, centered on shared ring buffers, drastically reduces overhead, enables true zero-copy operations, and provides a unified, flexible API for a wide range of I/O types.</p><h3>When to Consider io_uring for Your Applications</h3><ul><li><strong>High I/O Demands:</strong> If your application is I/O-bound and needs extremely low latency and high throughput (e.g., databases like RocksDB, PostgreSQL, web servers like Nginx, network proxies, distributed log systems like Redpanda).</li><li><strong>CPU-Bound by I/O Overhead:</strong> If profiling shows your CPU is spending too much time on context switching or data copying for I/O, especially with CPU vulnerability mitigations enabled.</li><li><strong>Fine-Grained Control:</strong> When you need precise control over I/O scheduling, buffer management, and the ability to chain operations for complex, interdependent workflows.</li></ul><p><strong>Found this helpful?</strong> Drop a share on Twitter or Hacker News or Linkedin tagging me — or just tell a fellow dev struggling with epoll that it’s time for an upgrade! Comment down, always open for curious discussion !!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78914aa24029" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Uploading Base64 URI/String  to Cloudinary with Node.js — all cloudinary solution!]]></title>
            <link>https://medium.com/@jatinumamtora/uploading-base64-uri-string-to-cloudinary-with-node-js-all-cloudinary-solution-38121cac9048?source=rss-24bbf2ff7048------2</link>
            <guid isPermaLink="false">https://medium.com/p/38121cac9048</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[cloudinary]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[base64]]></category>
            <category><![CDATA[cloud]]></category>
            <dc:creator><![CDATA[Jatin mamtora]]></dc:creator>
            <pubDate>Wed, 28 Feb 2024 18:47:02 GMT</pubDate>
            <atom:updated>2024-11-21T07:04:34.485Z</atom:updated>
            <content:encoded><![CDATA[<h3>Uploading Base64 URI/String of an Image to Cloudinary with Node.js That too without Server storage !!</h3><p>Image handling is an essential aspect of modern web applications. Often, images are processed as Base64-encoded strings, especially in AI workflows where models produce or consume such formats. However, Base64 encoding comes with a challenge — its size. Since Base64 strings are larger than the original binary data, they increase storage requirements, making efficient handling critical.</p><p>In this tutorial, we’ll explore a <strong>streamlined approach to uploading Base64-encoded images directly to Cloudinary using Node.js</strong>. This method bypasses the need for server-side storage, making your workflow faster and more scalable.</p><h3>Why Base64 Strings?</h3><ul><li>Base64 encoding is often used to represent binary data in a text-safe format, suitable for APIs, JSON, or embedding into HTML.</li><li>AI models typically use Base64 strings for images, as they cannot process raw binary data directly.</li></ul><h3>The Challenge: Efficient Storage</h3><ul><li><strong>Base64 strings are not just “normal strings.”</strong> They are 33% larger than the original binary file, which can significantly increase storage and bandwidth requirements.</li><li>Storing such encoded data in its current form can strain server resources and inflate database storage costs.</li></ul><h3>The Solution: Cloudinary + Node.js</h3><p>Cloudinary, a powerful cloud-based media management service, simplifies this process. By uploading Base64-encoded images directly to Cloudinary:</p><ul><li>You eliminate the need for server storage.</li><li>You leverage Cloudinary’s robust tools for optimization, transformation, and delivery of media files.</li></ul><p>This tutorial will guide you through the following:</p><ol><li><strong>Setting up your Node.js application</strong> for Base64 uploads.</li><li><strong>Configuring Cloudinary</strong> for seamless integration.</li><li><strong>Uploading images with minimal effort</strong> while ensuring scalability.</li></ol><p>By the end of this tutorial, you’ll have a lightweight, efficient image upload solution that’s perfect for AI, web apps, and beyond. Let’s dive in and make image uploads hassle-free!</p><h3>Prerequisites</h3><p>Before we begin, make sure you have the following set up:</p><ol><li>Cloudinary Account: If you haven’t already, sign up for a <a href="https://cloudinary.com/users/register_free">Cloudinary</a> account. This will provide you with the necessary credentials to interact with the Cloudinary API.</li><li>Node.js and npm: Ensure that Node.js and npm are installed on your machine. If not, you can download them from <a href="https://nodejs.org/">nodejs.org</a>.</li><li>Cloudinary npm Package: Install the Cloudinary npm package in your project directory:</li></ol><pre>npm install cloudinary</pre><h3>Setting Up Cloudinary Configuration</h3><p>ow, let’s configure Cloudinary in your Node.js application.</p><ol><li>API Key and Secret: Log in to your Cloudinary account and navigate to the Dashboard. Find your API Key and Secret under the Account Details section.</li><li>Configure Cloudinary in Node.js: Use your API Key and Secret to configure Cloudinary in your Node.js application. Here’s a sample configuration:</li></ol><pre>const cloudinary = require(&#39;cloudinary&#39;).v2;<br><br>cloudinary.config({<br>  cloud_name: &#39;your_cloud_name&#39;,<br>  api_key: &#39;your_api_key&#39;,<br>  api_secret: &#39;your_api_secret&#39;<br>});</pre><p>Now <strong>frontend</strong> will give you <strong>Base64</strong> encoding in <em>req.body </em>like this:</p><pre>data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/4gHYSUNDX1BST0ZJTEUAAQEAAAHIAAAAAAQwAABtbnRyUkdCIFhZWiAH4AABAAEAAAAAAABhY3NwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAA9tYAAQAAAADTLQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAlkZXNjAAAA8AAAACRyWFlaAAABFAAAABRnWFlaAAABKAAAABRiWFlaAAABPAAAABR3dHB0AAABUAAAABRyVFJDAAABZAAAAChnVFJDAAABZAAAAChiVFJDAAABZAAAAChjcHJ0AAABjAAAADxtbHVjAAAAAAAAAAEAAAAMZW5VUwAAAAgAAAAcAHMAUgBHAEJYWVogAAA</pre><p><strong>Now if you directly pass this data in NodeJs server it wont take it as body-parser or express.json() have their limit for 1 mb so you need to increase that so below is implementation :</strong></p><h3>Server Setup:</h3><pre>const express = require(&#39;express&#39;);<br>const cloudinary = require(&#39;cloudinary&#39;).v2;<br>var bodyParser = require(&#39;body-parser&#39;);<br><br>//This is the thing that is discussed above **<br>app.use(bodyParser.json({limit: &#39;50mb&#39;}));<br>app.use(bodyParser.urlencoded({limit: &#39;50mb&#39;, extended: true}));<br><br>const app = express();<br>const port = 3000;<br><br>// Middleware to parse JSON in the request body<br>app.use(express.json());<br><br>// Handle base64 image upload<br>app.post(&#39;/upload-base64&#39;, async (req, res) =&gt; {<br>  try {<br>    const dataURI = req.body.dataURI;<br><br>    const result = await cloudinary.uploader.upload(dataURI, {<br>//optional things just if you want some storage optimization<br>      overwrite: true,<br>      invalidate: true,<br>      width: 810, height: 456, crop: &quot;fill&quot;<br>    });<br><br>    res.json(result);<br>  } catch (error) {<br>    console.error(error);<br>    res.status(500).json({ error: &#39;Error uploading to Cloudinary&#39; });<br>  }<br>});<br><br>// Start the server<br>app.listen(port, () =&gt; {<br>  console.log(`Server is running on http://localhost:${port}`);<br>});</pre><p>If you receive any error make sure you have <strong><em>body-parser</em></strong> dependency installed.</p><h3>Conclusion</h3><p>You’ve just learned how to upload base64 encoded images directly to Cloudinary using Node.js. This method provides a convenient way to handle image uploads without the need for server storage. Feel free to adapt and customize the code for your specific use case.</p><p>Previous blog related to <a href="https://medium.com/@jatinumamtora/uploading-images-directly-to-cloudinary-from-a-form-in-node-js-6f3a087481b0"><strong>cloudinary</strong></a><strong> (click here).</strong></p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38121cac9048" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Uploading Images Directly to Cloudinary from a Form in Node.js]]></title>
            <link>https://medium.com/@jatinumamtora/uploading-images-directly-to-cloudinary-from-a-form-in-node-js-6f3a087481b0?source=rss-24bbf2ff7048------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f3a087481b0</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[storage]]></category>
            <category><![CDATA[cloudinary]]></category>
            <category><![CDATA[node-js-tutorial]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Jatin mamtora]]></dc:creator>
            <pubDate>Wed, 28 Feb 2024 18:26:16 GMT</pubDate>
            <atom:updated>2024-02-28T18:26:16.900Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In this tutorial, we’ll explore how to seamlessly upload images from a form to Cloudinary using Node.js. By bypassing the need to store images on your server, we can improve efficiency and save storage space. Let’s get started!</p><h3>Prerequisites</h3><p>Before diving into the code, make sure you have the following:</p><ol><li>Cloudinary Account: Sign up for a <a href="https://cloudinary.com/users/register_free">Cloudinary</a> account. Cloudinary is a cloud-based image and video management solution.</li><li>Node.js and npm: Install Node.js and npm on your machine. You can download them from <a href="https://nodejs.org/">nodejs.org</a>.</li><li>Cloudinary npm Package: Install the Cloudinary npm package by running the following command in your project directory:</li></ol><pre>npm install cloudinary</pre><h3>Setting Up Cloudinary Configuration</h3><p>Now, let’s configure Cloudinary in your Node.js application.</p><ol><li>API Key and Secret: Log in to your Cloudinary account and navigate to the Dashboard. Find your API Key and Secret under the Account Details section.</li><li>Configure Cloudinary in Node.js: Use your API Key and Secret to configure Cloudinary in your Node.js application. Here’s a sample configuration:</li></ol><pre>const cloudinary = require(&#39;cloudinary&#39;).v2;<br><br>cloudinary.config({<br>  cloud_name: &#39;your_cloud_name&#39;,<br>  api_key: &#39;your_api_key&#39;,<br>  api_secret: &#39;your_api_secret&#39;<br>});<br></pre><h3>Creating a Form for Image Upload</h3><p>Now, let’s create a simple HTML form for image upload.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>  &lt;meta charset=&quot;UTF-8&quot;&gt;<br>  &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>  &lt;title&gt;Image Upload&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>  &lt;form action=&quot;/upload&quot; method=&quot;post&quot; enctype=&quot;multipart/form-data&quot;&gt;<br>    &lt;input type=&quot;file&quot; name=&quot;image&quot; accept=&quot;image/*&quot;&gt;<br>    &lt;button type=&quot;submit&quot;&gt;Upload&lt;/button&gt;<br>  &lt;/form&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><h3>Handling Image Upload in Node.js</h3><p>Now, let’s handle the image upload on the server side using Node.js and Cloudinary.</p><pre>const express = require(&#39;express&#39;);<br>const multer = require(&#39;multer&#39;);<br>const cloudinary = require(&#39;cloudinary&#39;).v2;<br><br>const app = express();<br>const port = 3000;<br><br>// Configure Cloudinary (use your own cloud_name, api_key, and api_secret)<br>cloudinary.config({<br>  cloud_name: &#39;your_cloud_name&#39;,<br>  api_key: &#39;your_api_key&#39;,<br>  api_secret: &#39;your_api_secret&#39;<br>});<br><br>// Set up Multer for handling file uploads<br>const storage = multer.memoryStorage();<br>const upload = multer({ storage: storage });<br><br>// Handle image upload<br>app.post(&#39;/upload&#39;, upload.single(&#39;image&#39;), (req, res) =&gt; {<br>  if (!req.file) {<br>    return res.status(400).json({ error: &#39;No file uploaded&#39; });<br>  }<br><br>  cloudinary.uploader.upload_stream({ resource_type: &#39;auto&#39; }, (error, result) =&gt; {<br>    if (error) {<br>      console.log(error);<br>      return res.status(500).json({ error: &#39;Error uploading to Cloudinary&#39; });<br>    }<br>    res.json({ public_id: result.public_id, url: result.secure_url });<br>  }).end(req.file.buffer);<br>});<br><br>// Start the server<br>app.listen(port, () =&gt; {<br>  console.log(`Server is running on http://localhost:${port}`);<br>});</pre><h3>Conclusion</h3><p>Congratulations! You’ve successfully set up a Node.js application to directly upload images from a form to Cloudinary without storing them on your server. This approach not only simplifies the process but also helps in saving server storage.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f3a087481b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>