<?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 Prashant Chavan on Medium]]></title>
        <description><![CDATA[Stories by Prashant Chavan on Medium]]></description>
        <link>https://medium.com/@prashantchavan18?source=rss-8910b2dc8b26------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Gq_xa5an1_zeke7o</url>
            <title>Stories by Prashant Chavan on Medium</title>
            <link>https://medium.com/@prashantchavan18?source=rss-8910b2dc8b26------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 21:24:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@prashantchavan18/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[The Anatomy of a Database Insert: Where Does Your Data Go After INSERT?]]></title>
            <link>https://medium.com/@prashantchavan18/the-anotomy-of-a-database-insert-where-does-your-data-go-after-insert-61546784c668?source=rss-8910b2dc8b26------2</link>
            <guid isPermaLink="false">https://medium.com/p/61546784c668</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[insert]]></category>
            <category><![CDATA[query]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Prashant Chavan]]></dc:creator>
            <pubDate>Tue, 30 Jun 2026 16:48:43 GMT</pubDate>
            <atom:updated>2026-08-22T06:35:22.547Z</atom:updated>
            <content:encoded><![CDATA[<p>Meet our two developers:</p><ul><li><strong>200 (The Explainer): Named after the HTTP “200 OK” status code. They are the reliable senior engineer who always seems to know how things work under the hood.</strong></li><li><strong><em>404 (The Questioner):</em></strong><em> Named after the HTTP “404 Not Found” status code. They are the curious junior developer, constantly searching for answers and trying to make sense of complex systems.</em></li></ul><p><strong><em>404:</em></strong><em> Hey 200, if you are free can we go for a tea break?</em></p><p><strong>200: Sure, I’m always ready for Tea buddy…!</strong></p><blockquote><em>(They grab their cups and head to the Cafeteria)</em></blockquote><p><strong><em>404:</em></strong><em> Man, I was just running a massive INSERT script and it was taking forever. It got me thinking — when I write an insert statement and hit execute, what is actually happening? Where does that data physically go under the hood?</em></p><p><strong>200: That’s a great question. We use databases every day, but have you ever wondered how the data is physically stored inside them?</strong></p><p><strong><em>404:</em></strong><em> I honestly just assumed it gets dumped into some giant, hidden text file or a massive spreadsheet on the server. Does it not?</em></p><p><strong>200: Surprisingly, databases don’t store data in a human-readable format at all. Data is typically organized into binary pages, blocks, and other storage structures optimized for efficient random and sequential I/O operations.</strong></p><p><strong><em>404:</em></strong><em> Whattt! Pages…!!!? Blocks…!!!? What are these?</em></p><p><strong>200: It works like a hierarchy. Table records are stored in Pages (or DB blocks), which are grouped into Extents, which are saved to Data Files, which the operating system finally writes to Physical Disk Sectors.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*ISS1PvJVv5qAAxIo.png" /></figure><p><strong><em>404:</em></strong><em> ??? Can you please double-click on that and explain?</em></p><p><strong>200: Sure! Let’s start with the smallest piece.</strong></p><h3>Data Pages:</h3><p>A database page (also called a <strong>Data Block</strong> in some databases like Oracle) is the smallest unit of storage that a database engine reads or writes.</p><p>Think of a data page as a database’s storage container. Instead of saving each row separately on the physical disk, the database packs multiple rows into these fixed-size pages (usually 8 KB or 16 KB). Whenever data is read or written, the database moves these entire pages into memory rather than pulling individual rows.</p><p><strong><em>404:</em></strong><em> Okay, that makes sense. But if it’s just a fixed-size 8 KB container, how does the database organize the data inside it? How does it know where one row ends and the next one begins? Can I see what a page actually looks like?</em></p><p><strong>200: Wait, I’ll show you how a Data Page typically looks…</strong></p><blockquote>(200 pulls up a diagram on their phone and shows it to 404)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JHy--uSDpjMboWbc.png" /><figcaption><strong>Data Page</strong></figcaption></figure><p><strong><em>404:</em></strong><em> Looks cute…!</em></p><p><strong>200: Cute ? <em>(Takes a sip of tea)</em> Spend a minute looking at the above image, sorry “Cute image.”</strong></p><p><strong><em>404:</em></strong><em> I see some text inside the image like Page Header, Data Records, Free Space, Offset Array, etc. What are those exactly?</em></p><p><strong>200: Those are the fundamental essentials to look “Cute.” <em>(Both start laughing)</em> Jokes apart, I’ll help you understand all the terminologies mentioned in this image.</strong></p><p>There are three major sections:</p><ul><li><strong>Page Header:</strong> Contains metadata about the page, such as the Page Number, the amount of Free Space, checksums for data integrity, etc.</li><li><strong>Data Records:</strong> This is where the actual row data is physically written.</li><li><strong>Offset Array (or Row Offsets):</strong> Think of this as an index for the page itself. It is an array where each index holds a pointer to the exact starting location of the corresponding data record above it.</li></ul><p><strong><em>404:</em></strong><em> So, we can store all my million records in a single page, right?</em></p><p><strong>200: No! As you can see, the page and its sections have a fixed total size (usually 8 KB). Let’s say the Page Header takes up 96 Bytes, leaving roughly 8000 Bytes for Data Records and the Offset Array.</strong></p><p><strong>If a single record is around 200 Bytes, you can store roughly 40 records in one Data Page.</strong></p><p>For example:</p><pre>id (16 Bytes) | name (160 Bytes) | city (20 Bytes) | pincode (4 Bytes) |</pre><p><strong><em>404:</em></strong><em> If I understand correctly, I would need 25,000 Data Pages to store my 1 million records.</em></p><blockquote><strong><em>(1,000,000 records / 40 records per page = 25,000 pages)</em></strong></blockquote><p><strong>200: Exactly.</strong></p><p><strong><em>404:</em></strong><em> But I never remember creating Data Pages manually. Who creates them exactly, and who maintains them?</em></p><p><strong>200: Data pages are automatically created and managed by the database engine behind the scenes. Whenever you insert data that exceeds the capacity of existing pages, the database allocates a new one.</strong></p><p><strong>Think of a data page like an empty notebook page. You start writing text lines from the top down (Data Records), but you also start writing a table of contents from the bottom margin up (Offset Pointers). The clean, unwritten paper left in the dead center is your Free Space. It sits right between the boundaries of your written data and your pointers.</strong></p><p><em>404: Wait… you mentioned Extents earlier. We spoke a lot about Pages, but what exactly is an Extent?</em></p><p><strong>200: Good catch! Think of an Extent as a collection of consecutive Data Pages. Instead of allocating storage one page at a time, the database often allocates multiple pages together as a single unit. This improves allocation efficiency and helps keep related data physically close together.</strong></p><p><strong><em>404:</em></strong><em> So the hierarchy is basically:</em></p><p><em>Records → Pages → Extents → Database Files → Physical Storage</em></p><p><strong>200: Exactly!</strong></p><p><strong><em>404:</em></strong><em> Ohh, interesting… I understand that the table records are stored in Pages now. But what next? Data pages are stored on disk, aren’t they?</em></p><p><strong>200: Yes. Data pages are stored inside database files on the disk. However, they are not written directly to raw disk sectors. The database stores pages inside its own database files, and the Operating System (OS) maps those files to filesystem blocks and physical disk sectors underneath.</strong></p><p><strong>When a query requests a single row, the database usually loads the <em>entire page</em> containing that row into memory. This page-based I/O model is one of the key reasons databases organize data into pages and use structures like B+ Trees for efficient retrieval.</strong></p><blockquote><em>N</em><strong><em>OTE: </em></strong><em>For now, we’ll set aside the detailed discussion of B+ Trees and Index types such as Dense, Sparse, Secondary, and Clustered to stay focused on the core concept.</em></blockquote><p><strong><em>404:</em></strong><em> I’m getting a bit confused with the “Blocks” terminology. Can you elaborate a bit?</em></p><p><strong>200: Sure! There are actually two different kinds of blocks involved here:</strong></p><ol><li><strong>Database Pages (called Data Blocks in Oracle):</strong> These are managed by the database engine. The DB stores rows inside pages because reading and writing rows one at a time from a physical disk would be incredibly slow. For example, if your user record is 200 Bytes, the database does not perform a tiny 200-Byte disk read. Instead, it grabs the entire 8 KB page containing that row.</li><li><strong>Storage / Filesystem Blocks:</strong> These are managed by the OS and the physical storage device. When the database requests its 8 KB page, the OS might read multiple filesystem blocks (for example, two 4 KB OS blocks) from the hard drive to satisfy the database’s request.</li></ol><p><strong><em>404:</em></strong><em> Got it! Thanks for the explanation, it was a productive tea break<br>(for me, at least) (laughs)</em></p><p><strong>200: You are always welcome buddy.</strong></p><p><strong><em>404:</em></strong><em> Let’s catch up around lunch time! I want to know how D</em><strong><em>ata Retrieval</em></strong><em> from the database works internally.</em></p><p><strong>200: Sure, see you!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61546784c668" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hibernate N+1 Select Problem: Why It Happens and How to Fix It]]></title>
            <link>https://medium.com/@prashantchavan18/hibernate-n-1-select-problem-why-it-happens-and-how-to-fix-it-da83698d29b2?source=rss-8910b2dc8b26------2</link>
            <guid isPermaLink="false">https://medium.com/p/da83698d29b2</guid>
            <category><![CDATA[n-plus-1-queries]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[hibernate]]></category>
            <category><![CDATA[jpa]]></category>
            <dc:creator><![CDATA[Prashant Chavan]]></dc:creator>
            <pubDate>Mon, 01 Dec 2025 17:54:00 GMT</pubDate>
            <atom:updated>2025-12-02T14:15:09.322Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>A single API call making 100+ database queries! Sounds impossible, right?</strong></p><p>This is exactly what the Hibernate N+1 problem does. Hibernate handles most queries for us, which makes development smooth. But when real traffic hits production, hidden performance issues start surfacing. <br>One such issue is the <strong>N+1 select problem. </strong>Where Hibernate silently hits the database multiple times for the same related data. This leads to slow APIs, unnecessary DB load, and even connection pool exhaustion. The issue stays invisible in small datasets, but it becomes a real bottleneck as the system scales.</p><p>Before we fix it, let’s first understand what the N+1 problem actually is.</p><h3>What is the N+1 Problem ?</h3><p>The <strong>Hibernate N+1 query problem</strong> is a performance anti-pattern where the system retrieves a collection of parent entities, then triggers <strong>N separate database queries, </strong>one for each parent to fetch their associated child entities.</p><p>Consider a scenario where we need to fetch a list of employees and for each employee, access their related addresses.</p><blockquote>The Employee entity has a one-to-many relationship with Address, configured with LAZY fetching:</blockquote><ol><li><strong>The ‘1’ Query:</strong> An initial query is executed to load N parent entities <br>ex: All Employee records.</li><li><strong>The ’N’ Queries:</strong> For each of the N parent entities, when the lazy-loaded child collection is accessed <em>for the first time</em> within the transaction, the <strong>Persistence Context</strong> notices the uninitialized proxy. It then executes an additional, separate query to fetch the associated lazy-loaded child entity (ex: the Address list). This is called <strong>Lazy Initialization</strong>.</li></ol><blockquote>If you have 1000 employees, the total number of database queries executed is <br><strong>1 + 1000 = 1001</strong> queries for a single request. <br>This excessive request overhead between the application and the database reduces speed and overall performance</blockquote><h3>Let’s understand this with code.</h3><p>Employee.java</p><pre>@Entity<br>@Data<br>@NoArgsConstructor<br>public class Employee {<br><br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br><br>    private String name;<br><br>    @OneToMany(mappedBy = &quot;employee&quot;, cascade = CascadeType.ALL, fetch = FetchType.LAZY)<br>    private List&lt;Address&gt; addresses = new ArrayList&lt;&gt;();<br>}</pre><p>EmployeeController</p><pre>@GetMapping(&quot;/fetch_all&quot;)<br>public List&lt;EmployeeDTO&gt; fetchAllEmployees() {<br>    return employeeService.getAllEmployees();<br>}</pre><p>EmployeeService.java</p><pre>@Transactional(readOnly = true)<br>public List&lt;EmployeeDTO&gt; getAllEmployees() {<br>    List&lt;Employee&gt; employees = employeeRepo.findAll();<br><br>    return employees.stream()<br>            .map(EmployeeService::convertToEmployeeDTO)<br>            .toList();<br>}<br>private static EmployeeDTO convertToEmployeeDTO(Employee e) {<br>    Long employeeId = e.getId();<br>    String employeeName = e.getName();<br>    List&lt;Address&gt; employeeAddresses = e.getAddresses();<br><br>    return new EmployeeDTO(employeeId, employeeName, employeeAddresses.stream().map(Address::getCity).toList());<br>}</pre><p>Setup is done.</p><blockquote>Now, let’s hit the API: <strong>GET</strong><a href="http://localhost:8080/api/employees/fetch_all"><strong> </strong>http://localhost:8080/api/employees/fetch_all</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9saQK6B-ZOqsQB34P1MU5w.png" /></figure><p>When I hit the endpoint, I observed that Hibernate generated one query at line 25 and multiple queries at line 35.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MosZMJsCBek9ZmoLO_eKrA.png" /><figcaption>Console</figcaption></figure><p>As shown in the screenshot, the first query fetches data from the <strong>Employee</strong> table, while the remaining queries are executed to fetch the <strong>Address</strong> records for each employee. <br>In my case, I had 10 employees, so Hibernate triggered 1 query for employees and 10 additional queries for their addresses.</p><blockquote><strong>NOTE:</strong> The N+1 problem can occur with both LAZY and EAGER relationships. Even if you change the address mapping to EAGER, Hibernate can still issue N+1 queries when calling employeeRepo.findAll(). <br>EAGER loading only guarantees that child entities are fetched, but it does <strong>not</strong> guarantee they are loaded in a single query.</blockquote><h3><strong>Now, let’s fix this problem</strong></h3><h3><strong>Solution 1: Using JPA JOIN FETCH</strong></h3><p>The goal is to change the fetching strategy for this specific use case from <strong>Lazy</strong> to <strong>Eager</strong>, but without making the change permanent in the entity definition. We must instruct Hibernate to retrieve the parent and all children using a single, efficient JOIN query.</p><p>The most robust and standard JPA mechanism for this is the <strong>JOIN FETCH</strong> clause within a custom repository query.</p><h4>The Role of JOIN FETCH</h4><ul><li><strong>JOIN (Standard SQL):</strong> Combines the records from the Employee and Address tables.</li><li><strong>FETCH (JPA/Hibernate Hint):</strong> Crucially tells the ORM that the joined collection (e.addresses) must be <strong>initialized</strong> and attached to the parent entities <em>within this single result set</em>, bypassing the need for subsequent lazy loads.</li></ul><h4>Implementing the Fix</h4><p>We define a custom method in our EmployeeRepository using the @Query annotation:</p><pre>public interface EmployeeRepository extends JpaRepository&lt;Employee, Long&gt; {  <br>  @Query(&quot;SELECT DISTINCT e FROM Employee e LEFT JOIN FETCH e.addresses&quot;) <br>  List&lt;Employee&gt; findAllWithAddress(); <br>}</pre><p>The service layer requires a one-line change to call the optimized method:</p><pre>public List&lt;EmployeeDTO&gt; getAllEmployees() {<br>    // Replace this line:<br>    List&lt;Employee&gt; employees = employeeRepo.findAll();<br><br><br>    // With this line:<br>    List&lt;Employee&gt; employees = employeeRepo.findAllWithAddress();<br><br>    ...(Rest same code)<br>}</pre><p>The database interaction is now reduced from N+1 queries down to a single, efficient SELECT that loads all necessary data.</p><h3>Let’s Verify:</h3><blockquote>Now, let’s hit the API again: <strong>GET</strong><a href="http://localhost:8080/api/employees/fetch_all"><strong> </strong>http://localhost:8080/api/employees/fetch_all</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_CkCf_N6M0vb8mnk7TFsoA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UhVBjw_wMXCA2mkyB8ElYg.png" /><figcaption>Console</figcaption></figure><h3>Solution 2: Using @EntityGraph</h3><pre>@EntityGraph(attributePaths = &quot;addresses&quot;)<br>@Query(&quot;SELECT e FROM Employee e&quot;)<br>List&lt;Employee&gt; findAllWithAddress();</pre><ul><li>attributePaths = &quot;addresses&quot; tells JPA to eagerly load the address collection together with the Employee entity in a single query, preventing additional queries for each employee.</li></ul><blockquote>This effectively avoids the N+1 problem and loads the child entities in the same way as a JOIN FETCH query. <br>Hibernate ends up generating a similar SQL query in both cases.</blockquote><h4><strong>Congratulations 🎉</strong></h4><p><em>We have successfully reduced the N+1 queries down to a single, efficient query.</em></p><h3><strong>Conclusion</strong></h3><p>The N+1 select problem is a silent performance killer that only shows itself when real traffic hits your system. A simple API call can unexpectedly generate hundreds of SQL queries, slowing down your application and putting pressure on your database. <br><strong>JOIN FETCH/EntityGraph</strong> solves the problem by loading all required data in a single optimized query. With the right fetching strategy in place, your application becomes more predictable, scalable, and production-ready.</p><blockquote><strong>Thank you for reading. I hope it helped <em>😊</em></strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da83698d29b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>