<?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 Balkrishan Nagpal on Medium]]></title>
        <description><![CDATA[Stories by Balkrishan Nagpal on Medium]]></description>
        <link>https://medium.com/@balkrishan-nagpal?source=rss-a5c7b38e8e3c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*ej3PNMGRScwtmrrtQaoWOA.png</url>
            <title>Stories by Balkrishan Nagpal on Medium</title>
            <link>https://medium.com/@balkrishan-nagpal?source=rss-a5c7b38e8e3c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 17:17:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@balkrishan-nagpal/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[How to Precisely Count Hibernate Queries and Why Hibernate stats can be misleading]]></title>
            <link>https://balkrishan-nagpal.medium.com/how-to-precisely-count-hibernate-queries-and-hibernate-stats-can-be-misleading-3ce516afcc34?source=rss-a5c7b38e8e3c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ce516afcc34</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[hibernate]]></category>
            <category><![CDATA[jpa]]></category>
            <dc:creator><![CDATA[Balkrishan Nagpal]]></dc:creator>
            <pubDate>Mon, 18 May 2026 23:43:45 GMT</pubDate>
            <atom:updated>2026-05-18T23:45:09.799Z</atom:updated>
            <content:encoded><![CDATA[<p>Performance tuning in a Spring boot application usually begins with one nagging suspicion: <em>The N+1 Query Problem.</em> You look at your service, and you wonder: “Is this one JPA call, or is it triggering fifty hidden database round-trips?”</p><p>To figure this out, the standard advice is to use Hibernate’s built-in Statistics. But if you try to use this to profile a specific method in a real-world application, you’ll quickly find the numbers don&#39;t add up.</p><p>In this guide, we’ll explore why the default statistics fail in multi-threaded environments, why stats.clear() is a dangerous anti-pattern, and how to implement a surgical, thread-safe approach to query profiling.</p><h4>The “Standard” Way: Hibernate Statistics</h4><p>Hibernate provides a powerful monitoring tool out-of-the-box. By enabling spring.jpa.properties.hibernate.generate_statistics=true, you get access to a global Statistics object.</p><p>You can retrieve it by unwrapping the SessionFactory:</p><pre>SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);<br>Statistics stats = sessionFactory.getStatistics();<br>long totalQueries = stats.getQueryExecutionCount();</pre><p><strong>But here is the catch:</strong> Hibernate does not track “queries per method.” It keeps a <strong>cumulative, lifetime counter</strong> of every SQL query executed since the application started.</p><p>If you simply print the number, you will see a massive, constantly increasing integer that tells you nothing about the current operation. To determine how many queries a specific method triggers, you are forced to perform “delta” math: recording the count <em>before</em> your method runs and comparing it to the count <em>after</em> the method finishes.</p><h4>The Snapshot Approach — A False Sense of Security</h4><p>Because Hibernate provides a cumulative total, developers rely on the <strong>Snapshot Pattern</strong> to derive meaning from that number. The goal here is simple: convert a global, ever-increasing counter into a relative measurement of cost.</p><p>The pattern looks like this:</p><pre>// The Snapshot Approach<br>long before = stats.getQueryExecutionCount(); // Take a reading<br>myService.runComplexLogic();                  // Execute the work<br>long after = stats.getQueryExecutionCount();  // Take a second reading<br><br>System.out.println(&quot;Queries run: &quot; + (after - before)); // Calculate the delta</pre><p>This pattern is highly effective in <strong>Unit Tests</strong> or <strong>Single-Threaded environments</strong> (like a local startup script). By capturing the “before” state, you effectively create a baseline, allowing you to isolate the query count to only the lines of code running inside that specific block.</p><p>However, this logic rests on a fatal assumption: <strong>that your application is the only thing running.</strong></p><h4>The Multi-threading Problem: Why the Math Fails</h4><p>The Snapshot pattern is mathematically sound, but it is <strong>environmentally broken</strong>.</p><p>In a modern Spring Boot application, your server is rarely idle. It is serving requests, running background jobs, and handling API calls concurrently.</p><ul><li><strong>Start:</strong> Your thread reads a global query count of <strong>1000</strong>.</li><li><strong>The Operation:</strong> Your code runs and executes <strong>5</strong> queries.</li><li><strong>Concurrency:</strong> Simultaneously, a background thread runs a report that executes <strong>10</strong> queries.</li><li><strong>End:</strong> The global counter is now <strong>1015</strong> (1000 + 5 + 10).</li></ul><p>When you calculate 1015 - 1000, your profiling tool tells you that your method executed <strong>15</strong> queries, when it actually executed <strong>5</strong>. This &quot;noise&quot; from other threads makes the data useless for debugging performance regressions in production.</p><h4>The Drawbacks of SessionFactory.getStatistics()</h4><p>Because Hibernate stats are global and non-isolated, they suffer from three major flaws when used for profiling:</p><ol><li><strong>Race Conditions:</strong> Because you cannot isolate your thread from others, your counts are non-deterministic. You will get different results depending on how busy the server is at that exact millisecond.</li><li><strong>The </strong><strong>stats.clear() Trap:</strong> Some developers try to fix the noise by calling stats.clear() before their method runs. <strong>Do not do this in production.</strong> Calling clear() wipes out the statistics for the <em>entire application</em>. You will destroy the monitoring data for every other user and background process in the system.</li><li><strong>Lack of Granularity:</strong> It’s great for high-level health metrics (e.g., “Is our database slow overall?”), but it is fundamentally incapable of providing surgical, per-operation insights.</li></ol><h4>The Correct Solution: Thread-Local Query Counting</h4><p>If you need to measure queries for <em>exactly</em> one operation, you must step outside the global stats and use a ThreadLocalcounter. This ensures that every thread has its own isolated &quot;notebook&quot; to record its query activity.</p><h4>Step 1: The Thread-Safe Holder</h4><p>We use a ThreadLocal to ensure the count is unique per thread.</p><pre>public class QueryCounter {<br><br>    private static final ThreadLocal&lt;Integer&gt; counter = new ThreadLocal&lt;&gt;();<br><br>   public static void start_(){<br>       counter.set(0);<br>    }<br><br>    public static void increment_(){<br>      if (counter.get() != null) counter.set(counter.get() + 1);<br>    }<br>    public static int get() { return counter.get() == null ? 0 : counter.get(); }<br>    public static void clear() { counter.remove(); }<br>}</pre><h4>Step 2: The Interceptor</h4><p>We need to “hook” into Hibernate so it informs our counter every time a SQL statement is fired.</p><pre>public class QueryCountingInterceptor implements StatementInspector {<br>    @Override<br>    public String inspect(String sql) {<br>        QueryCounter.increment_(); // Only increments the count for THIS thread<br>        return sql;<br>    }<br>}</pre><h4>Step 3: Register the Interceptor</h4><p>Register the interceptor with Hibernate so it starts tracking.</p><pre>@Configuration<br>public class HibernateConfig {<br>    @Bean<br>    public HibernatePropertiesCustomizer hibernatePropertiesCustomizer() {<br>        return hibernateProperties -&gt; {<br>            hibernateProperties.put(&quot;hibernate.session_factory.statement_inspector&quot;, <br>                                   new QueryCountingInterceptor());<br>        };<br>    }<br>}</pre><h4>The Result: Surgical Precision</h4><p>Now, you can profile your method without interference from any other part of the application.</p><pre>public void processOrder() {<br>    QueryCounter.start_();<br>    try {<br>        orderService.save(order); // Hibernate triggers SQL -&gt; Interceptor increments counter<br>    } finally {<br>        System.out.println(&quot;Queries executed: &quot; + QueryCounter.get());<br>        QueryCounter.clear(); // Always clean up to prevent memory leaks<br>    }<br>}</pre><h4>Why this is better:</h4><ul><li><strong>Total Isolation:</strong> Concurrent requests don’t affect each other.</li><li><strong>No Global Side Effects:</strong> You aren’t resetting global state; your app’s main monitoring continues uninterrupted.</li><li><strong>Perfect Accuracy:</strong> You get the exact count of queries triggered by your logic, regardless of how busy your system is.</li></ul><h4>Final Thoughts</h4><p>For high-level production monitoring, stick to <strong>Spring Boot Actuator with Micrometer/Prometheus</strong>. It’s the industry standard for keeping an eye on database latency and connection pool health.</p><p>But, when you need to hunt down those pesky N+1 query bottlenecks in a complex service method, the ThreadLocalapproach is your best friend. It gives you the &quot;surgical&quot; precision needed to optimize your database layer without shooting in the dark.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ce516afcc34" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fixing Slow JPA Batch Jobs: A Deep Dive into flush() and clear()]]></title>
            <link>https://balkrishan-nagpal.medium.com/fixing-slow-jpa-batch-jobs-a-deep-dive-into-flush-and-clear-bcc5134d8225?source=rss-a5c7b38e8e3c------2</link>
            <guid isPermaLink="false">https://medium.com/p/bcc5134d8225</guid>
            <category><![CDATA[jpa]]></category>
            <category><![CDATA[batch-processing]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[performance-tuning]]></category>
            <category><![CDATA[hibernate]]></category>
            <dc:creator><![CDATA[Balkrishan Nagpal]]></dc:creator>
            <pubDate>Sun, 01 Mar 2026 23:31:00 GMT</pubDate>
            <atom:updated>2026-03-01T23:31:00.501Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve ever built a batch job using the Java Persistence API (JPA) and watched in horror as it started fast but gradually slowed to a crawl — or worse, crashed with a java.lang.OutOfMemoryError — you’ve likely hit the “Persistence Context Wall.” This is a classic problem where the very features that make JPA so convenient for web applications become its biggest performance liabilities during large-scale data processing.</p><p>The good news is that this is a solvable problem. To transform your slow, memory-hungry batch job into a scalable and efficient process, you must master the two most important manual controls in the EntityManager: flush() and clear().</p><p>This article will guide you through why this problem happens and how to fix it for good.</p><p><strong>The Problem: Why Your Batch Job is Slow and Crashing</strong></p><p>The root of the problem lies in the JPA <strong>Persistence Context</strong>, often called the first-level cache. Think of it as a mandatory, in-memory workspace that Hibernate (the most common JPA provider) uses to manage the state of your entities during a transaction.</p><p>This workspace is responsible for powerful features like:</p><ul><li><strong>Object Identity:</strong> Ensures that for any given primary key, you get the exact same Java object instance back within a session.</li><li><strong>Lazy Loading:</strong> Defers fetching related entities or large fields until you explicitly access them.</li><li><strong>Dirty Checking:</strong> Automatically detects which entities have been modified and need to be updated in the database.</li></ul><p>While these are fantastic for typical web request-response cycles, they create two massive bottlenecks in a batch job processing thousands or millions of records.</p><p><strong>1. The Memory Hog: The Persistence Context Never Forgets</strong></p><p>The persistence context holds a reference to <strong>every single entity</strong> that you load or save within a transaction.</p><p>Imagine a job that processes one million records. As your code iterates through them, you are not just processing them; you are simultaneously adding all one million entity objects to the persistence context. This causes your application’s heap memory usage to grow linearly until it’s completely exhausted, leading to the dreaded OutOfMemoryError.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T6UfAFm4C9KDdypwX9YVeQ.png" /></figure><p><em>(Conceptual diagram: Memory usage grows with each entity added to the context)</em></p><p><strong>2. The Performance Killer: The Cost of Dirty Checking</strong></p><p>Memory isn’t the only issue. To figure out what has changed, Hibernate performs <strong>dirty checking</strong> whenever the persistence context is flushed (which happens automatically before a transaction commits).</p><p>During this process, Hibernate must iterate over <strong>every single entity</strong> in the context and compare its current state against its original snapshot. When you have 100 entities, this is instant. When you have 500,000, it’s a huge, time-consuming operation. The time taken to flush grows with the size of the context, which is why your batch job starts fast and gets progressively slower.</p><p><strong>The Solution: Taking Control with flush() and clear()</strong></p><p>To achieve constant performance and memory usage, you must prevent the persistence context from growing indefinitely. The strategy is simple: process records in small batches, and after each batch, manually synchronize with the database and then clear the context.</p><p>This is where flush() and clear() come in.</p><p><strong>What Does flush() <em>Really</em> Do?</strong></p><p>The flush() method synchronizes the in-memory state of the persistence context with the database. It inspects all tracked entities, detects changes (dirty checking), and translates those changes into SQL INSERT, UPDATE, and DELETE statements. These SQL statements are then sent to the database.</p><p><strong>Crucially, flush() does NOT:</strong></p><ul><li><strong>Commit the transaction:</strong> The changes are sent to the database but are not made permanent or visible to other transactions until the entire transaction is committed.</li><li><strong>Free up memory:</strong> The entities remain in the persistence context, still managed and taking up memory.</li></ul><p><strong>What Does clear() Do?</strong></p><p>The clear() method is the memory-saver. It completely empties the persistence context, <strong>detaching</strong> all currently managed entities. This means Hibernate no longer holds a reference to them, and they become plain Java objects. The Java Garbage Collector is now free to reclaim the memory they were occupying.</p><p><strong>The Golden Rule: Implementing the Batch Processing Loop</strong></p><p>The best practice is to combine flush() and clear() at regular intervals. This creates a “sliding window” where the persistence context never holds more than a small number of entities at a time.</p><pre>@Transactional<br>public void processLargeDataset(List&lt;MyEntity&gt; entities) {<br>    int batchSize = 50; // A good default is between 20 and 100<br><br>    for (int i = 0; i &lt; entities.size(); i++) {<br>        MyEntity entity = entities.get(i);<br>        // Do some processing on the entity...<br>        entityManager.persist(entity);<br><br>        // At the end of each batch, flush and clear<br>        if ((i + 1) % batchSize == 0) {<br>            System.out.println(&quot;Flushing and clearing the batch...&quot;);<br>            <br>            // 1. Flush the changes to the database<br>            entityManager.flush();<br>            <br>            // 2. Clear the persistence context to free memory<br>            entityManager.clear();<br>        }<br>    }<br>}</pre><p>By following this pattern, you ensure that:</p><ul><li><strong>Memory usage remains flat:</strong> You only ever hold batchSize entities in memory at once.</li><li><strong>Performance is consistent:</strong> Dirty checking is always fast because it only ever runs on a small batch.</li></ul><p><strong>Beyond Batching: When Else Should You Manually flush()?</strong></p><p>While essential for batching, manually calling flush() is also useful in other scenarios where you need to force synchronization <em>before</em> a transaction commits.</p><ol><li><strong>Executing Queries on Unsaved Data:</strong> If you persist() a new entity and immediately want to execute a JPQL/SQL query that should include this new data, you must flush() first. Otherwise, the new entity only exists in memory and won’t be found by the query.</li><li><strong>Retrieving Database-Generated Values:</strong> When you save an entity with a generated ID (@GeneratedValue), the ID field in your Java object is only populated after the INSERT statement is executed. Calling flush() forces the INSERT, allowing you to access the generated ID right away.</li><li><strong>Enforcing Database Constraints Early:</strong> If you want to catch a UNIQUE constraint violation or another database error before the final commit, calling flush() will trigger the SQL statement and surface the exception immediately.</li></ol><p><strong>The Dangers of clear(): Managing Detached Entities</strong></p><p>While clear() is your best friend for memory management, it comes with side effects you must understand. Once clear() is called, all entities in the context become <strong>detached</strong>.</p><ul><li><strong>Changes are No Longer Tracked:</strong> If you modify a detached entity, Hibernate won’t notice, and your changes will be lost unless you explicitly re-attach it using entityManager.merge().</li><li><strong>Risk of LazyInitializationException:</strong> If you try to access a lazy-loaded collection (e.g., user.getOrders()) on a detached entity, your application will crash with a LazyInitializationException. This happens because the entity is no longer connected to an active session that can fetch the data from the database.</li></ul><p><strong>Conclusion</strong></p><p>The JPA Persistence Context is a powerful tool, but its magic can become a performance trap in batch processing. Forgetting to manage it is the number one cause of slow, memory-intensive data jobs.</p><p>By understanding how flush() synchronizes data and clear() reclaims memory, you can implement a robust batching strategy that ensures your application remains fast, scalable, and reliable, no matter how much data you throw at it.</p><p>Take control of your session, process in batches, and turn your struggling batch job into a high-performance data engine.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bcc5134d8225" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Erasure Coding — This is how cloud providers store multiple copies of data at low cost]]></title>
            <link>https://balkrishan-nagpal.medium.com/erasure-coding-this-is-how-cloud-providers-store-multiple-copies-of-data-at-low-cost-2e5d79a3fa24?source=rss-a5c7b38e8e3c------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e5d79a3fa24</guid>
            <category><![CDATA[cloud-storage]]></category>
            <category><![CDATA[cost-optimization]]></category>
            <category><![CDATA[reliability]]></category>
            <category><![CDATA[erasure-coding]]></category>
            <category><![CDATA[blob-storage]]></category>
            <dc:creator><![CDATA[Balkrishan Nagpal]]></dc:creator>
            <pubDate>Fri, 02 Jan 2026 00:46:11 GMT</pubDate>
            <atom:updated>2026-01-02T00:46:11.516Z</atom:updated>
            <content:encoded><![CDATA[<h3>Erasure Coding — This is how cloud providers store multiple copies of data at low cost</h3><h3>How cloud providers store multiple copies of data at low cost</h3><p>Have you ever thought how object storage systems like AWS S3, Azure blob storage etc. are able to provide such high data availability at such a low cost.</p><p>If they are really storing multiple copies of your data for high availability, then how come they can they provide this at such low cost. At the end of the day it’s a money game. 😉</p><p>Well, answer is they do not store multiple copies of your data. Then how do they provide such high availability without storing multiple copies of your data. Answer is, they use a technique named Erasure Coding.</p><p>In this post, I will talk about what Erasure coding is, how it works, how cloud providers use it to provide high availability without storing multiple copies of your data and in the end will point you to github repo which provides a good implementation.</p><h3>What is Erasure coding</h3><p>Erasure coding is a data protection technique that breaks data into chunks, encodes the chunks and creates some extra redundant information. This redundancy allows the data to be reconstructed even if some of the fragments are lost or damaged.</p><p>In simpler words, it gives you the ability to recover the data from failures at the cost of some storage overhead.</p><h3>How Erasure coding works</h3><p>Working of Erasure coding can be summarized in 3 steps:</p><ul><li><strong>Splitting the data</strong>: Erasure coding breaks down your data file into smaller chunks called data chunks</li><li><strong>Creating extra bits</strong>: It then uses complex math to create additional pieces of data called “parity bits” or “erasure codes.</li><li><strong>Spreading the pieces</strong>: The original data chunks and the parity bits are then distributed across multiple storage locations</li></ul><h3>What are different techniques</h3><p>There are many different erasure coding techniques, each with its own pros and cons. Some of the most common schemes include:</p><ul><li>Reed-Solomon coding</li><li>Low-density parity-check (LDPC) codes</li><li>Turbo codes</li></ul><p>In this post we will talk in more about Reed-Solomon.</p><h3>How Erasure coding is different from replication</h3><p>Replication creates full copies of your data and stores them on separate storage devices. In case of failure, we can use any copy to get the data.</p><p>Erasure coding on other hand breaks down your data into smaller chunks, generate additional “parity” or “erasure codes.” These parity pieces are then distributed alongside the data chunks across multiple storage devices and in case of failure these parity codes can be use for data recovery.</p><p>Comparing both, Erasure coding is much more storage efficient compared to replication. For ex:</p><p>In Reed-Solomon (10, 4) technique, 10 MB of user data is divided into ten 1MB blocks. Then, four additional 1 MB parity blocks are created to provide redundancy. This can tolerate up to 4 concurrent failures. The storage overhead here is 14/10 = 1.4X.</p><p>In the case of a fully replicated system, the 10 MB of user data will have to be replicated 4 times to tolerate up to 4 concurrent failures. The storage overhead in that case will be 50/10 = 5X.</p><p>Cost overhead of 1.4X vs 5X, is self explanatory to how public clouds, provide high availability at such low cost.</p><h3>How Reed-Solomon works</h3><p>Reed Solomon splits the incoming data into data chunk of size let’s say k. It then create additional chunks called parity bits or parity codes let’s say p, taking the total number of chunks to k+p. It then distributes these k+p chunks on different storage devices. These additional chunks give us the ability to recover the data in case some of the data chunks are lost. Till any k chunks out of total of k+p are available, data can be recovered successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qhvqWIbPmB_VYovOKx5sEQ.jpeg" /></figure><p>How many parity chunks are created, it depends on your requirement. Number of parity chunks should be equal to number of failures you want to tolerate. For ex: If data chunks size is 10 and you want to withstand 2 failures, you will have to create 2 parity chunks.</p><p>A more detail description of, how it works can be found <a href="https://www.backblaze.com/blog/reed-solomon/">here</a>. I encourage you to go through this link for much better understanding.</p><h3>Implementation</h3><p>One of the core principles of software engineering is, DRY (Don’t repeat yourself). So, rather than trying to reinvent the wheel and implement Reed solomon, I looked for an easy to use implementation, which can provide a good starting point and then change that If required.</p><p>In this process I stumbled upon this <a href="https://www.blogger.com/blog/post/edit/3986049094810771047/697144964185834737#">github repo</a> which provides a good started point. I highly encourage you clone this repo and play around with the code.</p><p>Since this repo was last updated 3 years ago, it is not most up to date with latest versions of tools. On my machine, I use Java 21 and in order to make it work with Java 21, I had to make some trivial changes. I made required changes to make it work with Java 21. Updated code with changes are pushed to <a href="https://github.com/food-for-techies/erasure-coding">this git repo</a>.</p><p>Run the following command from root of project to create a lib for using within your project.</p><p>./gradlew clean build</p><p>The repo also provides examples how to use Encoder and Decoder. Take a look at classes named SampleEncoder.java and SampleDecoder.java.</p><p>I used them and it works perfectly fine. I encoded a file and deleted some chunks and decoder was still able to recover the original file from leftover chunks.</p><p>That’s it for this Post. Happy eating (Learning 😉)</p><h3>References:</h3><p><a href="https://www.blogger.com/blog/post/edit/3986049094810771047/697144964185834737#">Reed Solomom tutorial</a></p><p><a href="https://www.blogger.com/blog/post/edit/3986049094810771047/697144964185834737#">Summary of how Reed Solomon works</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e5d79a3fa24" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Art of the DTO: Mastering Data Transfer in Modern Spring Boot]]></title>
            <link>https://balkrishan-nagpal.medium.com/the-art-of-the-dto-mastering-data-transfer-in-modern-spring-boot-20887d33fd8a?source=rss-a5c7b38e8e3c------2</link>
            <guid isPermaLink="false">https://medium.com/p/20887d33fd8a</guid>
            <category><![CDATA[dto]]></category>
            <category><![CDATA[layered-architecture]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Balkrishan Nagpal]]></dc:creator>
            <pubDate>Fri, 05 Dec 2025 06:10:04 GMT</pubDate>
            <atom:updated>2025-12-06T00:24:32.502Z</atom:updated>
            <content:encoded><![CDATA[<p>If you have been working with Java and Spring Boot for any length of time, you have likely encountered the <strong>Data Transfer Object (DTO)</strong>. It’s one of those concepts that seems simple on the surface — a plain object designed to carry data from one process to another.</p><p>But as your application grows from a weekend project into an enterprise-grade system, the humble DTO becomes the centre of some heated architectural debates. How exactly should we write them? And perhaps more importantly, <em>where</em> exactly do they fit in the request lifecycle?</p><p>Let’s dive into the industry standards for handling data transfer, moving from how to define them to how to architect them effectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UK0HSlxZ1Xy0Fbo5ckGOiQ.jpeg" /></figure><p><strong>Part 1: The Anatomy of a Perfect DTO</strong></p><p>First, let’s look at the code itself. When you are creating a DTO, you have a decision to make regarding the instance variables. Should you keep it simple with public fields, or stick to the classic encapsulation model?</p><p>If you ask a room full of senior Java developers, the answer will be nearly unanimous: <strong>keep your fields private.</strong></p><p><strong>Why “Public” is a bad idea</strong></p><p>But before that why even ask this question for DTO. This comes to limelight because DTOs don’t have any behaviour and their only purpose to provide access to data. There is virtually nothing in DTO to hide for which we need to expose methods.</p><p><strong>Back to Why “Public” is a bad idea</strong></p><p>It might be tempting to write public String username; and call it a day. It requires less code and feels faster. However, exposing instance variables publicly is widely considered an anti-pattern in Java for several reasons:</p><ul><li><strong>Loss of Control:</strong> You cannot prevent a consumer from setting invalid data (like a negative age).</li><li><strong>Tooling Incompatibility:</strong> The vast majority of Java libraries — from Jackson for JSON serialization to Hibernate for ORM — rely on the JavaBean convention (getters and setters). They often ignore public fields entirely.</li><li><strong>Tight Coupling:</strong> If you ever need to change how a variable is stored internally but want to keep the external access the same, public fields leave you no room to maneuver.</li></ul><p><strong>The Modern Standard: Enter Java Records</strong></p><p>For years, the standard was the <strong>POJO</strong> (Plain Old Java Object) — private fields with public getters and setters. We often used libraries like <strong>Lombok</strong> (@Data) to avoid writing the boilerplate code.</p><p>However, if you are running on a modern Java version (Java 14+), the industry has shifted toward <strong>Java Records</strong>.</p><p>Records are the new gold standard for DTOs. They are immutable, concise, and automatically handle equals(), hashCode(), and toString().</p><p><strong>The Verdict:</strong></p><ul><li><strong>Modern Approach (Best):</strong> Use <strong>Java Records</strong>.</li></ul><pre>public record UserDto(String username, String email) {}</pre><ul><li><strong>Legacy Approach (Good):</strong> Use private fields with <strong>Lombok</strong>.</li><li><strong>Avoid:</strong> Public instance variables.</li></ul><p><strong>Part 2: The Architecture — Where Does the DTO Belong?</strong></p><p>Now that we have built the perfect DTO, where do we use it?</p><p>A common struggle in Spring Boot development is defining the boundaries between layers. Specifically, when your Controller asks your Service for data, what should the Service return?</p><ol><li>The database <strong>Entity</strong>?</li><li>Or the <strong>DTO</strong>?</li></ol><p><strong>The Trap of Returning Entities</strong></p><p>It is incredibly common for developers to simply return the JPA Entity from the Service to the Controller. After all, the data is already there, so why map it to a new object?</p><p>While this saves you a few lines of code initially, it creates a minefield of technical debt.</p><p><strong>1. The StackOverflow Nightmare</strong><br> Entities often have bidirectional relationships (e.g., A User has Orders; Orders belong to a User). If you serialize an Entity directly to JSON, the serializer will loop endlessly between the two until your application crashes with a StackOverflowError.</p><p><strong>2. The “LazyInitializationException”</strong><br> If your entity uses Lazy Loading (the default for lists of data), the database connection usually closes once the Service method finishes. When the Controller (or the JSON converter) tries to access that list later, the application crashes because the session is gone.</p><p><strong>3. Security Leaks</strong><br> Entities represent your full database table. They contain things you never want the client to see: password hashes, internal flags, audit logs, and soft-delete markers. Returning an Entity exposes <em>everything</em>.</p><p><strong>The Best Practice: Service-Layer Mapping</strong></p><p>The industry standard is strict: <strong>The Service layer should return a DTO, not an Entity.</strong></p><p>Your Service layer acts as a transactional boundary. It is responsible for:</p><ol><li>Fetching the Entity from the Repository.</li><li>Initializing any lazy-loaded data needed.</li><li>Mapping that Entity to a DTO (using a tool like MapStruct).</li><li>Returning the safe, flat DTO to the Controller.</li></ol><p>This approach decouples your API from your Database. If you rename a column in your SQL database, your API consumers (frontend/mobile) won’t break, because the DTO remains stable.</p><p><strong>The Bottom Line</strong></p><p>Writing “clean code” isn’t just about indentation; it’s about intent and safety.</p><p>By using <strong>Java Records</strong> (or Lombok) to encapsulate your data, and by ensuring your <strong>Service layer returns DTOs </strong>instead of raw Entities, you protect your application from circular dependencies, security leaks, and brittle architecture. It requires a little more effort upfront, but your future self — debugging a production issue on a Friday afternoon — will thank you for it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20887d33fd8a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Postgres — How I improved data insertion speed by a factor of more than 1000x]]></title>
            <link>https://balkrishan-nagpal.medium.com/postgres-how-i-improved-data-insertion-speed-by-a-factor-of-more-than-1000x-1a968e736e86?source=rss-a5c7b38e8e3c------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a968e736e86</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[batching]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[Balkrishan Nagpal]]></dc:creator>
            <pubDate>Tue, 25 Nov 2025 02:08:21 GMT</pubDate>
            <atom:updated>2025-11-25T02:08:21.000Z</atom:updated>
            <content:encoded><![CDATA[<h3>Postgres — How I improved data insertion speed by a factor of more than 1000x</h3><p>Postgresql is one of the most popular RDBMS around and is being widely used. Saving data in database is one of the most primitive operation but there has always been a desire to get better performance. In this post I will talk about how I managed to improve the performance of database insert by a factor of more than 1000x</p><p>I will walk you through everything I did starting from beginning and how I achieved the desired performance.</p><h3>TechStack</h3><ul><li>Java 21</li><li>Spring boot 3.x</li><li>PostgresSQL 15</li></ul><h3>Machine configuration</h3><ul><li>OS — windows 11</li><li>CPU — i5 11th generation 2.4 Ghz</li><li>RAM — 16 GB</li></ul><h3>Assumptions</h3><p>This post assumes that you are aware of Java programming language and how spring boot ecosystem works.</p><h3>Git Repo</h3><p>All the code discussed in the post is available in following git repo:</p><p><a href="https://www.blogger.com/blog/post/edit/3986049094810771047/4471810502656929152#">https://github.com/food-for-techies/postgres-copy-save</a></p><h3>Let’s start</h3><h3>Creating Spring boot application</h3><p>I started off with creating a spring boot application. Easiest way to create a Spring boot application is by using <a href="https://www.blogger.com/blog/post/edit/3986049094810771047/4471810502656929152#">https://start.spring.io/</a></p><h3>Architecture</h3><p>I started off with MVC architecture, creating a controller, Service and Repository.</p><h3>Entity</h3><p>I created an entity class named Person. Here is how it looks like. For all the testing we will use this entity class to save to database.</p><h3>Let’s start</h3><h3>Creating Spring boot application</h3><p>I started off with creating a spring boot application. Easiest way to create a Spring boot application is by using <a href="https://www.blogger.com/blog/post/edit/3986049094810771047/4471810502656929152#">https://start.spring.io/</a></p><h3>Architecture</h3><p>I started off with MVC architecture, creating a controller, Service and Repository.</p><h3>Entity</h3><p>I created an entity class named Person. Here is how it looks like. For all the testing we will use this entity class to save to database.</p><h3>Let’s start</h3><h3>Creating Spring boot application</h3><p>I started off with creating a spring boot application. Easiest way to create a Spring boot application is by using <a href="https://www.blogger.com/blog/post/edit/3986049094810771047/4471810502656929152#">https://start.spring.io/</a></p><h3>Architecture</h3><p>I started off with MVC architecture, creating a controller, Service and Repository.</p><h3>Entity</h3><p>I created an entity class named Person. Here is how it looks like. For all the testing we will use this entity class to save to database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*JcFei_GyWMh1cNDo3oQCHA.png" /></figure><h3>Repository</h3><p>This is simplest possible repository created with Spring boot. Here is how it looks like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/1*6Ydt-pIuhxA34-9sCt4mbA.png" /></figure><h3>Test Data</h3><p>I generated some fake data related to person name and address in CSV format. We will use the same data for testing all scenarios. The test data is shared in the same git repo under resources folder in a file named: <strong>person-list.csv</strong></p><h3>Getting off the blocks — Save all records one at a time</h3><p>Read all records from CSV and save them to database. As you can imagine very basic and probably the most expensive way of saving to DB. It took approx 2166 seconds (36 mins) to save 100K records to database. This is such an expensive operation, I didn’t even try to save all 1 million rows to DB. The fact that it took 36 mins to save 100K records, indicates that this is very expensive and inefficient way of saving to database. The code for this to work is very straightforward and simple, invoke save method on your repository class passing in the instance of <strong>Person Entity. </strong>Here is how it looks like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*weYPnK-qrHZ4iqFu8P2YpA.png" /></figure><h3>Optimization 1 — Use batching</h3><p>As a first optimization, I reduced the number number of database calls by introducing batching. I used a different batch sizes of 25K, 30K and 50K to measure the performance and with that total time to save to database came down considerably.</p><p>Here are the times recorded for different batch sizes for saving all 1 million rows to DB.</p><ul><li>25K — 58 sec</li><li>30K — 65 sec</li><li>50K — 79 sec</li></ul><p>Note that, as we increase the batch size, time goes up. This is opposite to what we would expect.</p><p><strong>Note: Numbers can vary for machine but at some time I expect to see same behaviour for you as well. You might notice this behaviour for different batch sizes. I encourage you to play around with different batch sizes.</strong></p><p>For batching to work, we need to add required configuration to enable batching. Add following configuration to your application.yaml file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*of94PMelVbzuW6U2OZkYZw.png" /></figure><p>and use following code to save the data in batches.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*KI-LtgYsG4rqbGQWq4J8FQ.png" /></figure><h3>Optimization 2 (and last one) — Use PostGres CopyManager</h3><p>In previous 2 approaches I used Spring Data JPA for all database interactions. For this last optimization, I decided to use Postgres API. I used CopyManager API from PostgresSQL. Copy manager API is a native functionality of Postgres which is used to load bulk data into database. It is also available as a command line tool from Postgres command line interface.</p><p>With CopyManager I was able to load all 1 million rows into database in 4 seconds. Yes, you read that right, <strong>4 seconds</strong>. An improvement of more than 1000x from basic approach and 15x from batch approach.</p><p>To use CopyManager API, first we need to write an SQL query which defines the structure of your table and few options like delimiter and character encoding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*OYO0eTjWC2bIBhO5sKCCaw.png" /></figure><p>Next step is to get a connection to your database</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*fDT35HNeY0fPIoAWHI41hA.png" /></figure><p>Next prepare the data to be inserted to database. Prepare a string in which data in a row is “\t” delimited and rows are separated by “\n”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*EsNlrsSQzSOUvo8jKscYNw.png" /></figure><p>and the last step is to use CopyManager API and send the data to DB.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*vfEs-DYJ8PHuurgR0Uidjg.png" /></figure><p>Here is the graph showing the performance difference between 3 approaches.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/1*NHob28NqHQyhzfjqvSiO6w.png" /></figure><h3>Cons of using CopyManager:</h3><blockquote><em>There are no free lunches</em></blockquote><ul><li>You lose all the benefits of ORM framework</li><li>You need to mention and take care of all columns for which data should be inserted. With a ORM in play, you don’t have to worry about this</li><li>For any change in table structure, you need to remember to update the structure where you use CopyManager API</li><li>With ORM, when save something in DB, you get back an object which has the id of object but this approach you won’t get that.</li></ul><p>If all the performance gain which you get from using CopyManager, is more than the drawbacks which are mentioned above, you can use CopyManager but you need to evaluate carefully between what you gain and what are you losing upon.</p><h3>Why CopyManager is so fast</h3><p>CopyManager is fast because it cuts down the number of database visits. In a prod setup, where your application server and database server won’t be on same machine, this would mean, it cuts down the network calls. Network latency is one of the major factors when interacting between 2 servers. So, In a prod setup, your gain will be even more compared to what you get on a personal laptop where application and database are both on same machine.</p><h3>Summary</h3><p>When working with Spring boot and Postgres database, saving to database is a straights operation but when we need to save large dataset, we need some optimizations to improve the speed. Batching serves us well but when number of rows runs into millions, then even batching has its own limitations. To over come that, we can use Postgres native API called CopyManager. With CopyManager we can load bulk data into database cutting down our number of database trips and hence network calls and latency and giving us more better performance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a968e736e86" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flipkart MySQL High Availability — What the Original Blog Missed]]></title>
            <link>https://balkrishan-nagpal.medium.com/flipkart-mysql-high-availability-what-the-original-blog-missed-38a47ed36112?source=rss-a5c7b38e8e3c------2</link>
            <guid isPermaLink="false">https://medium.com/p/38a47ed36112</guid>
            <category><![CDATA[flipkart]]></category>
            <category><![CDATA[zookeeper]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[high-availability]]></category>
            <dc:creator><![CDATA[Balkrishan Nagpal]]></dc:creator>
            <pubDate>Mon, 27 Oct 2025 14:37:11 GMT</pubDate>
            <atom:updated>2025-10-27T14:37:11.067Z</atom:updated>
            <content:encoded><![CDATA[<h3>Flipkart MySQL High Availability — What the Original Blog Missed</h3><p>I was reading the Flipkart MySQL high availability blog <a href="https://blog.flipkart.tech/mysql-high-availability-5f71838f19e1">here</a>. It explains their MySQL high availability setup well. But it leaves out important operational details that matter when you run this in production.</p><p>Here’s the missing information, distilled into clear steps you can use.</p><blockquote>It is recommended that you read the original blog first and then read rest of this to get a better understanding of what was missing in the original blog.</blockquote><blockquote>Neither I work at Flipkart not I have seen the internals of the system. So, please take this blog with a pinch of salt.</blockquote><p><strong>How the Monitoring Works:</strong></p><ul><li>Every MySQL node runs an agent.</li><li>The agent sends health data to the monitor service every 10 seconds.</li><li>The monitor service acts as a gateway to Zookeeper.</li><li>It checks if the primary has failed and decides if failover is needed.</li><li>During failover it prevents split-brain.</li><li>It updates DNS to point to the new primary.</li></ul><p><strong>Assigning MySQL Nodes to Monitor</strong></p><p>Blog mentioned that each monitor node is responsible for few MySQL nodes but does not explain how specific monitor nodes get assigned to check specific MySQL nodes.</p><p>Here’s how it works:</p><ul><li>MySQL nodes register with Zookeeper.</li><li>Monitor nodes also register with Zookeeper.</li><li>Monitor nodes divide the list of MySQL nodes among themselves dynamically using either consistent hashing or leader election to partition nodes.</li><li>Zookeeper’s watch feature notifies monitors when a MySQL node joins or leaves.</li><li>Each MySQL node is checked by exactly one monitor.<br>Example: If you have 3 monitor nodes and 9 MySQL nodes, each monitor will watch 3 MySQL nodes.</li><li>If one monitor fails, the remaining monitors redistribute the load.</li></ul><p><strong>Waiting for Replica Lag to Catch Up Before Failover</strong></p><p>Failing over too early can cause data loss. You need to confirm that replicas are up to date before promoting one to primary but original blog does not mention how to do this.</p><p>Here are two ways to check:</p><p><strong>Approach 1: Use SHOW REPLICA STATUS</strong></p><p>Run the following SQL on replica</p><pre>SHOW REPLICA STATUS </pre><p>In result set, you should pay attention to 3 columns:</p><p><strong>Replica_IO_Running</strong> — Shows if the replica is actively fetching updates from the primary.<strong><br>Replica_SQL_Running</strong> — Shows if the replica is applying fetched updates to its own data.<br><strong>Seconds_Behind_Source</strong> — Shows how far the replica is lagging behind the primary in seconds.</p><p>If Seconds_Behind_Source == 0, it means replica is all caught up with updates.</p><p><strong>Approach 2: Heartbeat Table Method</strong></p><p>On the primary, create a table:</p><pre>CREATE TABLE heart_beat (  <br>  ts TIMESTAMP NOT NULL PRIMARY KEY DEFAULT CURRENT_TIMESTAMP  <br>);  </pre><p>Insert the current time periodically:</p><pre>INSERT INTO heart_beat (ts) VALUES (NOW());  </pre><ul><li>On the replica, read the latest timestamp and compare to current time.</li><li>The difference is your actual replication lag.</li></ul><p>The original blog gave a solid overview, but it talks about what it does but does not talk about how. I dug into these missing aspects because without them, you don’t get the full picture of MySQL high availability.<br>Knowing how monitors are assigned, how agents feed data, and how to check replica lag isn’t “extra” — it’s essential. These details explain why the system makes the right failover decisions and how it avoids data loss.</p><p>Hope this helps !!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38a47ed36112" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cryptography Essentials : A Developer’s Guide to Secure Apps]]></title>
            <link>https://balkrishan-nagpal.medium.com/cryptography-essentials-a-developers-guide-to-secure-apps-c9065f704976?source=rss-a5c7b38e8e3c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9065f704976</guid>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[ae]]></category>
            <category><![CDATA[symmetric-encryption]]></category>
            <category><![CDATA[hashing]]></category>
            <category><![CDATA[asymmetric-encryption]]></category>
            <dc:creator><![CDATA[Balkrishan Nagpal]]></dc:creator>
            <pubDate>Thu, 31 Jul 2025 14:50:44 GMT</pubDate>
            <atom:updated>2025-07-31T14:50:44.981Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Cryptography Essentials : A Developer’s Guide to Secure Apps</strong></h3><p>In the digital age, security is not just an add-on, but a fundamental necessity. This guide simplifies the essentials of cryptography, making it accessible for everyone. One common pitfall is, People use terms encryption and hashing interchangeably to mean same thing without realising these are 2 different things.</p><p>In this post, I will try to highlight the difference between encryption and hashing, so that you understand which one to use in which scenario and you should not use these terms interchangeably.</p><h3><em>Why Cryptography Matters</em></h3><p>Every time data moves across a network, it’s exposed. Whether it’s inside a private data center or over the internet, attackers can intercept it. Cryptography acts like a lock — it transforms readable data (plaintext) into scrambled data (ciphertext) that only someone with the right key can unlock.</p><h3><em>The Three Pillars of Cryptography</em></h3><ol><li>Symmetric Encryption — One Key to Lock and Unlock</li><li>Asymmetric Encryption — A Lock and a Key</li><li>Cryptographic Hashing — One Way Street</li></ol><h3>Symmetric Encryption</h3><ul><li><strong>What it is</strong>: Employs a single, secret key for both the encryption and decryption of data.</li><li><strong>Where to use it</strong>: Ideal for securing large amounts of data, such as files or databases (“data at rest”).</li><li><strong>Why it&#39;s popular</strong>: Its primary advantage is its exceptional speed and efficiency</li><li><strong>Downside</strong>: Securely sharing this single secret key presents a challenge; if compromised, it exposes all protected data.</li><li><strong>Real-world use case</strong>: Essential for securely storing sensitive user credentials within a database.</li><li><strong>Example</strong>: AES (Advanced Encryption Standard) is the current industry standard, having superseded the older and now insecure DES (Data Encryption Standard).</li></ul><h3>Asymmetric Encryption</h3><ul><li><strong>What it is</strong>: Uses a pair of mathematically linked keys: a public key for encrypting and a private key for decrypting.</li><li><strong>Where to use it</strong>: Secure communication (e.g., HTTPS), digital signatures, and secure key exchange.</li><li><strong>Why it’s popular</strong>: Solves the key distribution problem of symmetric encryption, enabling secure communication between parties who have never met.</li><li><strong>Downside</strong>: Significantly slower and more computationally intensive than symmetric encryption.</li><li><strong>Real-world use case</strong>: Securing online transactions and enabling secure email communication (like PGP).</li><li><strong>Example</strong>: RSA is a widely used and mature asymmetric algorithm, while ECC (Elliptic Curve Cryptography) is a newer, more performant alternative, as it offers strong security with smaller keys. Both are built on “trapdoor functions” — mathematical problems that are easy to solve in one direction but extremely difficult to reverse without a specific secret.</li></ul><h3>Cryptographic Hashing</h3><ul><li><strong>What it is</strong>: A one-way function that transforms input data of any size into a fixed-size string of characters, known as a hash or digest.</li><li><strong>Where to use it</strong>: Primarily for data integrity verification and secure password storage.</li><li><strong>Why it’s popular</strong>: It’s incredibly fast for verification and provides a concise representation of data.</li><li><strong>Downside</strong>: Simple hash functions are too fast, making them vulnerable to “rainbow table attacks” and “brute-force attacks” for password cracking.</li><li><strong>Real-world use case</strong>: Verifying that a downloaded file hasn’t been tampered with or ensuring the integrity of a blockchain transaction.</li><li><strong>Example</strong>: Modern password hashing algorithms like BCrypt and Argon2 are designed to be intentionally “slow” and computationally expensive. They achieve this through features like:<br>- <strong>Iterations (Work Factor)</strong>: Performing many rounds of hashing makes brute-force attacks prohibitively time-consuming.<br>- <strong>Salt</strong>: A unique, random piece of data added to a password before hashing ensures that even identical passwords produce different hashes, rendering rainbow table attacks ineffective.<br>- <strong>Memory Usage (e.g., Argon2)</strong>: Incorporating significant memory usage further increases the cost for attackers attempting to crack passwords.</li></ul><h3>Understanding AES Modes of Operation: Evolution of Security</h3><p>As mentioned above AES is the most popular technique for Symmetric encryption, but how AES is used (its “mode of operation”) dramatically impacts its security and performance. I will briefly talk about AES variations which can have significant impact.</p><p>There are at least 3 modes in AES:</p><ul><li><strong>ECB (Electronic Codebook) Mode</strong>:</li></ul><p><strong>How it works</strong>: The simplest mode, where each block of plaintext is encrypted independently.</p><p><strong>Why it’s insecure</strong>: This simplicity is its downfall. Identical plaintext blocks produce identical ciphertext blocks, revealing patterns in the encrypted data. A classic example is the “penguin image attack,” where the outline of the Linux penguin remains visible even after encryption.</p><ul><li><strong>CBC (Cipher Block Chaining) Mode</strong>:</li></ul><p><strong>How it works</strong>: A significant improvement over ECB. CBC introduces an Initialization Vector, a random value that is XORed with each plaintext block before encryption. This ensures that identical plaintext blocks produce different ciphertext blocks, effectively eliminating patterns.</p><p><strong>Limitations</strong>: While better, CBC is not easily parallelizable, meaning it can be slower for some operations. It also requires “padding” to ensure data blocks are of a fixed size, and critically, it lacks an “authentication tag” to verify data integrity.</p><ul><li><strong>GCM (Galois/Counter Mode)</strong>:</li></ul><p><strong>Why it’s recommended</strong>: GCM is the gold standard for AES today. It offers a trifecta of benefits:</p><p><strong>Confidentiality (Encryption)</strong>: Keeps your data secret.</p><p><strong>Integrity (Authentication Tag)</strong>: Guarantees that the data hasn’t been tampered with during transmission or storage.</p><p><strong>Efficiency</strong>: It’s “stream-like,” meaning it doesn’t require padding and is highly performant because it can be parallelized.</p><blockquote>Spring Security, a popular framework for Java applications, uses GCM by default for many of its encryption needs.</blockquote><h3>Summary</h3><p><strong>Encryption</strong> is a two-way process that transforms data into a secure format, which can then be reverted (decrypted) back to its original state</p><p><strong>Hashing</strong> is a one-way process that converts data into a fixed-size string (a hash value), which cannot be reversed to obtain the original data.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9065f704976" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Git Stash: All you need to know for context switching]]></title>
            <link>https://balkrishan-nagpal.medium.com/mastering-git-stash-all-you-need-to-know-for-context-switching-bdd723c21599?source=rss-a5c7b38e8e3c------2</link>
            <guid isPermaLink="false">https://medium.com/p/bdd723c21599</guid>
            <category><![CDATA[context-switching]]></category>
            <category><![CDATA[git-workflow]]></category>
            <category><![CDATA[developer-tools]]></category>
            <category><![CDATA[git-stash]]></category>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[Balkrishan Nagpal]]></dc:creator>
            <pubDate>Thu, 17 Jul 2025 12:27:54 GMT</pubDate>
            <atom:updated>2025-07-17T12:27:54.470Z</atom:updated>
            <content:encoded><![CDATA[<p>Are you a developer who’s working on a feature, only to be hit with an urgent bug report that needs immediate attention? Switching tasks in the middle of uncommitted work can be a nightmare, often leading to messy commits or the dreaded “save this file elsewhere for now”.</p><p>Enter git stash— your saviour.</p><p>git stash is one of Git’s most convenient and frequently used features. It allows you to temporarily save your uncommitted changes (both staged and unstaged) in your working directory and then revert your working directory to a clean state. Think of it as a magical temporary drawer for your code.</p><p>In this guide, we’ll dive deep into how ‘git stash’ works, its most common commands, and how to use it like a pro to keep your development workflow smooth and efficient.</p><p><strong>Understanding How </strong>git stash<strong> Works</strong></p><p>Imagine this scenario: You’re happily coding away on a Feature X. In your working directory, you’ve got modified files, maybe some new files you’ve already added to the staging area, and even some completely new files that Git doesn’t even know about yet.</p><p>Suddenly, the “production is on fire!” alarm rings. You need to switch to the main branch, fix the critical bug, and deploy — *right now*.</p><p>You can’t just git checkout main with uncommitted changes. Git will refuse, protecting you from losing work or accidentally committing changes to the wrong branch. This is exactly where git stash shines.</p><ol><li>It takes a snapshot: It captures the current state of your working directory (modified files) and your staging area (staged but uncommitted files).</li><li>It cleans up: Once the snapshot is taken, it reverts your working directory to the HEAD commit (the state of your last commit on that branch). All your uncommitted changes vanish from your files, but rest assured, they are safely tucked away internally.</li><li>It stores it: This snapshot is placed into a Last-In, First-Out (LIFO) stack within your Git repository, completely separate from your regular commit history. You can accumulate multiple such stashes.</li><li>You can retrieve it: Later on, whether it’s on the same branch or a different one, you can easily retrieve these saved changes and reapply them to your working directory.</li></ol><p>In essence: you’re temporarily “stashing” your current work, dealing with the urgent matter, and then seamlessly resuming your original task from exactly where you left off.</p><p><strong>Practical ‘git stash’ Commands to Master</strong></p><p>Let’s walk through the most common git stash commands. For illustrative purposes, imagine your working directory currently has a modified Feature.javaand an untracked data.jsonfile.</p><pre><br>git status<br># On branch feat/new-login<br># Changes not staged for commit:<br># modified: Feature.java<br># Untracked files:<br># data.json</pre><p><strong>1. Saving Your Changes (Stashing)</strong></p><p>git stash -m &lt;message&gt; It saves your modified and staged files and allows you to add a clear, memorable message. By default, it does NOT stash untracked files.</p><pre><br> git stash -m “WIP on feature x”<br> # Saved working directory and index state On feat/new-login: WIP on login form…<br> # (feature.js changes are now gone from your working directory)<br> git status<br> # On branch feat/new-login<br> # Untracked files:<br> # data.json<br> # (data.json is still there as it was untracked)</pre><p>To include untracked files, use -u option</p><pre><br> git stash -u -m “Including untracked config and feature work”<br> # Saved working directory and index state On feat/new-login: Including untracked config…<br> # (Both Feature.java and data.json are now gone)<br> git status<br> # On branch feat/new-login<br> # nothing to commit, working tree clean</pre><p><strong>2. Listing Your Stashes</strong></p><p>git stash list Shows all the stashes you currently have. They are indexed as stash@{0}, stash@{1}, etc., where stash@{0} is always the most recent stash.</p><pre><br> git stash list<br> # stash@{0}: On feat/new-login: Including untracked config and feature work<br> # stash@{1}: WIP on another-branch: 1a2b3c4 Another previous stash</pre><p><strong>3. Applying Your Stashes (Retrieving Changes)</strong></p><p>git stash applyApplies the changes from most recent stash to your current working directory.</p><p>If you want to apply changes from any specific stash, you do that by specifying the index</p><p>git stash apply stash@{1}</p><p>Crucially, ‘apply’ *<strong>keeps</strong>* the stash in your stash list. This means you can apply the same stash multiple times if needed (e.g., applying a common fix to several test branches).</p><pre><br> # (After handling the hotfix, switched back to your feature branch)<br> git checkout feat/new-login<br> git stash apply<br> # On branch feat/new-login<br> # Changes not staged for commit:<br> # modified: Feature.java<br> # Untracked files:<br> # data.json<br> <br> git stash list (the stash is still there)<br> # stash@{0}: On feat/new-login: Including untracked config and feature work</pre><p>git stash pop stash@{0} This command does two things:<br> 1. Applies the changes from the specified stash (or `stash@{0}` if none is given).<br> 2. Then, it removes that stash from the stash list.</p><blockquote>Use pop when you’re done with the stash and don’t need it anymore.</blockquote><pre><br> git stash pop<br> # On branch feat/new-login<br> # Changes not staged for commit:<br> # modified: feature.js<br> # Untracked files:<br> # config.json<br> #<br> git stash list (stash@{0} is now gone)<br> <br> </pre><p><strong>4. Inspecting Stashes</strong></p><p>git stash show stash@{0} Shows a summary of the changes in a specific stash (defaulting to stash@{0}).</p><p>git stash show -p stash@{0} This is highly useful! It shows the full diff (patch) for a specific stash, just like git diff. Use it to review what’s in a stash before applying it.</p><p><strong>5. Deleting Stashes</strong></p><p>git stash drop stash@{0}Deletes a specific stash from your list. If no stash is provided, it deletes stash@{0}.</p><p>git stash clear Deletes all stashes from your repository. Use with extreme caution! Only run this if you’re absolutely certain you don’t need any of your saved stashes.</p><p><strong>6. Creating a Branch from a Stash</strong></p><p>git stash branch &lt;new-branch&gt; stash@{0}This command is perfect if you stashed some work and later realize it should actually be on its own dedicated feature branch. As usual, if you don’t specify the stash, it takes the first one from stack. It does the following:<br> 1. Creates a new branch based on the commit where the stash was originally created.<br> 2. Applies the stashed changes to this newly created branch.<br> 3. Then, it drops the stash from your stash list.</p><pre><br> # You stashed some work while on ‘main’ by mistake<br> git stash branch feat/new-feature-from-stash stash@{0}<br> # Switched to a new branch ‘feat/new-feature-from-stash’<br> # Applied changes from stash@{0} and dropped it.</pre><p><strong>Conclusion</strong></p><p>git stash is an incredibly powerful and versatile tool for managing your Git workflow. It empowers you to maintain a clean working directory, effortlessly switch between tasks, and handle urgent interruptions without fear of losing your progress.</p><p>By understanding its mechanisms and mastering these essential commands, you’ll find your development process becoming more fluid, less prone to “dirty” commits, and significantly more productive.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bdd723c21599" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Hive in Big Data: From MapReduce to Modern Cloud Storage]]></title>
            <link>https://balkrishan-nagpal.medium.com/understanding-hive-in-big-data-from-mapreduce-to-modern-cloud-storage-70e713ffb9ce?source=rss-a5c7b38e8e3c------2</link>
            <guid isPermaLink="false">https://medium.com/p/70e713ffb9ce</guid>
            <category><![CDATA[cloud-storage]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[apache-hive]]></category>
            <category><![CDATA[hive-table]]></category>
            <category><![CDATA[big-data]]></category>
            <dc:creator><![CDATA[Balkrishan Nagpal]]></dc:creator>
            <pubDate>Sat, 24 May 2025 11:00:35 GMT</pubDate>
            <atom:updated>2025-05-24T11:00:35.170Z</atom:updated>
            <content:encoded><![CDATA[<p>In the early days of Big Data, processing massive datasets primarily meant writing complex <strong>MapReduce</strong> programs. MapReduce revolutionized scalable processing, but it wasn’t easy to work with — especially for analysts and data scientists who were used to writing SQL.</p><p>This gap gave rise to <strong>Apache Hive</strong>, a project that fundamentally changed how we interact with big data — and continues to be relevant today, especially with cloud-based storage like <strong>S3</strong> and <strong>Azure Data Lake</strong>.</p><p>Let’s explore why Hive was introduced, how it works with cloud storage, and the practical aspects of managing data using Hive tables.</p><h3><strong>Why Hive Was Needed After MapReduce</strong></h3><p>While MapReduce could scale across thousands of machines, it had serious usability challenges:</p><ul><li>Writing MapReduce jobs required expertise in Java or other programming languages.</li><li>Developing even a simple report meant hundreds of lines of boilerplate code.</li></ul><p><strong>Apache Hive</strong> solved this problem by introducing <strong>HiveQL</strong>, a SQL-like language that automatically compiled into MapReduce jobs.<br> This allowed users to:</p><ul><li>Write familiar <strong>SQL-style queries</strong> to analyze large datasets.</li><li>Focus on business logic instead of worrying about parallelism or job management.</li></ul><p>Hive effectively <strong>democratized access to Big Data</strong> for a much broader audience.</p><h3><strong>Major Components of Hive</strong></h3><h4>1. Hive Metastore (HMS)</h4><p>Stores all metadata about:</p><ul><li>File formats, locations, and serialization details. It’s typically backed by a relational DB like MySQL or PostgreSQL.</li><li>Tables and partitions</li><li>Column types and schemas</li></ul><h4>2. HiveQL (SQL Engine)</h4><p>Translates SQL queries into logical plans, and eventually into jobs that run on Hadoop, Tez, or Spark.</p><h4>3. Execution Engine</h4><p>Orchestrates execution of jobs on the cluster. It could be:</p><ul><li>MapReduce</li><li>Apache Tez</li><li>Apache Spark</li></ul><h4>4. Driver &amp; Compiler</h4><ul><li><strong>Driver</strong> manages the lifecycle of a HiveQL statement.</li><li><strong>Compiler</strong> generates the execution plan and submits it to the execution engine.</li></ul><h4>5. Storage Layer</h4><p>Hive reads/writes data to:</p><ul><li>HDFS (traditional)</li><li><strong>Amazon S3</strong>, <strong>Azure Blob Storage</strong>, <strong>Google Cloud Storage</strong> (modern). It supports <strong>columnar formats</strong> like ORC and Parquet for efficient querying.</li></ul><h3><strong>How Hive Works: Key Concepts</strong></h3><p>Hive isn’t a database engine in the traditional sense. It’s more like a <strong>SQL-to-distributed-job compiler</strong>.</p><p>Here’s what happens when you run a HiveQL query:</p><ol><li><strong>Parsing:</strong> The query is parsed and converted into an Abstract Syntax Tree (AST).</li><li><strong>Planning:</strong> Hive builds a logical execution plan.</li><li><strong>Optimization:</strong> The plan is optimized (e.g., predicate pushdown, join reordering).</li><li><strong>Execution:</strong> The optimized plan is translated into a series of jobs (MapReduce, Tez, or Spark) and executed on the cluster.</li><li><strong>Results:</strong> The results are fetched and returned to the user or client.</li></ol><h3>What is stored in Hive Metastore?</h3><ul><li>Table names and schema (columns, types, partitions)</li><li>File formats (like Parquet, ORC, Avro, etc.)</li><li>Table location (S3/ABS path)</li><li>Serialization and compression details</li><li>Partitioning information</li></ul><p>Metastore is the brain that <strong>knows where your data is</strong> and how to read it.</p><h3>Getting started with Hive</h3><p>Assuming Hive is already installed and configured on your cluster, the first step is to make your data queryable<strong> </strong>through Hive. Your data may reside in HDFS or cloud storage platforms such as Amazon S3<strong> </strong>or Azure Blob Storage.</p><p>To register the existing data with Hive, you can create an external table that points to the data’s storage location. For example, the following HiveQL statement defines a table over Parquet files stored in S3:</p><pre>CREATE EXTERNAL TABLE sales_data (<br>  order_id STRING,<br>  order_date DATE,<br>  amount DOUBLE<br>)<br>STORED AS PARQUET<br>LOCATION &#39;s3a://my-data-bucket/sales/parquet/&#39;;</pre><p>This command does not move or duplicate the data. Instead, it registers metadata in the Hive Metastore, enabling you to run SQL queries directly on the files where they are.</p><p>That’s it. Now you can run queries on this data by running SQL queries and don’t have to worry about complexity of MapReduce job.</p><pre>SELECT order_date, SUM(amount)<br>FROM sales_data<br>GROUP BY order_date;</pre><h3><strong>Managed vs External Tables: Key Differences</strong></h3><p>When we created a table above, we create a external table. There are 2 types of tables you can create in hive: Managed and External tables.</p><p>Let’s see what is the difference between the two.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*pJUz4nlEEY5d0Odik6WI0Q.png" /></figure><h3><strong>How Hive Works with Cloud Storage (S3, Azure)</strong></h3><p>As enterprises moved from on-prem Hadoop clusters to cloud object storage like <strong>Amazon S3</strong> or <strong>Azure Blob Storage</strong>, Hive evolved as well.</p><p>Today, it’s common to store raw and processed data in cloud storage and simply <strong>create Hive tables</strong> that point to that data.</p><p>Here are some questions asked when creating managed tables in Hive with data in cloud storage.</p><p><strong>If My Data is Already in S3/ABS — Should I Use Managed or External?</strong></p><p>In most real-world cloud architectures:</p><ul><li>You <strong>always prefer External tables</strong> if your data already exists in S3 or Azure Blob Storage.</li><li>You don’t want Hive to accidentally delete your raw or processed data if someone runs a DROP TABLE.</li><li>External tables give you better <strong>data governance and storage control</strong>.</li></ul><p><strong>Managed tables</strong> are mainly useful when:</p><ul><li>Hive should control the lifecycle of the data.</li><li>You want automatic cleanup when dropping tables (e.g., temp or staging tables).</li></ul><p><strong>Does Hive Copy Data When Creating Managed Table on Cloud?</strong></p><p><strong>Short answer: No!</strong></p><p>Even if you create a managed table and specify a LOCATION on S3/ABS, Hive:</p><ul><li>Does not copy the existing data.</li><li>Simply registers the metadata pointing to that location.</li></ul><p>You only incur storage and access costs for the actual files you query — no unexpected duplication.</p><p><strong>What Happens If I Do an Insert into Such a Managed Table?</strong></p><p>Suppose you create a managed table pointing to existing cloud data, and then run:</p><pre>INSERT INTO TABLE sales_data VALUES (1001, &#39;2025-04-26&#39;, 100.50);</pre><ul><li>Hive <strong>does NOT copy</strong> all existing files.</li><li>It <strong>creates a new small file</strong> (e.g., an ORC/Parquet file) inside the same cloud storage path.</li><li>Existing files remain <strong>untouched</strong>.</li><li>No large storage or network cost spike happens because of a simple insert.</li></ul><p>If you run INSERT OVERWRITE, then the behavior can change — Hive might recreate files, affecting cloud storage costs.</p><h3>What is Beeline</h3><p>When working with hive command line you have 2 options: 1. Hive CLI 2. Beeline CLI. Using both you can interact with hive but then what is the difference between the two.</p><p>Table shows the key difference between the two.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*E8fFq9wVgkqbEJgRr4KrEQ.png" /></figure><h3><strong>Summary</strong></h3><p>Apache Hive played a critical role in making Big Data accessible through SQL-like querying.<br> In today’s cloud-native environments:</p><ul><li>Hive still acts as a <strong>metadata layer</strong> over cloud storage.</li><li>Choosing between <strong>managed</strong> and <strong>external</strong> tables is crucial for proper cost and data control.</li><li>Simple operations like INSERT INTO <strong>do not copy</strong> all existing data, keeping cloud costs manageable.</li></ul><p>Happy learning :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70e713ffb9ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Multi-Environment Azure Deployments with Terraform]]></title>
            <link>https://balkrishan-nagpal.medium.com/mastering-multi-environment-azure-deployments-with-terraform-b2bbe252fd9e?source=rss-a5c7b38e8e3c------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2bbe252fd9e</guid>
            <category><![CDATA[modularization]]></category>
            <category><![CDATA[maintainability]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[reuseable]]></category>
            <dc:creator><![CDATA[Balkrishan Nagpal]]></dc:creator>
            <pubDate>Tue, 06 May 2025 15:37:47 GMT</pubDate>
            <atom:updated>2025-05-06T15:37:47.571Z</atom:updated>
            <content:encoded><![CDATA[<p>Deploying infrastructure to Azure across multiple environments (dev, staging, prod) can quickly become a tangled mess. This post distills best practices for organising your Terraform projects, ensuring maintainability, reusability, and consistency across your Azure deployments. We’ll focus on a modular approach that makes managing complex infrastructure easier.</p><p><strong>The Challenge: Scaling Your Infrastructure</strong></p><p>As your application grows, so does your infrastructure. Managing everything in a single Terraform file becomes unmanageable. You need a structured approach to:</p><ul><li><strong>Isolate environments</strong>: Dev should never impact prod!</li><li><strong>Reuse code</strong>: Avoid copy-pasting the same configuration multiple times.</li><li><strong>Manage complexity</strong>: Break down your infrastructure into manageable chunks.</li></ul><p><strong>The Solution: A Modular, Environment-Aware Terraform Project</strong></p><p>Here’s a project structure that tackles these challenges:</p><pre>├── README.md<br>├── variables.tf (Global Variables)<br>├── versions.tf   (Terraform and Provider versions)<br>├── data.tf       (Shared Data Sources)<br>├── modules/        # Reusable Infrastructure Modules<br>│   ├── resource-group/<br>│   │   ├── main.tf<br>│   │   ├── variables.tf<br>│   │   ├── outputs.tf<br>│   ├── virtual-network/<br>│   │   ├── main.tf<br>│   │   ├── variables.tf<br>│   │   ├── outputs.tf<br>│   ├── ...<br>├── environments/     # Environment-Specific Configurations<br>│   ├── dev/<br>│   │   ├── terraform.tfvars (Environment-specific variables)<br>│   │   ├── main.tf        (Root module calling other modules)<br>│   │   ├── variables.tf   (Variables specific to the dev env)<br>│   │   ├── backend.tf     (Remote state config)<br>│   ├── prod/<br>│   │   ├── terraform.tfvars (Environment-specific variables)<br>│   │   ├── main.tf        (Root module calling other modules)<br>│   │   ├── variables.tf   (Variables specific to the prod env)<br>│   │   ├── backend.tf     (Remote state config)<br>│   └── shared/         # Shared resource configurations (optional)<br>├── scripts/          # Optional: Scripts for automation</pre><p>Let’s break down each part:</p><p>README.md<strong>:</strong> Documentation is key! Explain your project structure, conventions, and deployment process.</p><p>variables.tf <strong>(Global):</strong> Defines variables shared across all environments, like the Azure region. Include sensible defaults.</p><pre>variable &quot;location&quot; {<br>  type        = string<br>  description = &quot;The Azure region to deploy to.&quot;<br>  default     = &quot;eastus&quot;<br>}</pre><p>versions.tf: Pin your Terraform and provider versions to ensure consistent behavior.</p><pre>terraform {<br>  required_version = &quot;&gt;= 1.0.0&quot;<br>  required_providers {<br>    azurerm = {<br>      source  = &quot;hashicorp/azurerm&quot;<br>      version = &quot;~&gt; 3.0&quot;<br>    }<br>  }<br>}</pre><p>data.tf: Contains data sources to fetch existing Azure resources or information.</p><p>modules/: The heart of reusability. Each subdirectory represents a reusable infrastructure component (e.g., resource-group, virtual-network). Each module has its own:</p><ul><li>main.tf: Defines the resources within the module.</li><li>variables.tf: Declares the input variables for the module (with descriptions and optional defaults!).</li><li>outputs.tf: Exposes important attributes of the created resources (e.g., the resource group name or ID).</li></ul><p>Example (Resource Group Module)</p><pre>resource &quot;azurerm_resource_group&quot; &quot;rg&quot; {<br>   name     = var.resource_group_name<br>   location = var.location<br>   tags = var.tags<br>}<br><br>output &quot;name&quot; {<br>   value       = azurerm_resource_group.rg.name<br>   description = &quot;The name of the resource group.&quot;<br>}<br><br>output &quot;id&quot; {<br>   value       = azurerm_resource_group.rg.id<br>   description = &quot;The ID of the resource group.&quot;<br>}<br><br>output &quot;location&quot; {<br>   value = azurerm_resource_group.rg.location<br>   description = &quot;The location of the resource group&quot;<br>}</pre><p>environments/<strong>:</strong> This directory separates your environment configurations. Each environment (e.g., dev, prod) has its own:</p><p>terraform.tfvars<strong>:</strong> Contains the <em>values</em> for the variables defined in your modules and the root module. <strong>Never commit secrets to this file!</strong></p><p>main.tf: The &quot;root module&quot; for the environment. This file calls the modules defined in the modules/ directory, passing the appropriate variable values. This is the starting point for Terraform execution in that environment.</p><p>Example environments/dev/main.tf</p><pre>module &quot;resource_group&quot; {<br>  source              = &quot;../../modules/resource-group&quot;<br>  resource_group_name = var.resource_group_name<br>  location            = var.location<br>  tags = {<br>    Environment = &quot;Development&quot;<br>    Project     = &quot;MyApp&quot;<br>  }<br>}<br><br>module &quot;virtual_network&quot; {<br>  source              = &quot;../../modules/virtual-network&quot;<br>  resource_group_name = module.resource_group.name  # Use the output<br>  location = module.resource_group.location  # Use the output<br>  vnet_name           = &quot;vnet-dev-myapp&quot;<br>  address_space       = [&quot;10.0.0.0/16&quot;]<br>}</pre><p>variables.tf: Defines environment-specific variables (less common, as most variables are passed through .tfvars but can be useful for things like environment names).</p><p>backend.tf: Configures the Terraform backend for remote state management. <strong>Use separate state files for each environment!</strong> This is absolutely critical for isolation.</p><p>Example environments/dev/backend.tf</p><pre>terraform {<br>  backend &quot;azurerm&quot; {<br>    resource_group_name  = &quot;rg-terraform-state&quot;<br>    storage_account_name = &quot;statestorageaccount&quot;<br>    container_name       = &quot;tfstate&quot;<br>    key                  = &quot;dev.terraform.tfstate&quot;  # Unique state file<br>  }<br>}</pre><p>· scripts/ <strong>(Optional):</strong> Shell scripts for automation (e.g., deploying to a specific environment).</p><h3>Key Concepts in Action</h3><ol><li>variables.tf vs. .tfvars: variables.tf <em>defines</em> the input variables (name, type, description, default value), while .tfvars <em>assigns values</em> to those variables for a specific environment. This separation enables code reuse and environment-specific configurations.</li><li>Modules: Modules encapsulate infrastructure components. They have their own main.tf, variables.tf, and outputs.tf.</li><li>main.tf : The main.tf file in each environment directory acts as the orchestrator. It calls the modules, passing the environment-specific values defined in terraform.tfvars.</li><li>Dependency Management: Ensure required resources are created before other dependent resources. Use the depends_on attribute <em>only if</em> Terraform doesn’t infer the dependency automatically (which it usually does if you correctly pass outputs).</li></ol><h3>Deployment Workflow</h3><ol><li>Define your modules in the modules/ directory.</li><li>Create environment directories (e.g., environments/dev, environments/prod).</li><li>In each environment directory, create a terraform.tfvars file and set the environment-specific variable values.</li><li>In the environment’s main.tf file, call the modules, passing the variable values.</li><li>Navigate to the environment directory (e.g., cd environments/dev).</li><li>Run terraform init, terraform plan, and terraform apply.</li></ol><h3>Conclusion</h3><p>This structured approach to Terraform projects promotes code reuse, simplifies environment management, and facilitates collaboration. By embracing modularity and environment-specific configurations, you can confidently scale your infrastructure with Terraform. Remember to adapt this structure to fit the specific needs of your project, and always prioritize security and maintainability.</p><p>Happy Terraforming!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2bbe252fd9e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>