<?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 Pratham Karia on Medium]]></title>
        <description><![CDATA[Stories by Pratham Karia on Medium]]></description>
        <link>https://medium.com/@kariapratham?source=rss-962bc4bfa4fb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dvicRvuM6L_35oCt7H66UA@2x.jpeg</url>
            <title>Stories by Pratham Karia on Medium</title>
            <link>https://medium.com/@kariapratham?source=rss-962bc4bfa4fb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 20:22:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kariapratham/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[Spring Boot HikariCP Explained: Connection Pool Tuning for High-Performance Applications]]></title>
            <link>https://medium.com/@kariapratham/spring-boot-hikaricp-explained-connection-pool-tuning-for-high-performance-applications-2eb40fe054ce?source=rss-962bc4bfa4fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/2eb40fe054ce</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[performance-optimization]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Pratham Karia]]></dc:creator>
            <pubDate>Sun, 18 Oct 2026 10:38:59 GMT</pubDate>
            <atom:updated>2026-10-18T10:38:59.918Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1TfKRVLnkieCvbo8gTXrYA.png" /></figure><p>In a high-throughput Java application, database connection management is not just configuration. It is a concurrency, resource-allocation, and performance problem.</p><p><strong>HikariCP</strong> is a lightweight JDBC connection pool designed to minimize connection-acquisition overhead and efficiently manage concurrent access to database connections. It is the default connection pool used by Spring Boot when JDBC or JPA is configured and no alternative pool is selected.</p><p>But here is the problem: using HikariCP does not automatically mean your application is optimized for production.</p><p>Understanding how connections are acquired, reused, and released is essential when building scalable Spring Boot applications.</p><h3>1. What Actually Happens When Your Application Requests a Connection?</h3><p>Establishing a physical database connection involves TCP communication, authentication, session initialization, and database-side resource allocation. Repeating this process for every database operation introduces unnecessary overhead.</p><p>HikariCP solves this by maintaining a pool of reusable JDBC connections.</p><p>The architecture is straightforward:</p><p>Application → DataSource → HikariCP → JDBC Connection → Database</p><p>When your application calls dataSource.getConnection(), HikariCP attempts to provide an available connection from the pool. If no connection is available, the requesting thread waits until one becomes available or the acquisition timeout expires.</p><p>Once the application finishes using the connection, calling Connection.close() normally returns it to the pool instead of closing the underlying physical connection.</p><p>Consider this example:</p><pre>try (Connection connection = dataSource.getConnection();<br>     PreparedStatement ps = connection.prepareStatement(<br>         &quot;SELECT balance FROM accounts WHERE id = ?&quot;)) {<br><br>    ps.setLong(1, 101L);<br><br>    try (ResultSet rs = ps.executeQuery()) {<br>        if (rs.next()) {<br>            System.out.println(rs.getBigDecimal(&quot;balance&quot;));<br>        }<br>    }<br>}</pre><p>The try-with-resources block ensures that the JDBC resources are closed correctly. The connection is returned to HikariCP even if an exception occurs.</p><p><strong>Important:</strong> Closing a pooled connection is a logical release operation, not necessarily a physical database disconnection.</p><h3>2. How HikariCP Manages Concurrency</h3><p>HikariCP uses a concurrent connection-bag abstraction to track connections and coordinate connection acquisition, creation, and return.</p><p>At a high level, connection acquisition involves:</p><ol><li>Attempting to acquire an available connection.</li><li>Waiting when all suitable connections are currently in use.</li><li>Creating additional connections when permitted by pool limits and pool state.</li><li>Failing with a connection timeout if a connection cannot be acquired within the configured deadline.</li></ol><p>HikariCP uses lightweight synchronization and thread-parking mechanisms to coordinate contention. It also tracks connection usage and supports leak detection for connections held beyond a configured threshold.</p><p>However, HikariCP does not make SQL queries intrinsically faster. Its primary responsibility is to manage database connections efficiently and limit concurrent database access.</p><p>Actual query performance still depends on execution plans, indexing, locking, I/O, transaction design, and database capacity.</p><h3>3. Why You Shouldn’t Deploy With Default HikariCP Configuration</h3><p>Spring Boot commonly uses a default HikariCP maximumPoolSize of 10 connections. This can be perfectly reasonable for a small application, but it should not be mistaken for a production capacity plan.</p><p>Imagine an API receiving hundreds of concurrent requests. If 10 requests occupy all available database connections, additional requests that need connections must wait.</p><p>The application may have spare CPU capacity, yet request latency continues increasing because database connection acquisition has become a bottleneck.</p><p>The opposite mistake is equally dangerous. Increasing the pool size without understanding database capacity can increase contention, memory usage, lock competition, and database scheduling overhead.</p><p>Default settings also cannot account for your infrastructure’s connection limits, transaction duration, latency objectives, or number of application replicas.</p><p>Consider these parameters:</p><ul><li>maximum-pool-size: Controls the maximum number of pooled connections.</li><li>connection-timeout: Controls how long a thread waits to acquire a connection.</li><li>max-lifetime: Controls the maximum lifetime of a pooled connection, subject to lifecycle rules.</li><li>idle-timeout: Controls retirement of excess idle connections.</li><li>leak-detection-threshold: Helps identify connections that remain checked out for unusually long periods.</li></ul><p>Production configuration should be deliberate, measured, and workload-specific.</p><h3>4. Configuring HikariCP in Spring Boot</h3><p>A typical PostgreSQL configuration might look like this:</p><pre>spring:<br>  datasource:<br>    url: jdbc:postgresql://localhost:5432/payments<br>    username: app_user<br>    password: ${DB_PASSWORD}<br>    hikari:<br>      pool-name: PaymentsPool<br>      maximum-pool-size: 20<br>      minimum-idle: 10<br>      connection-timeout: 3000<br>      validation-timeout: 1000<br>      idle-timeout: 600000<br>      max-lifetime: 1740000<br>      leak-detection-threshold: 60000</pre><p>These values are illustrative and must be validated against the actual workload.</p><p>Here is what matters technically:</p><p><strong>maximum-pool-size: 20</strong></p><p>The pool can provide at most 20 pooled connections simultaneously. This includes both active and idle connections. Once all 20 are checked out, additional borrowers must wait.</p><p><strong>minimum-idle: 10</strong></p><p>HikariCP attempts to maintain at least 10 idle connections when possible. Setting minimum-idle equal to maximum-pool-size effectively creates a fixed-size pool.</p><p><strong>connection-timeout: 3000</strong></p><p>A borrower waits up to approximately three seconds to acquire a connection before HikariCP throws a SQLException. This is an acquisition timeout, not a SQL execution timeout.</p><p><strong>max-lifetime: 1740000</strong></p><p>This configures a maximum connection lifetime of 29 minutes. It is useful when retiring connections before infrastructure-imposed connection limits. HikariCP applies lifecycle rules and does not normally retire a connection while it is checked out.</p><p><strong>idle-timeout: 600000</strong></p><p>An idle connection can be retired after approximately 10 minutes when the pool has more connections than its configured minimum idle target. This setting does not force the pool below its minimum idle target.</p><p><strong>leak-detection-threshold: 60000</strong></p><p>HikariCP logs a warning when a connection remains checked out beyond the configured threshold. This is a diagnostic mechanism, not an automatic connection-reclamation mechanism. Long-running legitimate operations can also trigger warnings.</p><h3>5. Pool Sizing: Why More Connections Can Make Things Worse</h3><p>A common misconception is that a larger connection pool automatically increases throughput.</p><p>It does not.</p><p>Suppose your application has 100 request threads and a pool size of 20. Only 20 threads can hold connections from that pool simultaneously. The remaining threads may wait if they need database access.</p><p>Increasing the pool to 100 allows more concurrent database operations, but it also exposes the database to more simultaneous work. If the database is already CPU-bound or experiencing lock contention, the additional concurrency can reduce overall throughput.</p><p>A commonly cited starting heuristic is:</p><blockquote><strong>Pool Size ≈ (2 × CPU Cores) + Effective Spindle Count</strong></blockquote><p>This is a rough heuristic, not a universal sizing formula. It should not replace workload testing, especially for SSD-backed databases, cloud infrastructure, or workloads dominated by network and I/O waits.</p><p>A more useful approach is to measure:</p><ul><li>Database query execution time.</li><li>Connection acquisition latency.</li><li>Transaction duration.</li><li>Database CPU utilization and lock contention.</li><li>Active connections and pending borrowers.</li><li>Throughput and tail latency under realistic load.</li></ul><p>The objective is to identify the pool size at which the database achieves healthy throughput without excessive contention.</p><h3>The Multi-Instance Problem</h3><p>Pool sizing becomes more important when deploying multiple application replicas.</p><blockquote><strong>Total Connections = Number of Instances × Pool Size</strong></blockquote><p>For example, 10 application instances with a maximum pool size of 20 can potentially consume 200 database connections.</p><p>That total must fit within the database’s connection budget, accounting for other services, background workers, monitoring, migrations, and administrative sessions.</p><p>A pool size that works perfectly for one instance may overwhelm the database after horizontal scaling.</p><h3>6. Diagnosing HikariCP Pool Exhaustion</h3><p>A slow API does not necessarily indicate slow SQL. The request may be waiting for a database connection before the query even starts. HikariCP exposes metrics that help distinguish connection contention from query latency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*U8yBAS386rE2q177y-JxhQ.png" /></figure><p>These metrics can be collected through Spring Boot Actuator and Micrometer, depending on your dependencies and monitoring configuration.</p><p>A common warning sign is sustained maximum active connections combined with increasing pending borrowers and connection timeouts.</p><p>Investigate the underlying cause before increasing the pool size.</p><p>Potential causes include:</p><ul><li>Long-running SQL queries.</li><li>Missing indexes and inefficient execution plans.</li><li>Transactions holding connections longer than necessary.</li><li>Database lock contention.</li><li>Connections not being released correctly.</li><li>Excessive concurrent database access.</li><li>Database CPU, memory, or I/O saturation.</li></ul><p>For example, consider a service that starts a transaction, executes a query, makes an external HTTP request, and then commits.</p><p>The connection may remain occupied throughout the external request even though the database is doing no useful work during that interval.</p><p>Keeping transactions short and avoiding network calls inside them where possible reduces unnecessary connection occupancy.</p><h3>7. Connection Pooling Is Not a Substitute for Query Optimization</h3><p>HikariCP cannot compensate for inefficient SQL or poor transaction design.</p><p>Consider a query that scans millions of rows because the filtering column lacks an appropriate index. Increasing the connection pool may allow more copies of that expensive query to run simultaneously, increasing database pressure.</p><p>Similarly, a connection leak can exhaust even a generously sized pool if application code fails to release connections. The correct optimization sequence is to measure acquisition latency, inspect SQL execution plans, analyze transaction duration, and evaluate database resource utilization. Only then should pool sizing be adjusted.</p><h3><strong>Conclusion</strong></h3><p>HikariCP is a connection lifecycle and concurrency-management layer, not a query optimizer.</p><p>Its effectiveness depends on correct connection handling, workload-aware pool sizing, appropriate timeout configuration, database capacity, and observability.</p><p><strong>The goal is not to maximize the number of connections. It is to maximize useful database throughput while keeping connection acquisition predictable and resource contention under control.</strong></p><p>Before deploying a Spring Boot application to production, establish a connection budget, test realistic concurrency, monitor pool metrics, and validate configuration against the behavior of the actual database.</p><p>Defaults are a starting point, not a performance guarantee.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2eb40fe054ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to deploy without taking a downtime?]]></title>
            <link>https://medium.com/@kariapratham/how-to-deploy-without-taking-a-downtime-6c96441d5e4d?source=rss-962bc4bfa4fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c96441d5e4d</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[blue-green-deployment]]></category>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[zero-downtime]]></category>
            <dc:creator><![CDATA[Pratham Karia]]></dc:creator>
            <pubDate>Thu, 23 Jul 2026 11:56:54 GMT</pubDate>
            <atom:updated>2026-07-23T11:56:54.672Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rupo18r2vAnwCBGSKFZWvA.png" /></figure><p>Modern distributed systems operate under an expectation of continuous availability. Whether you’re processing payment transactions, serving millions of API requests, or running mission-critical enterprise applications, even a few seconds of downtime during deployment can lead to revenue loss, failed transactions, degraded customer trust, and SLA violations.</p><p>Traditional deployment methods often involve stopping the currently running application, deploying a new version, and restarting services. During this window, users experience HTTP 502/503 errors, connection failures, or partial system outages.</p><p>Blue-Green Deployment eliminates this problem by maintaining two identical production environments and switching traffic between them only after the new version has been completely validated.</p><p>This article explores Blue-Green Deployment from an infrastructure, networking, application, and database perspective, along with implementation patterns used in enterprise-scale production systems.</p><h3>The Problem with Traditional Deployments</h3><p>A conventional deployment typically follows this sequence:</p><pre>1. Stop Application<br>2. Copy new artifacts<br>3. Restart services<br>4. Wait for startup<br>5. Verify application<br>6. Accept traffic</pre><p>During restart:</p><ul><li>Active TCP connections terminate.</li><li>Reverse proxies return HTTP 502/503.</li><li>JVM warm-up increases latency.</li><li>Cache becomes cold.</li><li>Database connection pools need rebuilding.</li><li>Health checks fail temporarily.</li></ul><p>If the application startup takes:</p><ul><li>Spring Boot : 30 seconds</li><li>.NET : 15 seconds</li><li>Node.js : 5 seconds</li></ul><p>that entire period represents production downtime.</p><p>Rollback is equally problematic because another deployment cycle is required.</p><h3>The Core Principle</h3><p>Blue-Green deployment solves this by maintaining <strong>two independent production environments</strong>.</p><pre>           Users<br>             |<br>      Load Balancer<br>        /         \<br>     Blue        Green</pre><p>Only one environment receives production traffic.</p><p>The second environment remains idle but fully operational.</p><p>For example:</p><pre>Blue<br>Version : v1.4.2<br>Traffic : 100%</pre><pre>Green<br>Version : v1.5.0<br>Traffic : 0%</pre><p>Both environments contain:</p><ul><li>identical infrastructure</li><li>identical database connectivity</li><li>identical secrets</li><li>same network topology</li><li>same monitoring</li><li>same autoscaling policies</li></ul><p>The only difference is the application version.</p><h3>Deployment Workflow</h3><p>Instead of replacing the existing application, a completely new environment is prepared.</p><p>Deploy v2</p><pre>Users<br>   |<br>Load Balancer<br>      |<br>     Blue (v1)</pre><pre>Deploy</pre><pre>Green (v2)</pre><p>After deployment:</p><ul><li>JVM starts</li><li>Dependency Injection initializes</li><li>Connection pools are created</li><li>Redis connections establish</li><li>Kafka consumers initialize</li><li>Application caches warm</li><li>Health checks pass</li></ul><p>At this stage users are still using Blue.</p><p>No production traffic reaches Green.</p><h3>Validation Phase</h3><p>Production deployment should never immediately switch traffic.</p><p>Instead perform:</p><ul><li>Smoke tests</li><li>API validation</li><li>Authentication tests</li><li>Payment flow validation</li><li>Database migration verification</li><li>External integration verification</li><li>Cache verification</li><li>Load testing</li><li>Synthetic monitoring</li></ul><p>Example:</p><pre>curl https://green.example.com/actuator/health</pre><pre>{<br>   &quot;status&quot;:&quot;UP&quot;<br>}</pre><p>Only after all validation succeeds should traffic be switched.</p><h3>Traffic Switching</h3><p>Traffic switching should be atomic.</p><p>Example using a load balancer:</p><p>Before</p><pre>Blue  -&gt; 100%<br>Green -&gt; 0%</pre><p>After switch</p><pre>Blue -&gt; 0%<br>Green -&gt; 100%</pre><p>The switch usually takes milliseconds.</p><p>Users experience no interruption because:</p><ul><li>TCP connections remain valid</li><li>Reverse proxy simply forwards new requests</li><li>Existing requests complete normally</li><li>New requests reach Green</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*-u78nP7xS2IL8x_2khnTiA.png" /><figcaption>Blue-Green Deployment using Nginx</figcaption></figure><h3>Infrastructure Architecture</h3><pre>                    Internet<br>                       |<br>                 Load Balancer<br>                       |<br>          ----------------------------<br>          |                          |<br>     Blue Environment          Green Environment<br>          |                          |<br>   Spring Boot API             Spring Boot API<br>          |                          |<br>       Redis                    Redis<br>          |                          |<br>       Database (Shared)</pre><p>The infrastructure should be completely identical.</p><p>Configuration drift between environments defeats the purpose of Blue-Green deployments.</p><p>Infrastructure-as-Code tools such as Terraform, CloudFormation, or Ansible are commonly used to guarantee identical environments.</p><h3>Health Checks</h3><p>Health checks are critical.</p><p>Never switch traffic solely because the application process is running.</p><p>Health endpoints should verify:</p><ul><li>database connectivity</li><li>Redis availability</li><li>message broker connectivity</li><li>disk availability</li><li>thread pool saturation</li><li>downstream APIs</li><li>application readiness</li></ul><p>Spring Boot example:</p><pre>management.endpoint.health.probes.enabled=true<br>management.health.readinessstate.enabled=true<br>management.health.livenessstate.enabled=true</pre><p>The load balancer should only route traffic after readiness checks return healthy.</p><h3>Database Challenges</h3><p>The database is often the most complex aspect of Blue-Green deployment because both application versions typically share the same database.</p><p>Example:</p><pre>Blue (v1)<br>          \<br>           Shared Database<br>          /<br>Green (v2)</pre><p>If the new version introduces incompatible schema changes, Blue may stop functioning immediately after migration.</p><h3>Expand-and-Contract Database Pattern</h3><p>Instead of destructive migrations:</p><h3>Phase 1</h3><p>Add new columns.</p><pre>ALTER TABLE customer<br>ADD COLUMN phone_number VARCHAR(20);</pre><p>Blue ignores the new column.</p><p>Green begins using it.</p><h3>Phase 2</h3><p>Deploy Green.</p><p>Both versions function correctly.</p><h3>Phase 3</h3><p>Migrate existing data.</p><h3>Phase 4</h3><p>Switch traffic.</p><h3>Phase 5</h3><p>Remove obsolete columns in a later release.</p><p>This pattern ensures backward compatibility throughout the deployment process.</p><h3>Cache Warming</h3><p>Cold caches often produce latency spikes after switching.</p><p>Before traffic cutover:</p><pre>Warm Redis</pre><pre>Load Product Cache</pre><pre>Load User Permissions</pre><pre>Load Configuration</pre><pre>Load Exchange Rates</pre><p>By pre-populating caches, Green begins serving requests with production-level performance immediately.</p><h3>Connection Draining</h3><p>Switching traffic instantly may terminate long-running requests.</p><p>Instead:</p><pre>Blue</pre><pre>Stop accepting new requests</pre><pre>↓</pre><pre>Complete existing requests</pre><pre>↓</pre><pre>Shutdown</pre><p>Most load balancers support connection draining.</p><p>Examples include:</p><ul><li>AWS ALB</li><li>NGINX</li><li>HAProxy</li></ul><p>This prevents interrupted uploads, payment processing, and streaming requests.</p><h3>Rollback Strategy</h3><p>One of Blue-Green Deployment’s greatest advantages is rollback simplicity.</p><p>Suppose:</p><pre>Blue : v1</pre><pre>Green : v2</pre><p>Traffic switches.</p><p>An unexpected production issue appears.</p><p>Rollback becomes:</p><pre>Blue -&gt; 100%<br>Green -&gt; 0%</pre><p>The rollback completes within seconds because the previous version is still running.</p><p>Traditional rollback would require:</p><ul><li>redeployment</li><li>application restart</li><li>cache rebuilding</li><li>JVM startup</li><li>validation</li></ul><p>Blue-Green avoids all of these.</p><h3>Conclusion</h3><p>Blue-Green Deployment is more than a deployment technique, it is an architectural strategy that decouples software release from production availability. By maintaining two identical environments and shifting traffic only after the new version has been thoroughly validated, organizations can deploy with virtually no downtime while preserving the ability to roll back within seconds.</p><p>Implementing Blue-Green successfully requires careful consideration of networking, load balancing, health checks, database evolution, session management, cache behavior, and observability. When combined with robust CI/CD automation and backward-compatible database practices, it enables highly reliable software delivery for systems where availability is non-negotiable.</p><p>As modern applications continue to demand continuous delivery without service interruption, Blue-Green Deployment remains one of the most effective patterns for achieving resilient, zero-downtime releases at scale.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c96441d5e4d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Offset vs Cursor Pagination: Which One Should You Use in High-Performance APIs?]]></title>
            <link>https://medium.com/@kariapratham/offset-vs-cursor-pagination-which-one-should-you-use-in-high-performance-apis-d65d05f04854?source=rss-962bc4bfa4fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/d65d05f04854</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[cursor-based-pagination]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[pagination]]></category>
            <category><![CDATA[offset-based-pagination]]></category>
            <dc:creator><![CDATA[Pratham Karia]]></dc:creator>
            <pubDate>Sun, 05 Jul 2026 13:33:23 GMT</pubDate>
            <atom:updated>2026-07-05T13:33:23.186Z</atom:updated>
            <content:encoded><![CDATA[<p>Pagination is one of those features that almost every backend developer implements, yet it’s surprisingly easy to get wrong.</p><p>Most applications start with <strong>OFFSET/LIMIT</strong> because it’s simple and supported by virtually every database. It works well during development when there are only a few hundred rows.</p><p>Then the application grows.</p><p>Your table reaches millions of records.</p><p>Users start requesting page 500.</p><p>Queries become slower.</p><p>Records start appearing twice or disappearing entirely.</p><p>This is where many engineering teams discover <strong>cursor-based pagination</strong>.</p><p>In this article, we’ll dive deep into how both pagination techniques work internally, why offset pagination slows down at scale, and when cursor pagination becomes the better choice.</p><h3>Why Do We Need Pagination?</h3><p>Imagine an orders table with <strong>50 million rows</strong>.</p><pre>ID          Customer      Amount<br>------------------------------------<br>1           Alice         120<br>2           Bob           450<br>3           Charlie       900<br>...<br>50,000,000</pre><p>Returning every row in a single API response would:</p><ul><li>Consume huge amounts of memory</li><li>Increase network latency</li><li>Slow down serialization</li><li>Increase database load</li><li>Provide a poor user experience</li></ul><p>Instead, APIs return only a small subset of data.</p><p>For example:</p><pre>GET /orders?page=2&amp;size=20</pre><p>or</p><pre>GET /orders?cursor=1245890&amp;limit=20</pre><p>Both return 20 records.</p><p>The difference lies in <strong>how the database finds those records</strong>.</p><h3>Offset-Based Pagination</h3><p>Offset pagination is the most familiar approach.</p><p>Example:</p><pre>SELECT *<br>FROM orders<br>ORDER BY id<br>LIMIT 20 OFFSET 40;</pre><p>This means:</p><ul><li>Skip the first 40 rows</li><li>Return the next 20</li></ul><p>If page size is 20:</p><pre>Page            Offset<br>1                 0<br>2                 20<br>3                 40<br>10                180<br>100               1980</pre><p>Very straightforward.</p><h3>What Happens Internally?</h3><p>Many developers think the database jumps directly to row number 40.</p><p>It doesn’t.</p><p>Imagine the database executing:</p><pre>1<br>2<br>3<br>4<br>5<br>...<br>40<br>41<br>42<br>43<br>...<br>60</pre><p>To return rows <strong>41–60</strong>, the database still has to walk through the previous 40 rows.</p><p>Now imagine:</p><pre>OFFSET 5000000</pre><p>The database effectively needs to traverse millions of entries before returning the requested page.</p><p>Even with indexes, this work isn’t free.</p><h3>Why OFFSET Gets Slower</h3><p>Suppose your table contains <strong>10 million rows</strong>.</p><p>Requesting:</p><pre>LIMIT 20 OFFSET 9000000</pre><p>means the database will approximately:</p><pre>Read row 1 <br>  ↓ <br>Read row 2 <br>  ↓ <br>Read row 3 <br>  ↓ <br> ... <br>  ↓ <br>Read row 8,999,999 <br>  ↓ <br>Read row 9,000,000 <br>  ↓<br>Finally return 20 rows</pre><p>Notice something? You only needed <strong>20 rows</strong>, but the database examined millions. This is why response time grows as page numbers increase. The query becomes progressively slower.</p><h3>Another Hidden Problem: Inconsistent Results</h3><p>Consider this data.</p><pre>1<br>2<br>3<br>4<br>5<br>6<br>7<br>8<br>9<br>10</pre><p>Page size:</p><pre>5</pre><p>User requests:</p><pre>  Page 1<br><br>1 2 3 4 5</pre><p>Before requesting page 2, another user inserts:</p><pre>0</pre><p>Now the table becomes:</p><pre>0<br>1<br>2<br>3<br>4<br>5<br>6<br>7<br>8<br>9<br>10</pre><p>Page 2 becomes:</p><pre>5<br>6<br>7<br>8<br>9</pre><p>Notice that <strong>5 appears twice</strong>.</p><p>Similarly, deleting rows can cause records to be skipped entirely.</p><p>This issue becomes common in systems with frequent writes, such as:</p><ul><li>Social media feeds</li><li>Banking transactions</li><li>Order management systems</li><li>Notification services</li></ul><h3>Cursor-Based Pagination</h3><p>Cursor pagination solves this differently.</p><p>Instead of saying:</p><blockquote><em>Skip 1 million rows</em></blockquote><p>It says:</p><blockquote><em>Continue after this record.</em></blockquote><p>Example:</p><pre>SELECT *<br>FROM orders<br>WHERE id &gt; 5000<br>ORDER BY id<br>LIMIT 20;</pre><p>The cursor is simply: 5000</p><p>The next request becomes:</p><pre>GET /orders?cursor=5000&amp;limit=20</pre><h3>Why This Is Faster</h3><p>Suppose the primary key is indexed.</p><p>The database can directly locate: 5000</p><p>using the index.</p><p>Then read:</p><pre>5001</pre><pre>5002</pre><pre>5003</pre><pre>...</pre><pre>5020</pre><p>No scanning of previous millions of rows.</p><p>No skipping.</p><p>Just a direct lookup.</p><h3>Internally It Looks Like This</h3><p>Instead of:</p><pre>1</pre><pre>↓</pre><pre>2</pre><pre>↓</pre><pre>3</pre><pre>↓</pre><pre>...</pre><pre>↓</pre><pre>5,000,000</pre><pre>↓</pre><pre>Return 20</pre><p>The index performs something closer to:</p><pre>Index Lookup</pre><pre> ↓</pre><pre>5000</pre><pre> ↓</pre><pre>5001</pre><pre> ↓</pre><pre>5002</pre><pre> ↓</pre><pre>...</pre><pre> ↓</pre><pre>5020</pre><p>The work remains almost constant regardless of table size.</p><h3>Composite Cursors</h3><p>Real systems don’t always sort by ID. Suppose you’re sorting by:</p><pre>created_at DESC</pre><p>Multiple rows may share the same timestamp. Instead of using only:</p><pre>created_at</pre><p>we combine it with a unique column.</p><p>Example:</p><pre>WHERE<br>(created_at, id)<br>&lt;<br>(&#39;2026-07-01 10:15:30&#39;, 81293)</pre><p>This guarantees deterministic ordering.</p><h3>Cursor Example</h3><p>Page 1</p><pre>ID</pre><pre>101</pre><pre>102</pre><pre>103</pre><pre>104</pre><pre>105</pre><p>Cursor:</p><pre>105</pre><p>Next query:</p><pre>SELECT *<br>FROM orders<br>WHERE id &gt; 105<br>LIMIT 5;</pre><p>Result:</p><pre>106</pre><pre>107</pre><pre>108</pre><pre>109</pre><pre>110</pre><p>The cursor always points to the last item the client has already seen.</p><h3>What Happens During Inserts?</h3><p>Suppose the user has already loaded:</p><pre>101</pre><pre>102</pre><pre>103</pre><pre>104</pre><pre>105</pre><p>Cursor:</p><pre>105</pre><p>Meanwhile another order arrives:</p><pre>106</pre><p>Next query:</p><pre>WHERE id &gt; 105</pre><p>Result:</p><pre>106</pre><pre>107</pre><pre>108</pre><p>No duplicates.</p><p>No skipped rows.</p><p>The dataset remains consistent.</p><h3>API Design</h3><p>Offset pagination:</p><pre>GET /orders?page=15&amp;size=20</pre><p>Response</p><pre>{<br>  &quot;page&quot;:15,<br>  &quot;size&quot;:20,<br>  &quot;totalPages&quot;:842,<br>  &quot;totalElements&quot;:16831,<br>  &quot;content&quot;:[]<br>}</pre><p>Cursor pagination:</p><pre>GET /orders?cursor=12456&amp;limit=20</pre><p>Response</p><pre>{<br>  &quot;nextCursor&quot;:&quot;12476&quot;,<br>  &quot;hasMore&quot;:true,<br>  &quot;content&quot;:[]<br>}</pre><p>Notice there is no page number.</p><p>The client simply keeps asking for the next cursor.</p><h3>Performance Comparison</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CTtSjJCyCnv0uY5lAYh15w.png" /></figure><h3>When Offset Pagination Makes Sense</h3><p>Offset pagination is still perfectly acceptable when:</p><ul><li>Tables are relatively small</li><li>Users need page numbers</li><li>Administrative dashboards</li><li>Reporting screens</li><li>Back-office applications</li><li>SQL complexity should remain minimal</li></ul><p>Examples:</p><pre>Employee Management<br>Customer List<br>Inventory<br>Invoices<br>Admin Portal</pre><h3>When Cursor Pagination Is Better</h3><p>Cursor pagination is the preferred choice when:</p><ul><li>Millions of records exist</li><li>Data changes frequently</li><li>APIs serve mobile applications</li><li>Infinite scrolling feeds</li><li>Chat applications</li><li>Payment history</li><li>Transaction logs</li><li>Event streams</li><li>Audit logs</li></ul><p>Examples include:</p><pre>Twitter Feed<br>Instagram Feed<br>LinkedIn Timeline<br>GitHub Events<br>Bank Transactions<br>Payment Gateway Logs</pre><h3>What About UUIDs?</h3><p>Many modern applications use UUIDs instead of auto-increment IDs.</p><p>Can cursor pagination still work?</p><p>Yes.</p><p>As long as the ordering column is indexed and deterministic.</p><p>For example:</p><pre>ORDER BY created_at DESC, uuid DESC</pre><p>The cursor becomes:</p><pre>created_at</pre><pre>+</pre><pre>uuid</pre><p>The principle remains identical.</p><h3>Can Cursor Pagination Go Backwards?</h3><p>Yes, but it’s more complicated.</p><p>Instead of:</p><pre>id &gt; cursor</pre><p>you query:</p><pre>id &lt; cursor</pre><p>while reversing the sort order.</p><p>Many APIs simply support <strong>Next</strong> because infinite scrolling doesn’t require arbitrary page navigation.</p><h3>Final Thoughts</h3><p>Offset pagination is simple, intuitive, and works well for small datasets. However, as tables grow, the database spends increasing amounts of time scanning rows that will ultimately be discarded. In highly dynamic datasets, inserts and deletes can also lead to duplicate or missing records between page requests.</p><p>Cursor pagination approaches the problem differently. Rather than counting how many rows to skip, it uses the last seen record as the starting point for the next query. This allows the database to leverage indexes efficiently, keeps query performance nearly constant as data grows, and provides more stable results in systems where records are continuously being added or removed.</p><p>There isn’t a universally “better” pagination strategy. The right choice depends on the type of application you’re building. If users need direct access to page numbers, such as in an admin dashboard or reporting interface, offset pagination is often the simplest solution. But if you’re building high-traffic APIs, mobile applications, transaction histories, or infinite-scrolling feeds, cursor pagination offers significantly better scalability and consistency.</p><p>Choosing the right pagination strategy early can save substantial performance tuning later, especially as your application scales from thousands to millions of records.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d65d05f04854" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Virtual Threads Reduced Our Spring Boot Memory by 72%]]></title>
            <link>https://medium.com/@kariapratham/how-virtual-threads-reduced-our-spring-boot-memory-by-72-07310e75afd0?source=rss-962bc4bfa4fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/07310e75afd0</guid>
            <category><![CDATA[java-virtual-threads]]></category>
            <category><![CDATA[java-spring-boot]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[virtual-threads]]></category>
            <dc:creator><![CDATA[Pratham Karia]]></dc:creator>
            <pubDate>Fri, 03 Jul 2026 07:40:10 GMT</pubDate>
            <atom:updated>2026-07-03T07:40:10.892Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*dtgs2R6DnPJSxRY7F6p2Ig.jpeg" /></figure><p>For years, the standard approach to building high-concurrency Java applications was simple: add more threads, increase the thread pool, tune the JVM, and hope the hardware keeps up.</p><p>That strategy works, until it doesn’t.</p><p>As our <strong>Interoperable Cardless Cash Withdrawal (ICCW)</strong> middleware handled increasing production traffic, we discovered that the biggest bottleneck wasn’t CPU or database performance.</p><p>It was the cost of traditional threads.</p><p>After migrating the application to <strong>Java Virtual Threads (Project Loom)</strong>, our production memory usage during peak traffic dropped from approximately <strong>2 GB</strong> to around <strong>550 MB</strong>, while maintaining the same business logic, same APIs, and same infrastructure.</p><p>This article explains exactly why that happened, what Virtual Threads changed internally, and why they are an excellent fit for synchronous payment systems.</p><h3>What is ICCW?</h3><p><strong>Interoperable Cardless Cash Withdrawal (ICCW)</strong> enables users to withdraw cash from an ATM without inserting a debit card. Instead of authenticating with a physical card, the ATM generates a QR code that is scanned using any supported UPI application.</p><p>At a high level, the transaction looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gNXhCC3IC3xOMBymeFxw6g.png" /></figure><p>The middleware acts as the orchestration layer between the ATM network and the UPI ecosystem. Every stage of the transaction is synchronous and highly latency-sensitive. The ATM is continuously waiting for responses before moving to the next step.</p><h3>Why Threading Became a Bottleneck</h3><p>Although the system performs payment processing, it actually spends a surprisingly small amount of time executing Java code. Most of the request lifecycle is spent waiting.</p><p>From the JVM’s perspective, the thread is doing almost nothing while waiting for the network. Yet with platform threads, that waiting thread still consumes valuable operating system resources.</p><p>Multiply that by thousands of simultaneous ATM transactions and the cost becomes significant.</p><h3>The Hidden Cost of Platform Threads</h3><p>Traditional Java threads are <strong>OS threads</strong>. Each request typically occupies one thread until the transaction finishes.</p><p>Even if the thread is blocked on a network call, it still owns:</p><ul><li>Native thread resources</li><li>Dedicated stack memory</li><li>JVM metadata</li><li>Scheduling overhead by the operating system</li></ul><p>A default platform thread often reserves around <strong>1 MB of stack memory</strong> (configurable with -Xss).</p><p>The important point isn’t that every thread immediately uses the full megabyte, it doesn’t. Instead, the JVM reserves a relatively large stack for every thread, and maintaining thousands of these threads introduces substantial memory overhead and operating system scheduling costs.</p><p>Imagine only 2,000 concurrent requests.</p><pre>2000 Platform Threads<br>≈ 2000 MB Reserved Stack Space<br>+ Heap Objects<br>+ Thread Metadata<br>+ Context Switching</pre><p>Even if the CPU utilization is low, memory usage continues increasing simply because every blocked request occupies an expensive operating system thread.</p><h3>Why Payment Systems Are Different</h3><p>Unlike CPU-intensive workloads such as video encoding or image processing, payment systems are mostly waiting for external systems.</p><p>For a single ATM transaction, the middleware waits for:</p><ul><li>UPI Switch responses</li><li>Network latency</li><li>External payment processing</li><li>ATM acknowledgements</li></ul><p>The CPU performs work for only a tiny fraction of the request lifecycle. The rest is idle waiting. That makes the workload an ideal candidate for Virtual Threads.</p><h3>Enter Java Virtual Threads</h3><p>Virtual Threads were introduced as part of <strong>Project Loom</strong> in Java 21.</p><p>Instead of mapping one Java thread directly to one operating system thread, the JVM schedules millions of lightweight virtual threads onto a much smaller pool of carrier threads.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HHNzH3K-5Wu_rtVsOKX9ww.png" /></figure><p>When a Virtual Thread performs a blocking operation such as an HTTP call, the JVM detaches it from the carrier thread.</p><p>That carrier thread immediately starts executing another Virtual Thread.</p><p>Once the network response arrives, the Virtual Thread resumes execution exactly where it paused.</p><ol><li>No callbacks.</li><li>No reactive programming.</li><li>No complicated asynchronous code.</li></ol><h3>Our Migration</h3><p>One of the biggest advantages of Virtual Threads is how little application code actually changes.</p><p>Our service layer continued using synchronous REST calls.</p><ol><li>Validation logic remained unchanged.</li><li>Database access remained unchanged.</li><li>Business logic remained unchanged.</li></ol><p>Instead of tuning larger thread pools, we configured Spring Boot to execute requests using Virtual Threads.</p><p>The programming model stayed imperative:</p><pre>validateRequest();<br>callUpiSwitch();<br>processResponse();<br>return response;</pre><p>Developers continued writing normal blocking code, while the JVM handled scheduling efficiently underneath. Instead of wasting operating system threads, the JVM efficiently schedules new work while previous requests wait for external systems.</p><h3>Production Results</h3><p>After migrating to Virtual Threads, the production improvements were immediately visible. The most noticeable improvement was memory consumption. The application handled the same workload while using roughly <strong>72% less memory</strong>. This reduction also lowered garbage collection pressure and allowed the JVM to spend less time managing thread-related overhead.</p><h3>Why the Memory Reduction Was So Significant</h3><p>The improvement wasn’t because our business objects became smaller. It wasn’t because JSON serialization became faster. It wasn’t because database queries changed.</p><p>The biggest difference was that we no longer needed thousands of heavyweight platform threads waiting on network calls.</p><p>Virtual Threads transformed blocked waiting into inexpensive suspended continuations managed by the JVM. Instead of allocating large native stacks for every concurrent request, the JVM stores only the execution state required to resume processing later. For I/O-bound applications, this dramatically improves scalability.</p><h3>When They Won’t Help Much</h3><p>Virtual Threads are not a universal performance solution. Applications dominated by CPU-intensive work, such as encryption-heavy batch jobs, video processing, machine learning inference, or image rendering, are still constrained primarily by available processor cores.</p><p>Virtual Threads improve concurrency, not raw computational throughput.</p><h3>Lessons Learned</h3><p>One of the biggest misconceptions is that more threads automatically mean more performance.</p><p>In reality, more operating system threads often mean:</p><ul><li>Higher memory consumption</li><li>Increased context switching</li><li>More scheduler overhead</li><li>Diminishing returns under load</li></ul><p>Virtual Threads change this equation.</p><p>By allowing millions of lightweight concurrent tasks without requiring millions of operating system threads, they let developers keep the simplicity of synchronous programming while achieving scalability previously associated with asynchronous frameworks.</p><p>Our migration required minimal code changes, preserved the readability of the codebase, and reduced peak production memory consumption from approximately <strong>2 GB</strong> to <strong>550 MB</strong>.</p><p>For high-concurrency, I/O-bound systems, that’s a compelling reason to consider Virtual Threads as the default execution model in modern Java.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=07310e75afd0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why TanStack Query is Your New Best Friend?]]></title>
            <link>https://medium.com/@kariapratham/why-tanstack-query-is-your-new-best-friend-d69788cf4934?source=rss-962bc4bfa4fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/d69788cf4934</guid>
            <dc:creator><![CDATA[Pratham Karia]]></dc:creator>
            <pubDate>Sat, 03 Jan 2026 18:31:58 GMT</pubDate>
            <atom:updated>2026-01-03T18:31:58.346Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Tanstack Logo" src="https://cdn-images-1.medium.com/max/1000/0*o05ZyR_UCScM3Axy" /></figure><p>If you’ve been building React applications for a while, you’re likely familiar with the “Data Fetching Ceremony.” It usually looks something like this: define three pieces of state (data, isLoading, error), fire off a useEffect on mount, handle the promise, manually toggle the loading states, and hope you don&#39;t run into a race condition.</p><p>It works, but it’s repetitive, error-prone, and quite frankly, exhausting.</p><p>Enter <strong>TanStack Query</strong>. It’s not just a data-fetching library; it’s an asynchronous state manager that handles the “server state” so you don’t have to.</p><h3>1. The Problem with “Manual” Fetching</h3><p>In a standard React setup, your server data lives in useState. The problem is that server data is fundamentally different from client state (like a toggle or a form input). Server data is:</p><ul><li><strong>Remote:</strong> You don’t own it.</li><li><strong>Asynchronous:</strong> It takes time to arrive.</li><li><strong>Out of date:</strong> The moment you fetch it, it could have changed on the server.</li></ul><p>When you use useEffect, you are responsible for caching, re-fetching when the window is refocused, handling retries, and deduplicating requests. TanStack Query does all of this out of the box.</p><h3>2. Cleaner Code: Before vs. After</h3><p>Let’s look at a real-world example: fetching a list of users.</p><h3>The “Old” Way (Manual)</h3><pre>function Users() {<br>  const [users, setUsers] = useState([]);<br>  const [loading, setLoading] = useState(true);<br>  const [error, setError] = useState(null);<br><br>  useEffect(() =&gt; {<br>    let isMounted = true;<br><br>    fetch(&quot;/api/users&quot;)<br>      .then(res =&gt; res.json())<br>      .then(data =&gt; {<br>        if (isMounted) {<br>          setUsers(data);<br>          setLoading(false);<br>        }<br>      })<br>      .catch(err =&gt; {<br>        if (isMounted) {<br>          setError(err);<br>          setLoading(false);<br>        }<br>      });<br><br>   <br>    return () =&gt; {<br>      isMounted = false;<br>    };<br>  }, []);<br><br>  if (loading) return &lt;div&gt;Loading...&lt;/div&gt;;<br>  if (error) return &lt;div&gt;Error!&lt;/div&gt;;<br><br>  return (<br>    &lt;ul&gt;<br>      {users.map(u =&gt; (<br>        &lt;li key={u.id}&gt;{u.name}&lt;/li&gt;<br>      ))}<br>    &lt;/ul&gt;<br>  );<br>}</pre><h3>The TanStack Way</h3><pre>import { useQuery } from &#39;@tanstack/react-query&#39;;<br>function Users() {<br>  const { data: users, isLoading, error } = useQuery({<br>    queryKey: [&#39;users&#39;],<br>    queryFn: () =&gt; fetch(&#39;/api/users&#39;).then(res =&gt; res.json()),<br>  });<br>  if (isLoading) return &lt;div&gt;Loading...&lt;/div&gt;;<br>  if (error) return &lt;div&gt;Error!&lt;/div&gt;;<br>  return &lt;ul&gt;{users.map(u =&gt; &lt;li key={u.id}&gt;{u.name}&lt;/li&gt;)}&lt;/ul&gt;;<br>}</pre><p><strong>What did we gain? Boilerplate reduction:</strong> We removed 15 lines of state management.</p><ul><li><strong>Automatic Caching:</strong> If you navigate away and come back, the data is there instantly.</li><li><strong>Window Focus Refetching:</strong> If a user leaves your tab and comes back, TanStack Query automatically checks for updates.</li></ul><h3>3. The “Life-Saving” Features</h3><h3>Automatic Deduplication</h3><p>Imagine you have three different components on one page that all need the current user’s profile. With useEffect, you might accidentally trigger three separate API calls. TanStack Query recognizes they share the same queryKey and collapses them into a <strong>single request</strong>.</p><h3>Stale-While-Revalidate (SWR)</h3><p>This is the magic sauce. When you request data that is already in the cache, TanStack Query provides the “stale” data immediately (so the UI doesn’t flicker a loading spinner) and then fetches the “fresh” data in the background. Once the fresh data arrives, it silently updates the UI. It’s a seamless user experience.</p><h3>Easy Mutations</h3><p>Updating data is just as easy as fetching it. The useMutation hook handles the lifecycle of a POST or PUT request, allowing you to trigger &quot;Invalidations.&quot;</p><pre>const mutation = useMutation({<br>  mutationFn: (newTodo) =&gt; axios.post(&#39;/todos&#39;, newTodo),<br>  onSuccess: () =&gt; {<br>    // This tells TanStack Query that the &#39;todos&#39; list is now old<br>    // It will automatically refetch the list for you!<br>    queryClient.invalidateQueries({ queryKey: [&#39;todos&#39;] });<br>  },<br>});</pre><h3>4. Why It Truly Makes Life Easier</h3><p>The real win isn’t just less code; it’s <strong>mental overhead</strong>.</p><p>When using TanStack Query, you stop thinking about <em>how</em> to get the data and start thinking about <em>what</em> data your UI needs. You get a standardized way to handle errors, loading states, and pagination across your entire team.</p><p>Moreover, the <strong>TanStack DevTools</strong> give you a visual look into your cache, showing exactly what data is “fresh,” “stale,” or “inactive.” It’s like having an X-ray machine for your app’s data layer.</p><h3>Final Thoughts</h3><p>If you are still manually managing server state with useState and useEffect, you are working too hard. TanStack Query allows you to delete hundreds of lines of complex logic while simultaneously making your app faster and more resilient.</p><p>It’s not just a library; it’s a superpower for your frontend.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d69788cf4934" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling Bulk Upload in Spring Boot: Why Batching Made All the Difference]]></title>
            <link>https://medium.com/@kariapratham/handling-bulk-upload-in-spring-boot-why-batching-made-all-the-difference-44a12e7fa5a7?source=rss-962bc4bfa4fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/44a12e7fa5a7</guid>
            <category><![CDATA[batch-processing]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[bulk-uploading]]></category>
            <dc:creator><![CDATA[Pratham Karia]]></dc:creator>
            <pubDate>Sun, 14 Sep 2025 17:24:10 GMT</pubDate>
            <atom:updated>2025-09-14T17:25:59.603Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Spring batch image" src="https://cdn-images-1.medium.com/max/534/1*9ge51UR-eP_dalTPN9XeEg.png" /></figure><p>In my office I had to build a bulk upload feature that could handle extremely large Excel files, sometimes close to a million rows. At first I focused on the parsing side, starting with Apache POI and later trying FastExcel Reader. FastExcel was definitely faster and lighter, but I realized that parsing was not the real bottleneck. The real pain point was saving the data into the database.</p><p>My first version persisted rows one by one. It worked for small files, but with anything above a hundred thousand rows the performance collapsed. The database was flooded with insert statements, transactions piled up, and the upload took hours. It didn’t matter how fast I parsed the file, if the persistence layer was inefficient, the whole flow failed.</p><p>That’s when I shifted to batching. Instead of saving records individually, I grouped them into batches of a few hundred rows. After each batch, I flushed the persistence context and cleared it. This single change transformed the upload pipeline. A process that once took hours finished in minutes. For a million rows, batching brought the upload time down to a practical level and kept memory usage steady.</p><p>I also experimented with batch sizes. Too small and the overhead of flushing became noticeable, too large and the persistence context grew heavy. For my setup, batches of around 500 rows struck the right balance between throughput and stability.</p><p>Once I had batching working, another challenge showed up: user experience. Uploading such large files meant users had to wait a long time for the request to finish, sometimes staring at a spinning loader for minutes. That’s when I introduced async jobs. Instead of processing everything inside the same request, the file was accepted quickly, stored, and a background job was triggered to process it. Users could check the status later or get notified once the job was complete. This change made the system feel responsive, even when the backend was busy crunching through a million rows.</p><p>In the end, FastExcel helped me parse large files quickly, but batching and async jobs were what truly unlocked performance and usability at scale. Without batching, the database was the bottleneck. Without async jobs, the user experience was painful. With both in place, the system became capable of handling million-row imports reliably while keeping users happy.</p><p>For me the biggest lesson was clear: bulk upload is not just about how fast you can read a file. It’s about how you write to the database and how you design the flow so that users are not stuck waiting. Batching strategies decide the scalability, and async jobs decide the usability. Together they turn bulk upload from a fragile feature into something production-ready.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44a12e7fa5a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Get a Tech Job (And Lose Your Mind)]]></title>
            <link>https://medium.com/@kariapratham/how-to-get-a-tech-job-and-lose-your-mind-e3a2b7f0281c?source=rss-962bc4bfa4fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3a2b7f0281c</guid>
            <category><![CDATA[ghosting]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[satire]]></category>
            <category><![CDATA[job-hunting]]></category>
            <category><![CDATA[referrals]]></category>
            <dc:creator><![CDATA[Pratham Karia]]></dc:creator>
            <pubDate>Mon, 04 Aug 2025 03:22:54 GMT</pubDate>
            <atom:updated>2025-08-04T06:31:29.646Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Job Search Image" src="https://cdn-images-1.medium.com/max/284/1*6K2gMK4SXDP5umiOMYsTUg.jpeg" /></figure><h2>How to Get a Tech Job in 2025: Sell Your Soul, Solve 50,000 LeetCode Problems, and Learn Every Tech Ever Invented.</h2><blockquote>By: A surviving software engineer</blockquote><p>Ah yes, the noble quest for a tech job in 2025. Where once you could write a simple CRUD app and land a decent salary, today you must train like a Silicon Valley Avenger, mastering every programming language known to mankind while simultaneously inventing three new ones.</p><p>Let me take you through the average journey of a humble developer looking for a job in today’s AI-powered, blockchain-scented, cloud-deployed, containerized tech world.</p><p><strong>Step 1: Solve 50,000 DSA Questions or Die Trying</strong></p><p>You thought programming was about building cool stuff?</p><p>Nope.</p><p>You must now become a monk of the Temple of LeetCode. It is required – nay, expected – that you:</p><p>•	Sort linked lists in 47 different ways</p><p>•	Merge k sorted arrays using O(n log log n) time</p><p>•	Use DFS to find your lost motivation</p><p>One must meditate in binary trees and achieve enlightenment through dynamic programming. If your solution doesn’t run in constant time and constant space, congratulations – you’re unemployed.</p><p><strong>Step 2: Choose Your Final Boss: ML, AI, DevOps, or All of the Above</strong></p><p>Gone are the days of “Full Stack Developer.”</p><p>Now, every job posting wants a Machine Learning DevOps Blockchain Cloud AI Full Stack Prompt Engineer with LLM Experience.</p><p>You need to:</p><p>•	Build a CNN model that can detect sarcasm in recruiter emails</p><p>•	Write Terraform scripts in your sleep</p><p>•	Set up Kubernetes clusters on your iPhone</p><p>•	Prompt GPT-17 into building your portfolio site</p><p>•	And of course, fine-tune LLaMA-6 on a Raspberry Pi</p><p>Don’t know all this? That’s cute. Best of luck with your personal growth journey on LinkedIn.</p><p><strong>Step 3: Beg for Referrals Like You’re on a Digital Street Corner</strong></p><p>Hi, I hope you’re doing well! I came across your profile and was wondering if you’d be open to referring me for the SDE role at ZuckazonSoftAICloud. Thank you! 🙏</p><p>Send this 200 times. Receive:</p><p>•	3 replies saying “Sorry, the role is closed”</p><p>•	1 reply saying “Use the careers page”</p><p>•	46 “Seen”s and eternal silence</p><p>Sometimes you wonder if you should write code or start selling protein powder on Instagram.</p><p><strong>Step 4: The Interview Gauntlet</strong></p><p>Welcome to your first round:</p><p>“Design Twitter.”</p><p>You stutter, “Do you mean the UI?”</p><p>“No. All of Twitter.”</p><p>You mention you’ve never worked on a distributed system with 300 million users. The interviewer nods with disappointment. You’re supposed to have done that in your second-year internship. On the side. While learning Rust. During a hackathon. Blindfolded.</p><p><strong>Step 5: Soft Skills (A.K.A. Perform Emotional Gymnastics)</strong></p><p>You’re told soft skills matter. So you smile and say:</p><p>“I’m passionate about scalable systems.”</p><p>Which is a lie. You’re passionate about getting paid and not debugging race conditions at 2 AM.</p><p>Then comes the favorite question:</p><p>“Tell me about a time you failed.”</p><p>You answer, “This interview.”</p><p>You are correct.</p><p><strong>Step 6: Build a Portfolio Website That Uses Every Buzzword in Existence</strong></p><p>Your website must:</p><p>•	Be built with React, TypeScript, GraphQL, Tailwind, and Next.js</p><p>•	Be deployed on Vercel with CI/CD from GitHub Actions</p><p>•	Have a dark mode</p><p>•	Generate AI-written blogs explaining why you built the site</p><p>•	Have a chatbot that asks visitors for referrals</p><p>Bonus points if you’ve written “I’m passionate about technology” in Comic Sans.</p><p><strong>Step 7: Wait. Refresh. Wait. Refresh</strong>.</p><p>You’ve applied to 184 positions.</p><p>You’re ghosted by 179.</p><p>Rejected by 3 because “we decided to go with a candidate who better aligns with our blurry, undefined expectations.”</p><p>2 send you interviews.</p><p>1 wants you to build Twitter again.</p><p>And the last one? It was a phishing scam. You now also need to change your passwords.</p><p><strong>Step 8: Success! (Maybe)</strong></p><p>One day, a recruiter calls.</p><p>You brace yourself.</p><p>They offer you:</p><p>•	₹4.2 LPA</p><p>•	A 6-day workweek</p><p>•	No remote option</p><p>•	And the glorious title: Software Intern (Senior)</p><p>You accept.</p><p>Because rent is due.</p><p><strong>Conclusion</strong></p><p>Getting a tech job today is like fighting a boss battle where the boss changes form every five seconds and you’re handed a rubber duck as your weapon.</p><p>You’re expected to be:</p><p>•	A coding wizard</p><p>•	A systems design philosopher</p><p>•	A DevOps shaman</p><p>•	A networking ninja</p><p>•	An AI whisperer</p><p>But in the end, all you wanted was to build something cool, learn along the way, and maybe, just maybe, not have to cry in the bathroom during the “Tell me about yourself” round.</p><p>So if you’re on this journey right now – fighting through LeetCode, crafting the perfect cold email, and designing scalable versions of apps you don’t even use – just know:</p><p>You’re not alone.</p><p>You’re just stuck in Tech Job: The MMORPG.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3a2b7f0281c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why You Should Stop Using @Autowired in Spring]]></title>
            <link>https://medium.com/@kariapratham/why-you-should-stop-using-autowired-in-spring-7b2335e0e6cf?source=rss-962bc4bfa4fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b2335e0e6cf</guid>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[lombok]]></category>
            <category><![CDATA[constructor-injection]]></category>
            <category><![CDATA[springboot-best-practices]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <dc:creator><![CDATA[Pratham Karia]]></dc:creator>
            <pubDate>Mon, 23 Jun 2025 21:19:55 GMT</pubDate>
            <atom:updated>2025-06-23T21:19:55.648Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*BiVsZtSRkDQiUq1l.png" /></figure><p>For many Java developers working with Spring Boot, using @Autowired is a habit. It feels convenient. Add a field, annotate it, and Spring wires everything up. And yes, it works. But if you&#39;re aiming to write robust, testable, and maintainable code, it&#39;s time to reconsider this approach.</p><p>This article explains why using @Autowired on fields can lead to hidden dependencies, difficult testing, and unpredictable behavior. It also shows what you should use instead.</p><h3>The Problem with @Autowired Field Injection</h3><p>Let’s begin with a common example:</p><h4>1. Hidden Dependencies</h4><p>When you use field injection, dependencies are not visible in the constructor. This makes it harder to understand what a class depends on by just reading its definition.</p><pre>// ❌ Field Injection (bad)<br>@Component<br>public class OrderService {<br><br>    @Autowired<br>    private PaymentProcessor paymentProcessor;<br><br>    public void processOrder() {<br>        paymentProcessor.process();<br>    }<br>}</pre><p>Compare that with:</p><pre>// ✅ Constructor Injection (good)<br>@Component<br>public class OrderService {<br><br>    private final PaymentProcessor paymentProcessor;<br><br>    public OrderService(PaymentProcessor paymentProcessor) {<br>        this.paymentProcessor = paymentProcessor;<br>    }<br><br>    public void processOrder() {<br>        paymentProcessor.process();<br>    }<br>}</pre><p>Now it’s clear this class depends on PaymentProcessor. You can see it directly in the constructor.</p><h4>2. No Immutability</h4><p>With field injection, you can’t use final. That means dependencies can be changed after the object is created, even accidentally.</p><pre>// ❌ Mutable dependency<br>@Component<br>public class BillingService {<br><br>    @Autowired<br>    private Logger logger; // not final, can be reassigned<br>}</pre><p>This weakens your code&#39;s safety and predictability. With constructor injection, you can declare fields as final, ensuring they are assigned only once and never modified. This results in more stable objects and fewer side effects.</p><pre>// ✅ Immutable dependency<br>@Component<br>public class BillingService {<br><br>    private final Logger logger;<br><br>    public BillingService(Logger logger) {<br>        this.logger = logger;<br>    }<br>}</pre><p>This way, logger cannot be null or changed later.</p><h4>3. Difficult Testing</h4><p>Field injection makes mocking and unit testing more complex. You may need to use reflection or start a Spring context just to inject a mock.</p><pre>// ❌ Hard to test with field injection<br>BillingService service = new BillingService(); // doesn&#39;t compile<br>ReflectionTestUtils.setField(service, &quot;logger&quot;, mockLogger);</pre><p>With constructor injection, testing is simple and clean:</p><pre>// ✅ Easy unit test<br>Logger mockLogger = mock(Logger.class);<br>BillingService service = new BillingService(mockLogger);</pre><p>No Spring context needed, no hacks, just proper object-oriented programming.</p><h4>4. Lifecycle Surprises</h4><p>Spring injects fields <strong>after</strong> the constructor runs. If your constructor logic depends on injected fields, you’ll hit NullPointerException.</p><pre>// ❌ Unsafe usage<br>@Component<br>public class AlertService {<br><br>    @Autowired<br>    private MailService mailService;<br><br>    public AlertService() {<br>        mailService.send(&quot;App started&quot;); // NPE: mailService not injected yet<br>    }<br>}</pre><p>Constructor injection ensures dependencies are ready when the object is created:</p><pre>// ✅ Safe lifecycle<br>@Component<br>public class AlertService {<br><br>    private final MailService mailService;<br><br>    public AlertService(MailService mailService) {<br>        this.mailService = mailService;<br>        mailService.send(&quot;App started&quot;); // this works<br>    }<br>}</pre><h3>The Right Way: Constructor Injection</h3><p>Spring fully supports constructor injection. Since Spring 4.3, if your class has only one constructor, Spring will use it automatically, even without @Autowired.</p><p>With Lombok, this gets even cleaner:</p><pre>@RequiredArgsConstructor<br>@Service<br>public class InvoiceService {<br>    private final InvoiceRepository invoiceRepository;<br>}</pre><p>This style is concise, immutable, testable, and idiomatic.</p><h3>Is @Autowired Ever Okay?</h3><p>There are rare situations where field injection with @Autowired is acceptable, for example, in configuration classes or legacy systems where circular dependencies are unavoidable.</p><p>But in general application code, constructor injection is almost always the better choice.</p><p>Just because something works doesn’t mean it’s right. Field injection with @Autowired is a shortcut that creates long-term problems. It hides class dependencies, makes testing difficult, breaks object immutability, and leads to unpredictable behavior.</p><p>Constructor injection, especially when paired with tools like Lombok, is the recommended and modern way to write Spring code. It gives you clear structure, better maintainability, and a foundation for clean, scalable software.</p><p>Make the switch. Your future self and your teammates will thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b2335e0e6cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why You Must Override hashCode() When Overriding equals() in Java?]]></title>
            <link>https://medium.com/@kariapratham/why-you-must-override-hashcode-when-overriding-equals-in-java-221922fa7e46?source=rss-962bc4bfa4fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/221922fa7e46</guid>
            <category><![CDATA[equals-java]]></category>
            <category><![CDATA[java-object]]></category>
            <category><![CDATA[overriding]]></category>
            <category><![CDATA[java-best-practices]]></category>
            <category><![CDATA[hashset]]></category>
            <dc:creator><![CDATA[Pratham Karia]]></dc:creator>
            <pubDate>Sat, 21 Jun 2025 19:11:27 GMT</pubDate>
            <atom:updated>2025-06-21T19:16:33.939Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Java Logo" src="https://cdn-images-1.medium.com/max/700/0*kUNnVqMlforVyV8Z.png" /></figure><p>When you override equals() in Java to compare objects logically (by data, not memory address), <strong>you must also override </strong><strong>hashCode()</strong>. Failing to do so can cause subtle bugs especially when storing your objects in hash-based collections like HashMap or HashSet.</p><p>You might have heard:</p><blockquote>“If you override equals(), you must override hashCode().”</blockquote><p>But what exactly does that mean?<br>Is it <strong>mandatory</strong>? Why? And when?</p><h3>A Quick Recap: equals() vs hashCode()</h3><p>Every object in Java inherits two fundamental methods from the Object class:</p><pre>public boolean equals(Object obj);<br>public int hashCode();</pre><ul><li>equals(): Defines logical equality, do two objects represent the same data?</li><li>hashCode(): Returns an integer used in hashing structures to quickly find objects.</li></ul><h3>The Contract Between equals() and hashCode()</h3><p>Java defines a <strong>contract</strong>:</p><blockquote><em>If two objects are equal according to </em><em>equals(), they </em><strong><em>must</em></strong><em> return the same </em><em>hashCode().</em></blockquote><p>The reverse isn’t required: two objects can have the same hashCode() and still not be equal.</p><p>Why does this matter? Because <strong>Java’s hashing collections</strong> rely on this contract to store and retrieve objects correctly.</p><h3>What Goes Wrong if You Break the Contract</h3><p>Overriding equals() without hashCode()</p><pre>public class Person {<br>    private String name;<br>    private int age;<br><br>    public Person(String name, int age) { this.name = name; this.age = age; }<br><br>    @Override<br>    public boolean equals(Object obj) {<br>        if (this == obj) return true;<br>        if (obj == null || getClass() != obj.getClass()) return false;<br>        Person p = (Person) obj;<br>        return age == p.age &amp;&amp; name.equals(p.name);<br>    }<br>}</pre><p>Now use it in a HashSet:</p><pre>Set&lt;Person&gt; people = new HashSet&lt;&gt;();<br>people.add(new Person(&quot;Alice&quot;, 30));<br>people.add(new Person(&quot;Alice&quot;, 30));<br><br>System.out.println(people.size()); // ❌ Outputs 2</pre><p>Although equals() says the objects are the same, HashSet puts them in <strong>different buckets</strong> because hashCode() isn&#39;t overridden, so the default (based on memory address) is used.Correct Version: hashCode() overridden consistently.</p><h3>Proper Implementation with Consistent hashCode()</h3><pre>import java.util.Objects;<br><br>public class Person {<br>    private String name;<br>    private int age;<br><br>    public Person(String name, int age) { this.name = name; this.age = age; }<br><br>    @Override<br>    public boolean equals(Object obj) {<br>        if (this == obj) return true;<br>        if (obj == null || getClass() != obj.getClass()) return false;<br>        Person p = (Person) obj;<br>        return age == p.age &amp;&amp; name.equals(p.name);<br>    }<br><br>    @Override<br>    public int hashCode() {<br>        return Objects.hash(name, age);<br>    }<br>}</pre><p>Now:</p><pre>Set&lt;Person&gt; people = new HashSet&lt;&gt;();<br>people.add(new Person(&quot;Alice&quot;, 30));<br>people.add(new Person(&quot;Alice&quot;, 30));<br><br>System.out.println(people.size()); // ✅ Outputs 1</pre><h3>How Hash-Based Collections Use Them</h3><ul><li><strong>HashSet</strong>: Uses hashCode() to find a bucket, then equals() to check for duplicates.</li><li><strong>HashMap</strong>: Uses hashCode() on the key to find the bucket, then equals() to find the exact match.</li></ul><p>If hashCode() isn’t consistent with equals(), the bucket lookup <strong>fails</strong>, and equals() never even runs.</p><h3>When You Must Override hashCode()</h3><p>If your object will be used in:</p><ul><li>HashSet, HashMap, Hashtable, LinkedHashMap</li><li>ConcurrentHashMap, WeakHashMap</li><li>Frameworks like <strong>Hibernate</strong>, <strong>Spring</strong>, <strong>Jackson</strong>, <strong>Gson.</strong></li><li>Any custom hash-based data structure.</li></ul><p>Then you must override hashCode() alongside equals().</p><h3>When You Might Skip It</h3><p>You can skip overriding hashCode() <em>only if</em>:</p><ul><li>You don’t override equals() (default reference equality is fine)</li><li>You never use the object in a hash-based collection.</li><li>You only use collections like ArrayList, LinkedList, TreeSet (which rely on compareTo or equals() only)</li></ul><blockquote>Even then, it’s safer to override both to avoid future bugs during refactoring.</blockquote><h3>Best Practices</h3><ul><li><strong>Always override </strong><strong>hashCode() when you override </strong><strong>equals()</strong></li><li>Use Objects.hash(...) for clean, safe implementations</li><li>Ensure both methods use the <em>same fields</em> for consistency</li></ul><blockquote><em>Overriding </em><em>equals() without </em><em>hashCode() is like writing the rules for comparison but forgetting how to find what you’re comparing. The compiler won’t warn you, but your collections will misbehave silently.</em></blockquote><p>Stick to the contract, and your Java code will remain predictable, correct, and bug-free.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=221922fa7e46" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Constructor vs Static Factory vs Builder Pattern: When and What to Use in Java]]></title>
            <link>https://medium.com/@kariapratham/constructor-vs-static-factory-vs-builder-pattern-when-and-what-to-use-in-java-5f1ec79d3cc5?source=rss-962bc4bfa4fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f1ec79d3cc5</guid>
            <category><![CDATA[builder-pattern]]></category>
            <category><![CDATA[static-factory-method]]></category>
            <category><![CDATA[java-object]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[constructor]]></category>
            <dc:creator><![CDATA[Pratham Karia]]></dc:creator>
            <pubDate>Thu, 19 Jun 2025 21:57:28 GMT</pubDate>
            <atom:updated>2025-06-19T21:57:28.384Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Java Logo" src="https://cdn-images-1.medium.com/max/1024/0*lvh0UkVkK7_YuOV9.png" /></figure><p>Java offers multiple ways to create objects, each with its own strengths and trade-offs. Whether you’re building a simple data holder or a complex immutable object, understanding when to use <strong>constructors</strong>, <strong>static factory methods</strong>, or the <strong>builder pattern</strong> is essential for writing clean, maintainable, and extensible code.</p><h3>1. The Role of Constructors: Simplicity First</h3><p>At its core, a constructor is the simplest and most direct way to create an object in Java. It binds the act of instantiation directly to the structure of the class, with required parameters clearly defined. For instance, when you write:</p><pre>public class User {<br>    private String name;<br>    private int age;<br><br>    public User(String name, int age) {<br>        this.name = name;<br>        this.age = age;<br>    }<br>}</pre><p>you are telling consumers of the User class that a name and an age are mandatory. This kind of clarity is valuable when the object is simple, when all required data is known at the time of creation, and when there’s no ambiguity about what the object should contain. Constructors make such relationships explicit.</p><p>However, constructors start to feel clumsy when you deal with more than three or four parameters, especially when many of them are optional. At that point, the constructor signature loses meaning, becomes harder to read, and any attempt to overload constructors can quickly lead to confusion or repetitive code.</p><h3>2. Static Factory Methods: Clarity Through Naming</h3><p>Static factory methods step in when you want more control over how objects are created and when you want to communicate more through method names. Instead of calling new and supplying arguments in a strict order, you can define a static method that wraps the constructor, adds context, or even changes the behavior. Take this modified User class:</p><pre>public class User {<br>    private String name;<br>    private int age;<br><br>    private User(String name, int age) {<br>        this.name = name;<br>        this.age = age;<br>    }<br><br>    public static User of(String name, int age) {<br>        return new User(name, age);<br>    }<br><br>    public static User guest() {<br>        return new User(&quot;Guest&quot;, 0);<br>    }<br>}</pre><p>Now, instead of writing new User(&quot;Alice&quot;, 30), you write User.of(&quot;Alice&quot;, 30), which is equally descriptive. But the real power comes when you can return pre-defined or cached instances like User.guest(), making your API more expressive. This isn’t possible with constructors alone.</p><p>Static factory methods also enable returning objects that are subclasses of the return type or implementing an interface. This is widely used in the Java standard library methods like List.of(...) or Set.of(...) return immutable versions of those collections, not just concrete implementations.</p><p>However, because they look like ordinary static methods, they don’t clearly signal to the reader that they return a new object.</p><h4>The Limitation of Static Factory Methods with Subclassing:</h4><p>In Java, static methods are not inherited like instance methods. This means a static factory method defined in a superclass won’t automatically work correctly when used with subclasses, and trying to cast the result can lead to runtime errors.</p><p>Here’s a concrete example:</p><pre>public class User {<br>    protected String name;<br><br>    protected User(String name) {<br>        this.name = name;<br>    }<br><br>    public static User create(String name) {<br>        return new User(name);<br>    }<br><br>    public void print() {<br>        System.out.println(&quot;User: &quot; + name);<br>    }<br>}<br><br>public class AdminUser extends User {<br>    public AdminUser(String name) {<br>        super(name);<br>    }<br><br>    public static AdminUser create(String name) {<br>        return new AdminUser(name);<br>    }<br><br>    @Override<br>    public void print() {<br>        System.out.println(&quot;Admin: &quot; + name);<br>    }<br>}</pre><p>Now, here’s what happens when you mistakenly call the superclass factory and try to cast:</p><pre>public class Test {<br>    public static void main(String[] args) {<br>        AdminUser admin = (AdminUser) User.create(&quot;Pratham&quot;); // ❌ Throws ClassCastException<br>        admin.print();<br>    }<br>}</pre><p>Even though AdminUser extends User, the User.create(&quot;Pratham&quot;) method returns a User object — not an AdminUser. Since static methods are resolved at compile time and don&#39;t participate in polymorphism, Java doesn’t &quot;redirect&quot; the call to the subclass’s create() method.</p><p>To safely create an AdminUser, you must explicitly call:</p><pre>AdminUser admin = AdminUser.create(&quot;Pratham&quot;);<br>admin.print();  // ✅ Admin: Pratham</pre><p>This example shows why static factory methods must be redefined in each subclass if needed, unlike constructors which are naturally extensible using super(...).</p><p>This approach <strong>kills the DRY (Don’t Repeat Yourself) principle</strong> because each subclass must redefine its own static factory method even if the logic is identical to the super class. Unlike constructors, which can be reused via super(...), static methods are not inherited or overrideable. This means every subclass must duplicate the factory method just to return the correct type, leading to redundant and boilerplate-heavy code.</p><h3>3. The Builder Pattern: Managing Complexity Gracefully</h3><p>The builder pattern enters the picture when object creation becomes too complex for constructors or static factories. This is especially true when you have multiple optional fields, want to avoid telescoping constructors, or need to ensure immutability after construction.</p><p>Imagine a User class with four or more fields, only two of which are mandatory. Rather than writing multiple overloaded constructors, or adding many static factory variants, you encapsulate the creation process inside a builder:</p><pre>public class User {<br>    private final String name;<br>    private final int age;<br>    private final String email;<br>    private final String address;<br><br>    private User(Builder builder) {<br>        this.name = builder.name;<br>        this.age = builder.age;<br>        this.email = builder.email;<br>        this.address = builder.address;<br>    }<br><br>    public static class Builder {<br>        private final String name;<br>        private final int age;<br>        private String email;<br>        private String address;<br><br>        public Builder(String name, int age) {<br>            this.name = name;<br>            this.age = age;<br>        }<br><br>        public Builder email(String email) {<br>            this.email = email;<br>            return this;<br>        }<br><br>        public Builder address(String address) {<br>            this.address = address;<br>            return this;<br>        }<br><br>        public User build() {<br>            return new User(this);<br>        }<br>    }<br>}</pre><p>With this structure in place, you can create a new user in a fluent, readable way:</p><pre>User user = new User.Builder(&quot;Alice&quot;, 28)<br>                .email(&quot;alice@example.com&quot;)<br>                .address(&quot;New York&quot;)<br>                .build();</pre><p>The builder pattern offers the clarity of named parameters (which Java lacks), and ensures that once the object is created, it cannot be changed, a key principle when designing immutable classes.</p><p>Builders are slightly more verbose and require more boilerplate than constructors or factory methods. But when you are building APIs or SDKs meant to scale or be consumed by other developers, builders often offer the cleanest and most self-documenting experience.</p><h3>So, What Should You Choose?</h3><p>When deciding between constructors, static factory methods, and the builder pattern, your goal should be to favor readability, maintainability, and correctness. For objects that are simple, always require the same data, and are unlikely to evolve in terms of parameters, a constructor is perfectly fine. When you want more expressive creation logic, or want to hide how an object is instantiated, static factory methods offer more flexibility. And when you have optional parameters, want immutability, or are designing fluent APIs, the builder pattern is the best fit.</p><p>None of these is universally better than the others. Instead, they each shine in different situations. Knowing which one to pick and when is what separates readable code from rigid code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f1ec79d3cc5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>