<?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 Kandaanusha on Medium]]></title>
        <description><![CDATA[Stories by Kandaanusha on Medium]]></description>
        <link>https://medium.com/@kandaanusha?source=rss-766c27233dc7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*8I5xksIxvc1Adpkx</url>
            <title>Stories by Kandaanusha on Medium</title>
            <link>https://medium.com/@kandaanusha?source=rss-766c27233dc7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 01:13:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kandaanusha/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[HTTP persistent connection]]></title>
            <link>https://medium.com/@kandaanusha/http-persistent-connection-944c1effa7e6?source=rss-766c27233dc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/944c1effa7e6</guid>
            <category><![CDATA[https]]></category>
            <category><![CDATA[keep-alive]]></category>
            <category><![CDATA[persistent-connections]]></category>
            <dc:creator><![CDATA[Kandaanusha]]></dc:creator>
            <pubDate>Wed, 23 Sep 2026 17:33:08 GMT</pubDate>
            <atom:updated>2026-09-23T17:33:08.038Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>HTTP Keep-Alive</strong> (also known as <strong>HTTP persistent connection</strong>) is a instruction that allows a single TCP connection to remain open for multiple HTTP requests and responses.</p><h4>The Core Problem It Solves</h4><p>By default, early web protocols (like HTTP/0.9 and HTTP/1.0) closed the underlying network connection after every single request-response cycle.</p><p>Modern web pages are complex and often require dozens or hundreds of individual files to load completely (such as HTML, CSS stylesheets, JavaScript files, images, and fonts). Without Keep-Alive, a browser would have to open and close a brand-new TCP connection for <em>every single asset</em>, introducing massive network overhead.</p><h4>How Keep-Alive Enhances Performance</h4><ul><li><strong>Reduced Latency:</strong> It completely skips the repeated overhead of the <strong>TCP 3-way handshake</strong> and <strong>SSL/TLS cryptographic handshakes</strong> for every subsequent file.</li><li><strong>Lower CPU and Memory Load:</strong> The web server handles fewer connection setups and tear-downs, significantly conserving system resources.</li><li><strong>Faster Page Load Speed:</strong> Files are transferred sequentially (or pipelined) over a warm, open connection, which noticeably decreases the overall time to interact with a page.</li></ul><h4>How It Works Across HTTP Versions</h4><ul><li><strong>HTTP/1.0: Disabled by default.</strong> The client must explicitly ask to keep the connection open by attaching the Connection: keep-alive header.</li><li><strong>HTTP/1.1: Enabled by default.</strong> All connections are persistent unless a header explicitly states Connection: close.<strong>Connection Handling is </strong>Persistent but sequential (one request finishes before the next begins).<strong>Packet Loss Impact is </strong>High (stalls the queue)</li><li><strong>HTTP/2 &amp; HTTP/3 : Prohibited/Obsolete.</strong> These newer protocols natively handle persistence and multiplexing. Connection-specific headers like Connection and Keep-Alive are completely ignored or rejected.<strong>Connection Handling is </strong>Persistent and <strong>multiplexed</strong> (all requests sent simultaneously).<strong>Packet Loss Impact is </strong>High (stalls the entire TCP Connection) for HTTP/2. <strong>Packet Loss Impact is </strong>Low (stalls the only affected streams) for HTTP/3.</li></ul><h4>The Keep-Alive Header Parameters</h4><p>When using HTTP/1.x, you can configure the behavior of a persistent connection using specific parameters inside the Keep-Alive response header: [<a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Keep-Alive">1</a>]</p><ul><li><strong>timeout</strong>: An integer indicating the time (in seconds) that the host will let an idle connection sit open before closing it. For example, timeout=5 means the connection shuts down if nothing is sent for 5 seconds. [<a href="https://en.wikipedia.org/wiki/HTTP_persistent_connection">1</a>, <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Keep-Alive">2</a>]</li><li><strong>max</strong>: The maximum number of individual requests that can be sent over this single connection before forcing it to close. [<a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Keep-Alive">1</a>]</li></ul><p><em>Example HTTP/1.1 Header:</em></p><p>http</p><pre>Connection: keep-alive<br>Keep-Alive: timeout=5, max=100</pre><h3><strong>HTTP/2 and HTTP/3</strong></h3><p>In <strong>HTTP/2 and HTTP/3</strong>, the concept of Keep-Alive is obsolete because connection persistence is baked directly into the core design of the protocols. Instead of handling requests one after another over an open connection, they use Multiplexing.</p><p>Here is how each version handles connection persistence and concurrency:</p><h4>HTTP/2: TCP Multiplexing</h4><p>HTTP/2 uses a single TCP connection between the browser and the server, but it introduces a binary framing layer that breaks communication down into tiny, independent pieces called <strong>frames</strong>.</p><ul><li><strong>Single Connection:</strong> A single TCP connection is opened at the start and stays open for the entire session.</li><li><strong>Streams:</strong> Inside that single connection, multiple bidirectional data flows (called streams) run concurrently.</li><li><strong>No Interleaving Blocks:</strong> The browser can request HTML, CSS, JS, and images <strong>all at the exact same time</strong> over the same connection. The frames are mixed together on the wire and reassembled on the other side. This completely eliminates <strong>Head-of-Line (HoL) blocking</strong> at the application layer.</li></ul><h4>HTTP/3: QUIC Multiplexing</h4><p>While HTTP/2 fixed application-layer blocking, it suffered if a network packet was dropped. Because HTTP/2 still relies on TCP, a single lost packet forces the entire connection to pause until that packet is resent (Transport-layer HoL blocking).</p><p>HTTP/3 solves this by ditching TCP entirely and moving to <strong>QUIC</strong> (which runs on top of UDP).</p><ul><li><strong>Independent Streams:</strong> Like HTTP/2, it uses a single persistent connection with multiple streams. However, in HTTP/3, <strong>each stream is entirely independent</strong>.</li><li><strong>Zero HoL Blocking:</strong> If a packet carrying data for an image is dropped, only that specific stream pauses. The CSS, JS, and HTML streams continue downloading without a millisecond of delay.</li><li><strong>Connection Migration:</strong> Because QUIC uses unique “Connection IDs” rather than IP addresses, you can switch from Wi-Fi to cellular data without dropping the connection or needing a new handshake.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=944c1effa7e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cron Job Duplication : Causes & Solutions]]></title>
            <link>https://medium.com/@kandaanusha/cron-job-duplication-causes-solutions-9a180d5dfaaf?source=rss-766c27233dc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a180d5dfaaf</guid>
            <category><![CDATA[cronjob]]></category>
            <category><![CDATA[scheduling]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Kandaanusha]]></dc:creator>
            <pubDate>Tue, 04 Aug 2026 13:00:12 GMT</pubDate>
            <atom:updated>2026-08-04T13:00:12.236Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>You have 3 servers.Each runs the same midnight cron job. Now every email is sent 3 times.Explain why did it occur and all possible solutions with pros and crons</strong></blockquote><p>This is a classic distributed systems trap: <strong>you scaled your application infrastructure, but your scheduled tasks weren’t aware of the scale.</strong></p><p>When you had one server, a single cron job made sense. But once you duplicated the server across three instances, each instance inherited the exact same crontab schedule. At midnight, all three servers independently trigger the job, hit the database, query the pending emails, and send them out — resulting in every recipient getting three copies.</p><p>Here is a detailed look at why this happens and the best ways to fix it, ranked from simplest quick fixes to production-grade solutions.</p><h3>Why It Occurred</h3><ol><li><strong>Independent Execution:</strong> standard cron (crontab) is localized to the operating system instance. Server A doesn&#39;t know Server B or C exist, so there is no built-in coordination.</li><li><strong>Race Condition / Idempotency Lack:</strong> If the cron job simply queries SELECT * FROM emails WHERE status = &#39;pending&#39;, all three servers run this query simultaneously before any single server has time to mark the emails as sent.</li></ol><h3>Solutions, Pros, and Cons</h3><h3>1. Dedicated Cron Server (Static Partitioning)</h3><p><strong>How it works:</strong> Remove the cron job from Server B and Server C. Leave the midnight cron running <strong>only on Server A</strong>.</p><p><strong>Pros:</strong></p><ul><li><strong>Simplest fix:</strong> Takes under 2 minutes to set up.</li><li>No code changes or extra dependencies required.</li></ul><p><strong>Cons:</strong></p><ul><li><strong>Single Point of Failure (SPOF):</strong> If Server A crashes or goes down for maintenance at 11:59 PM, no emails are sent at all.</li><li><strong>Configuration Drift:</strong> Makes Server A “special,” breaking infrastructure-as-code or immutable deployment patterns.</li></ul><blockquote><strong><em>Best For</em></strong><em>: Emergency quick-fix on a tight deadline.</em></blockquote><h3>2. Distributed Locking (e.g., Redis / Database Lock)</h3><p><strong>How it works:</strong> Before running the email script, the cron task attempts to acquire a named lock (e.g., email_cron_lock) in a shared store like Redis or your database. Whichever server gets the lock runs the job; the other two fail to acquire the lock and exit gracefully.</p><p><strong>Pros:</strong></p><ul><li>Prevents duplicate execution reliably across multiple instances.</li><li>Maintains high availability — if Server A is down, Server B or C will acquire the lock instead.</li><li>Minimal code changes required using existing libraries (e.g., Redlock for Redis, GET_LOCK() in MySQL, or pg_advisory_lock in PostgreSQL).</li></ul><p><strong>Cons:</strong></p><ul><li>Introduces a dependency on a shared state (Redis/DB).</li><li>If the lock expiration isn’t handled correctly (e.g., job dies mid-execution without releasing or times out too early), jobs could be locked out or run twice.</li></ul><blockquote><strong><em>Best For</em></strong><em>: </em>Small-to-medium apps with existing Redis/DB.<em>.</em></blockquote><h3>3. Decouple Scheduling from Execution (Queue Worker Model)</h3><p><strong>How it works:</strong> Instead of the cron job doing the actual work of sending emails, a single lightweight scheduler (or external tool) pushes email tasks/events into a shared message queue (like RabbitMQ, AWS SQS, or Redis Bull/Sidekiq). The three servers act as workers that pull jobs off the queue.</p><p><strong>Pros:</strong></p><ul><li><strong>Highly Scalable &amp; Fault Tolerant:</strong> If you have 10,000 emails, all 3 servers work together in parallel to clear the queue 3x faster without duplication.</li><li>Built-in retry mechanisms, dead-letter queues, and execution tracking.</li><li>Industry standard for background processing in modern web architectures.</li></ul><p><strong>Cons:</strong></p><ul><li>Requires architectural refactoring (adding a message broker and worker architecture).</li><li>Higher initial complexity to set up and monitor.</li></ul><blockquote><strong><em>Best For</em></strong><em>: </em>Scalable, high-volume transactional emails.</blockquote><h3>4. External Orchestration / Cloud Scheduler</h3><p><strong>How it works:</strong> Offload scheduling to a centralized external system (e.g., AWS EventBridge, Google Cloud Scheduler, Temporal, or a Kubernetes CronJob) that triggers a single web endpoint (POST /api/jobs/send-emails) or runs a container once.</p><p><strong>Pros:</strong></p><ul><li>Removes scheduling logic entirely from application servers.</li><li>Detailed logging, monitoring, and alerting built out of the box.</li><li>Easy to manage via infrastructure tools (Terraform, CloudFormation).</li></ul><p><strong>Cons:</strong></p><ul><li>Webhooks must be secured (authentication/tokens) to prevent unauthorized execution.</li><li>Introduces dependency on cloud vendor infrastructure.</li></ul><blockquote><strong><em>Best For</em></strong><em>: </em>Modern cloud-native or containerized stacks.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a180d5dfaaf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular Change Detection Stragegy]]></title>
            <link>https://medium.com/@kandaanusha/angular-change-detection-stragegy-e9d21896b189?source=rss-766c27233dc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9d21896b189</guid>
            <dc:creator><![CDATA[Kandaanusha]]></dc:creator>
            <pubDate>Thu, 16 Jul 2026 16:59:50 GMT</pubDate>
            <atom:updated>2026-07-16T16:59:50.553Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s look at why we even need change detection in the first place, and exactly what it does using a simple game.</p><h3>The Problem: Why do we need it?</h3><p>In normal web development, if you change a variable in your code, the screen doesn’t automatically know.</p><p>If you have: let name = &quot;Alice&quot; on your screen, and you change it to name = &quot;Bob&quot; in your code, the screen will still say &quot;Alice&quot; until you <em>force</em> it to update.</p><p>Angular’s <strong>Change Detection</strong> is the automatic system that updates the screen for you.</p><h3>The “Spot the Difference” Analogy</h3><p>Think of Angular as a game of <strong>“Spot the Difference.”</strong></p><p>Angular keeps two mental pictures of your app:</p><ol><li><strong>Picture A:</strong> What the screen looked like <em>before</em> (e.g., name = &quot;Alice&quot;).</li><li><strong>Picture B:</strong> What your data looks like <em>right now</em> (e.g., name = &quot;Bob&quot;).</li></ol><p>Whenever you do anything on the website — like click a button, type in an input box, or load data from the internet — Angular immediately plays “Spot the Difference.”</p><ol><li>It starts at the very top of your page and walks down to the bottom.</li><li>It compares <strong>Picture A</strong> with <strong>Picture B</strong>.</li><li>It spots the difference: <em>“Ah! The name changed from Alice to Bob!”</em></li><li>It instantly updates only that specific spot on the screen to say “Bob”.</li></ol><p>That is all Change Detection is: <strong>constantly comparing the old data to the new data, finding the differences, and updating the screen so they match.</strong></p><p>Now that we know Angular is playing a giant game of <strong>“Spot the Difference”</strong>, let’s look at the next big question:</p><p><strong>How does Angular know <em>when</em> to start playing the game, and how does it do it so fast without slowing down your computer?</strong></p><p>Let’s look at the two main secrets behind this.</p><h3>Secret 1: The “Doorbell” (How Angular knows when to check)</h3><p>Angular doesn’t run the “Spot the Difference” game every single microsecond — that would melt your computer’s processor. Instead, it sits quietly and waits for a “doorbell” to ring.</p><p>In Angular, the doorbell rings whenever three things happen:</p><ol><li><strong>User Interaction:</strong> You click a button, type a key, or scroll.</li><li><strong>Waiting is Over:</strong> A timer finishes (like a setTimeout in code).</li><li><strong>Data Arrives:</strong> Information finally loads from a server/database.</li></ol><p>The moment any of these three things happen, the doorbell rings, and Angular says: <em>“Aha! Something changed. Time to run the game!”</em></p><h3>Secret 2: The “Waterfall” (How Angular checks the page)</h3><p>An Angular website is built like a family tree. You have a main parent box (the whole page), which has child boxes (like a Sidebar and a Main Content area), which have their own child boxes (like individual buttons or images).</p><p>When the doorbell rings, Angular always plays the game like a <strong>waterfall</strong> — it starts at the very top (the Parent) and flows straight down to the bottom (the youngest Child).</p><p>It never goes sideways, and it never goes up. This one-way street makes it incredibly fast.</p><h3>The Master Shortcut: “Do Not Disturb” (OnPush)</h3><p>Now, imagine your website is huge — like Facebook or Amazon. If you click a “Like” button on <em>one</em> tiny post, does Angular really need to check the entire website, the sidebar, the chat window, and the navigation bar?</p><p>By default, <strong>yes</strong>, it does.</p><p>To prevent this lag, Angular has a secret setting called <strong>OnPush</strong>. It’s like putting a &quot;Do Not Disturb&quot; sign on certain parts of your family tree.</p><ul><li><strong>Without OnPush (Default):</strong> Angular knocks on every single door in the house to check for differences.</li><li><strong>With OnPush:</strong> Angular skips entire rooms unless you specifically hand a new piece of data directly to that room.</li></ul><blockquote><strong><em>In short:</em></strong><em> </em><em>OnPush tells Angular, </em>&quot;Hey, don&#39;t waste your time checking me or my children unless I get brand-new information!&quot;<em> This is how professional developers keep massive Angular apps running lightning-fast.</em></blockquote><h3>1. The OnPush Strategy (The &quot;Do Not Disturb&quot; Mode)</h3><p>By default, when Zone.js notices <em>any</em> event, it walks down your entire component tree to run change detection.</p><p>When you use OnPush, you tell Angular: <em>&quot;Only check this component if its inputs actually change, or if an event is fired inside it.&quot;</em></p><h3>How to write OnPush in Code:</h3><pre>import { Component, Input, ChangeDetectionStrategy } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-user-profile&#39;,<br>  template: `<br>    &lt;div&gt;<br>      &lt;h3&gt;User: {{ user.name }}&lt;/h3&gt;<br>    &lt;/div&gt;<br>  `,<br>  // This line turns on the &quot;Do Not Disturb&quot; mode!<br>  changeDetection: ChangeDetectionStrategy.OnPush <br>})<br>export class UserProfileComponent {<br>  @Input() user!: { name: string };<br>}</pre><h3>The Catch (Object References)</h3><p>Because of how JavaScript works, OnPush only triggers if the <strong>memory reference</strong> of the input changes.</p><ul><li><strong>This WILL NOT trigger OnPush:</strong></li></ul><pre>// You just changed a property inside the object.  <br>// The box is the same, you just changed what&#39;s inside. Angular won&#39;t notice! <br>this.currentUser.name = &#39;Bob&#39;;</pre><ul><li><strong>This WILL trigger OnPush:</strong></li></ul><pre>// You created a brand new object.  <br>// It&#39;s a completely new box. Angular spots the difference and updates!<br> this.currentUser = { name: &#39;Bob&#39; };</pre><h3>2. Angular Signals (The Modern “Sniper” Mode)</h3><p>While OnPush is a great optimization, it still requires Angular to walk down from the parent components to check things.</p><p><strong>Signals</strong> completely change this. Instead of a “top-down walkthrough,” Signals work like a direct wire.</p><p>A Signal is a special wrapper around a value. When that value changes, it doesn’t need Zone.js to ring a doorbell, and it doesn’t need to walk the component tree. It knows exactly which HTML tag is using it, and <strong>updates only that exact spot on the screen instantly.</strong></p><h3>How to write Signals in Code:</h3><pre>import { Component, signal } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-counter&#39;,<br>  template: `<br>    &lt;!-- We read the signal like a function: count() --&gt;<br>    &lt;p&gt;Current Count: {{ count() }}&lt;/p&gt; <br>    &lt;button (click)=&quot;increment()&quot;&gt;Add +1&lt;/button&gt;<br>  `<br>})<br>export class CounterComponent {<br>  // 1. Define a signal with a starting value of 0<br>  count = signal(0);<br>  increment() {<br>    // 2. Update the signal&#39;s value<br>    this.count.set(this.count() + 1); <br>  }<br>}</pre><h3>Why this is a massive deal:</h3><ul><li><strong>No Zone.js overhead:</strong> It enables a “Zoneless” future where your app uses significantly less memory and runs faster.</li><li><strong>Fine-grained updates:</strong> If you have 50 components on your page and a signal in component #50 updates, Angular updates <em>only</em> that exact template binding. The rest of the page remains entirely untouched and un-evaluated.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9d21896b189" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Troubleshooting the Angular + Java CORS Boss Fight: A Developer’s Guide]]></title>
            <link>https://medium.com/@kandaanusha/troubleshooting-the-angular-java-cors-boss-fight-a-developers-guide-41449e7da2fb?source=rss-766c27233dc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/41449e7da2fb</guid>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Kandaanusha]]></dc:creator>
            <pubDate>Thu, 16 Jul 2026 13:00:09 GMT</pubDate>
            <atom:updated>2026-07-16T13:00:09.974Z</atom:updated>
            <content:encoded><![CDATA[<p>Every web developer, at some point in their journey, runs into the dreaded browser wall:</p><p>Access to XMLHttpRequest at &#39;http://localhost:8080/api/users&#39; from origin &#39;http://localhost:4200&#39; has been blocked by CORS policy.</p><p>It is a rite of passage. You have a shiny Angular frontend running on port 4200 and a robust Java backend (likely Spring Boot) running on port 8080. They are both on your machine, yet the browser treats them like hostile foreign entities.</p><p>Let’s dissect exactly why this happens and explore the concrete ways to fix it on both the Angular frontend and the Java backend.</p><h3>The Anatomy of the Problem: Why the Browser Blocks You</h3><p>Before writing code, we need to understand the <strong>Same-Origin Policy (SOP)</strong>. The browser enforces this security mechanism to prevent malicious websites from reading data from another site without permission.</p><p>An <strong>Origin</strong> is defined by three things: <strong>Protocol, Domain, and Port</strong>.</p><ul><li>http://localhost:4200 (Angular)</li><li>http://localhost:8080 (Java API)</li></ul><p>Because the ports (4200 vs 8080) do not match, they are considered entirely different origins. When Angular requests data, the browser sends the request but intercepts the response. If the Java backend doesn&#39;t explicitly return the correct headers saying <em>&quot;Hey, I trust port 4200!&quot;</em>, the browser throws a CORS error and hides the data from your Javascript code.</p><h3>Strategy 1: The Frontend Illusion (Angular Dev Proxy)</h3><p>The cleanest way to handle this during local development is to trick the browser into thinking the frontend and backend share the exact same origin. We do this using Angular’s built-in development proxy.</p><h3>Step 1: Create proxy.conf.json</h3><p>In the root directory of your Angular project (right next to package.json), create a file named proxy.conf.json:</p><pre>{<br>  &quot;/api&quot;: {<br>    &quot;target&quot;: &quot;http://localhost:8080&quot;,<br>    &quot;secure&quot;: false,<br>    &quot;changeOrigin&quot;: true,<br>    &quot;logLevel&quot;: &quot;debug&quot;<br>  }<br>}</pre><h3>Step 2: Register it in angular.json</h3><p>Find your project’s architect -&gt; serve configuration block and point it to your new proxy file</p><pre>&quot;architect&quot;: {<br>  &quot;serve&quot;: {<br>    &quot;options&quot;: {<br>      &quot;proxyConfig&quot;: &quot;proxy.conf.json&quot;<br>    }<br>  }<br>}</pre><h3>Step 3: Use Relative Paths</h3><p>In your Angular services, stop hardcoding http://localhost:8080. Instead, use a relative path:</p><pre>// Angular Service<br>this.http.get(&#39;/api/users&#39;).subscribe(...);</pre><p>When you run ng serve, Angular intercepts any request starting with /api and forwards it behind the scenes to your Java backend on port 8080. The browser only ever sees requests going to port 4200, eliminating CORS altogether.</p><h3>Strategy 2: The Backend Authorization (Java / Spring Boot)</h3><p>If your app is deployed across different cloud domains in production, or if you prefer to solve this on the backend, Java gives you three primary entry points to grant origin permissions.</p><h3>Option A: The Quick Fix (@CrossOrigin)</h3><p>If you only have a few controllers causing issues, annotate them directly.</p><pre>@RestController<br>@RequestMapping(&quot;/api/users&quot;)<br>@CrossOrigin(origins = &quot;http://localhost:4200&quot;)<br>public class UserController {<br>    <br>    @GetMapping<br>    public ResponseEntity&lt;List&lt;User&gt;&gt; getAllUsers() {<br>        return ResponseEntity.ok(userService.getAll());<br>    }<br>}</pre><h3>Option B: The Global MVC Configurer (Recommended)</h3><p>For global configuration without cluttering your code with annotations, define a dedicated WebMvcConfigurer bean.</p><pre>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br>import org.springframework.web.servlet.config.annotation.CorsRegistry;<br>import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;<br><br>@Configuration<br>public class WebCorsConfig {<br>    @Bean<br>    public WebMvcConfigurer corsConfigurer() {<br>        return new WebMvcConfigurer() {<br>            @Override<br>            public void addCorsMappings(CorsRegistry registry) {<br>                registry.addMapping(&quot;/**&quot;) // Match all endpoints<br>                        .allowedOrigins(&quot;http://localhost:4200&quot;, &quot;https://production-frontend.com&quot;)<br>                        .allowedMethods(&quot;GET&quot;, &quot;POST&quot;, &quot;PUT&quot;, &quot;DELETE&quot;, &quot;OPTIONS&quot;)<br>                        .allowedHeaders(&quot;*&quot;)<br>                        .allowCredentials(true);<br>            }<br>        };<br>    }<br>}</pre><h3>Strategy 3: The Spring Security Trap</h3><p>If your Java backend includes <strong>Spring Security</strong>, Options A and B will fail silently.</p><p>Spring Security acts as a filter chain that sits <em>in front</em> of your MVC Controllers. When an Angular application makes a request with custom headers (like an Authorization Bearer token), the browser sends a hidden preliminary request called an <strong>OPTIONS preflight</strong>.</p><p>Spring Security catches this unauthenticated OPTIONS request, flags it as unauthorized, and blocks it before it ever reaches your MVC CORS configuration.</p><p>To bypass this, you must explicitly pass the CORS configurations directly into the SecurityFilterChain:</p><pre>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br>import org.springframework.security.config.annotation.web.builders.HttpSecurity;<br>import org.springframework.security.web.SecurityFilterChain;<br>import org.springframework.web.cors.CorsConfiguration;<br>import java.util.List;<br><br>@Configuration<br>public class SecurityConfig {<br>    @Bean<br>    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {<br>        http<br>            .cors(cors -&gt; cors.configurationSource(request -&gt; {<br>                CorsConfiguration config = new CorsConfiguration();<br>                config.setAllowedOrigins(List.of(&quot;http://localhost:4200&quot;));<br>                config.setAllowedMethods(List.of(&quot;GET&quot;, &quot;POST&quot;, &quot;PUT&quot;, &quot;DELETE&quot;, &quot;OPTIONS&quot;));<br>                config.setAllowedHeaders(List.of(&quot;*&quot;));<br>                config.setAllowCredentials(true);<br>                return config;<br>            }))<br>            .csrf(csrf -&gt; csrf.disable()) // Only do this for specific APIs / Dev testing<br>            .authorizeHttpRequests(auth -&gt; auth<br>                .anyRequest().authenticated()<br>            );<br>        return http.build();<br>    }<br>}</pre><h3>Verification: Knowing When You’ve Won</h3><p>To ensure your fix worked, crack open your browser’s <strong>Developer Tools (F12)</strong> and head to the <strong>Network</strong> tab. Click on your API network request and examine the <strong>Response Headers</strong>.</p><p>If successful, you will see:</p><ul><li>Access-Control-Allow-Origin: <a href="http://localhost:4200/">http://localhost:4200</a></li><li>Access-Control-Allow-Methods: GET, POST, ...</li></ul><p>If these headers are present, the browser will drop its shields, allow the network traffic to flow freely, and your Angular app will render its components smoothly.</p><h3>The Single-Domain Setup (The “No-CORS” Standard)</h3><p>In enterprise production environments, the most common practice is to completely eliminate CORS by placing both the frontend and the backend behind a <strong>Reverse Proxy</strong> or <strong>API Gateway</strong> (like Nginx, AWS CloudFront, Cloudflare, or an Application Load Balancer).Developers don’t hardcode full URLs like https://api.example.com. Instead, they use relative paths:</p><p>In this setup, everything is served under a <strong>single domain</strong>:</p><ul><li><strong>Frontend:</strong> <a href="https://my-app.com/">https://my-app.com/</a></li><li><strong>Backend:</strong> <a href="https://my-app.com/api/...">https://my-app.com/api/...</a></li></ul><p>Because the domain, protocol, and port are identical, the browser views this as the <strong>Same-Origin</strong>. CORS is never triggered, meaning you don’t have to configure <em>any</em> CORS settings in Java!</p><h3>How it works with Nginx (Production Example):</h3><p>When a user goes to https://my-app.com, the request hits your Nginx server. Nginx acts as a traffic cop:</p><pre>server {<br>    listen 443 ssl;<br>    server_name my-app.com;<br><br># 1. Route static frontend requests to Angular files<br>    location / {<br>        root /var/www/angular-app;<br>        try_files $uri $uri/ /index.html;<br>    }<br>    # 2. Route API requests to the Java Backend running on port 8080<br>    location /api {<br>        proxy_pass http://localhost:8080; <br>        proxy_set_header Host $host;<br>        proxy_set_header X-Real-IP $remote_addr;<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41449e7da2fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Frog Jump — Part 1]]></title>
            <link>https://medium.com/@kandaanusha/frog-jump-part-1-50293ad7dfce?source=rss-766c27233dc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/50293ad7dfce</guid>
            <dc:creator><![CDATA[Kandaanusha]]></dc:creator>
            <pubDate>Sat, 27 Jun 2026 10:18:09 GMT</pubDate>
            <atom:updated>2026-06-29T16:58:18.063Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>There are n steps. Frog can jump 1 step at a time or 2 steps at a time. How many total possible ways Frog can reach nth step</strong></p><p>To find the total number of ways the frog can reach the n-th step, we can think about the problem <strong>backwards</strong> by looking at the very last decision the frog makes.</p><h3>The Logic Break Down</h3><p>To land exactly on step n, the frog only has two possible last moves:</p><ol><li><strong>From step n-1:</strong> The frog takes a <strong>1-step</strong> jump.</li><li><strong>From step n-2:</strong> The frog takes a <strong>2-step</strong> jump.</li></ol><p>Because these two scenarios are completely mutually exclusive, the total number of ways to reach step n is simply the sum of the ways to reach step n-1 and the ways to reach step n-2.</p><p>If we let F(n) represent the total ways to reach the n-th step, we get the recurrence relation:</p><p>F(n) = F(n-1) + F(n-2)</p><p>This is exactly the formula for the <a href="https://medium.com/@kandaanusha/fibonacci-algorithm-in-java-bd4fa44da493"><strong>Fibonacci sequence</strong></a>.</p><h3>Base Cases</h3><p>Let’s look at the smallest possible steps to anchor our formula:</p><ul><li><strong>Step 1 (n=1):</strong> Only <strong>1 way</strong> (a single 1-step jump).</li><li><strong>Step 2 (n=2):</strong> There are <strong>2 ways</strong> (1 step + 1 step, OR a single 2-step jump).</li></ul><p>Using our formula to go higher:</p><ul><li><strong>Step 3 (n=3):</strong> F(2) + F(1) = 2 + 1 = <strong>3 ways</strong>.</li><li><strong>Step 4 (n=4):</strong> F(3) + F(2) = 3 + 2 = <strong>5 ways</strong>.</li></ul><h3>The Final Answer</h3><p>The total number of ways the frog can reach the n-th step is given by the <strong>(n+1)-th Fibonacci number</strong>, assuming the standard Fibonacci sequence starts as F_1 = 1, F_2 = 1, F_3 = 2, F_4 = 3, F_5 = 5, and so on.</p><p>Total Ways = F{n+1}</p><h3>Recursive Programming</h3><ul><li><strong>Time Complexity:</strong> O(n²)</li><li><strong>Space Complexity:</strong> 0(n) (uses stack)</li></ul><pre>public class FrogJumpDP {<br>    public static int countWays(int n) {<br>        if (n &lt;= 0) return 0;<br>        if (n == 1) return 1;<br>         return countWays[n-1]+countWays[n-2]<br>    }<br>}</pre><h3>Dynamic Programming with Memoization (Tabulation)</h3><p>If you need to look up or store the ways to reach every single intermediate step up to n, you can use an array to explicitly store the state of each step.</p><ul><li><strong>Time Complexity:</strong> O(n)</li><li><strong>Space Complexity:</strong> O(n) — For the dp array.</li></ul><pre>public class FrogJumpDP {<br>    public static int countWays(int n) {<br>        if (n &lt;= 0) return 0;<br>        if (n == 1) return 1;<br>        <br>        int[] dp = new int[n + 1];<br>        dp[1] = 1;<br>        dp[2] = 2;<br><br>for (int i = 3; i &lt;= n; i++) {<br>            dp[i] = dp[i - 1] + dp[i - 2];<br>        }<br>        return dp[n];<br>    }<br>}</pre><h3>Optimized Iterative Approach (Recommended)</h3><p>This is the most efficient method. Instead of storing the results for all steps in an array, we only track the possibilities for the previous two steps. This keeps our space requirements minimal.</p><ul><li><strong>Time Complexity:</strong> O(n) — We loop from 3 to n exactly once.</li><li><strong>Space Complexity:</strong> O(1) — We only use a few variables to track state.</li></ul><pre>public class FrogJump {<br>    public static int countWays(int n) {<br>        // Base cases<br>        if (n &lt;= 0) return 0;<br>        if (n == 1) return 1;<br>        if (n == 2) return 2;<br><br>int prev2 = 1; // Represents W(n-2) -&gt; initially step 1<br>        int prev1 = 2; // Represents W(n-1) -&gt; initially step 2<br>        int current = 0;<br>        for (int i = 3; i &lt;= n; i++) {<br>            current = prev1 + prev2;<br>            prev2 = prev1;<br>            prev1 = current;<br>        }<br>        return current;<br>    }<br>    public static void main(String[] args) {<br>        int n = 5; <br>        System.out.println(&quot;Total ways to reach step &quot; + n + &quot;: &quot; + countWays(n));<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50293ad7dfce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fibonacci Algorithm in Java]]></title>
            <link>https://medium.com/@kandaanusha/fibonacci-algorithm-in-java-bd4fa44da493?source=rss-766c27233dc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd4fa44da493</guid>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Kandaanusha]]></dc:creator>
            <pubDate>Wed, 24 Jun 2026 17:41:21 GMT</pubDate>
            <atom:updated>2026-06-24T17:41:21.162Z</atom:updated>
            <content:encoded><![CDATA[<p><em>The </em><strong><em>Fibonacci series</em></strong><em> is a sequence of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1.</em></p><p><em>0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, …</em></p><h3>1) The Recursive Approach (Simplest code, poor performance)</h3><p>This directly mimics the mathematical definition of Fibonacci (F(n) = F(n-1) + F(n-2)). However, it is highly inefficient for large numbers because it recalculates the same values over and over.</p><pre>public class FibonacciRecursive {<br>    public static int fibonacci(int n) {<br>        if (n &lt;= 1) {<br>            return n;<br>        }<br>        return fibonacci(n - 1) + fibonacci(n - 2);<br>    }<br>    <br>public static void main(String[] args) {<br>        int n = 10;<br>        System.out.print(&quot;Fibonacci Series up to &quot; + n + &quot; terms: &quot;);<br>        for (int i = 0; i &lt; n; i++) {<br>            System.out.print(fibonacci(i) + &quot; &quot;);<br>        }<br>    }<br>}</pre><ul><li><strong>Time Complexity:</strong>O(2^n)</li><li><strong>Space Complexity: 0(n) (stack)</strong></li><li><strong>Pros:</strong> Very simple and readable code.</li><li><strong>Cons:</strong> Terrible time complexity O(2^n). Trying to find fibonacci(50) this way will cause your program to freeze.</li></ul><h3>2) Memoization / Dynamic Programming (Optimized Recursion)</h3><p>If you <em>must</em> use recursion but want it to be fast, you use <strong>Memoization</strong>. This technique stores the results of expensive function calls in an array (a cache) so you don’t re-calculate them.</p><pre>public class FibonacciMemoization {<br>    private static int[] cache;<br><br>public static int fibonacci(int n) {<br>        if (n &lt;= 1) return n;<br>        <br>        // If we already calculated it, just return it<br>        if (cache[n] != 0) return cache[n];<br>        <br>        // Otherwise, calculate and store it<br>        cache[n] = fibonacci(n - 1) + fibonacci(n - 2);<br>        return cache[n];<br>    }<br>    public static void main(String[] args) {<br>        int n = 10;<br>        cache = new int[n];<br>        <br>        System.out.print(&quot;Fibonacci Series: &quot;);<br>        for (int i = 0; i &lt; n; i++) {<br>            System.out.print(fibonacci(i) + &quot; &quot;);<br>        }<br>    }<br>}</pre><ul><li><strong>Time Complexity:</strong>O(n)</li><li><strong>Space Complexity: 0(n)</strong></li><li><strong>Pros:</strong> Drops the time complexity down to a blazing-fast O(n).</li><li><strong>Cons:</strong> Uses extra memory O(n) space complexity to store the array.</li></ul><h3>3) The Iterative Approach (Best for general use)</h3><p>This is the most efficient and practical way to print or find a Fibonacci number. It uses a simple loop and has a time complexity of O(n) and space complexity of O(1).</p><pre>public class FibonacciIterative {<br>    public static void printFibonacci(int n) {<br>        int a = 0, b = 1;<br>        System.out.print(&quot;Fibonacci Series up to &quot; + n + &quot; terms: &quot;);<br>        <br>        for (int i = 1; i &lt;= n; i++) {<br>            System.out.print(a + &quot; &quot;);<br>            int next = a + b;<br>            a = b;<br>            b = next;<br>        }<br>    }<br>   <br>public static void main(String[] args) {<br>        printFibonacci(10); // Outputs first 10 numbers<br>    }<br>}</pre><ul><li><strong>Time Complexity: </strong>O(n)</li><li><strong>Space Complexity: 0(1)</strong></li><li><strong>Pros:</strong> Highly efficient, no risk of StackOverflowError.</li><li><strong>Cons:</strong> Not as “elegant-looking” as recursion.</li></ul><h3>4) Java 8 Streams Approach (The Functional Way)</h3><p>If you love modern, functional Java, you can generate the Fibonacci series using Stream.iterate.</p><pre>import java.util.stream.Stream;<br><br>public class FibonacciStream {<br>    public static void main(String[] args) {<br>        int n = 10;<br>        <br>        System.out.print(&quot;Fibonacci Series via Streams: &quot;);<br>        Stream.iterate(new int[]{0, 1}, f -&gt; new int[]{f[1], f[0] + f[1]})<br>              .limit(n)<br>              .map(f -&gt; f[0])<br>              .forEach(num -&gt; System.out.print(num + &quot; &quot;));<br>    }<br>}</pre><ul><li><strong>Time Complexity: </strong>O(n)</li><li><strong>Space Complexity: 0(1)</strong></li><li><strong>Pros:</strong> Compact, declarative, and elegant.</li><li><strong>Cons:</strong> Marginally slower than the basic iterative loop due to object boxing, but perfectly fine for everyday use</li></ul><h3>Production Best Practices</h3><p>If you plan to deploy Fibonacci code into a high-scale production environment, there are a few subtle but major traps that can crash your application or cause incorrect data.</p><p>Here are the primary production issues you need to watch out for, along with how to fix them:</p><h3>1. Integer Overflow (The Silent Bug)</h3><p>The Fibonacci sequence grows exponentially. A standard Java 32-bit int will overflow surprisingly fast, resulting in negative numbers or garbage data.</p><ul><li><strong>int overflows at n = 47</strong></li><li><strong>long overflows at n = 93</strong></li></ul><h3>The Fix:</h3><p>If you need to calculate large Fibonacci numbers beyond the 92nd term, you <strong>must</strong> use BigInteger. While this prevents data corruption, it introduces a fresh infrastructure hazard: <strong>CPU Starvation</strong>.</p><p>BigInteger objects are immutable. Every addition requires allocating a new array of ints under the hood, scaling in time complexity based on the number of digits. If an API accepts an unvalidated request for $n = 1,000,000$, the CPU will instantly peg at 100% utilization computing the result. Saturated cores mean failed load-balancer health checks, dropped traffic, and cascading timeouts across your microservices.</p><pre>import java.math.BigInteger;<br><br>public class ProductionFibonacci {<br>    public static BigInteger getLargeFibonacci(int n) {<br>        BigInteger a = BigInteger.ZERO;<br>        BigInteger b = BigInteger.ONE;<br>        <br>        for (int i = 1; i &lt;= n; i++) {<br>            BigInteger next = a.add(b);<br>            a = b;<br>            b = next;<br>        }<br>        return a;<br>    }<br>}</pre><h3>2. StackOverflowError in Recursion</h3><p>If your code uses the naive recursive or even the memoized recursive approach, every function call adds a frame to the JVM call stack.</p><ul><li>If a user requests a high number (e.g., n = 10,000), the stack depth will exceed the JVM’s memory limits, abruptly crashing the thread with a java.lang.StackOverflowError.</li></ul><h3>The Fix:</h3><ul><li><strong>Never use recursion for open-ended inputs in production.</strong> Convert the logic to an iterative loop.</li></ul><h3>3. Memory Leaks in Memoization (The OutOfMemoryError Trap)</h3><p>If you chose the <strong>Memoization/Dynamic Programming</strong> approach using a static map or cache (like HashMap&lt;Integer, Long&gt;), that cache will live in memory forever.</p><ul><li>If your application handles thousands of unique, large requests, your JVM will eventually run out of heap memory and throw an OutOfMemoryError (OOM).</li></ul><h3>The Fix:</h3><ul><li>Use the <strong>Iterative</strong> approach instead, as it uses O(1) constant memory.</li><li>If you absolutely need a cache, use a proper caching library like <strong>Guava</strong> or <strong>Caffeine</strong> with a Time-To-Live (TTL) or maximum size limit configured.</li></ul><h3>4. Multi-Threaded Concurrency Issues</h3><p>If you are running this code inside a web server (like a Spring Boot application) and multiple user threads are updating or reading a shared cache (like the cache array or HashMap from the previous example) at the same time, it will cause race conditions or memory visibility issues.</p><h3>The Fix:</h3><ul><li>Keep variables local to the method so they are inherently thread-safe.</li><li>If a global cache is required, use a thread-safe data structure like ConcurrentHashMap.</li></ul><h3>Production Grade Code</h3><p>To make this production-ready, we must combine <strong>strict input validation</strong>, <strong>constant space complexity O(1)</strong>, <strong>arbitrary-precision math</strong>, and <strong>thread isolation</strong>.</p><p>Below is the definitive, production-grade implementation for calculating a Fibonacci sequence in Java:</p><pre>package com.enterprise.math;<br><br>import java.math.BigInteger;<br>import java.util.ArrayList;<br>import java.util.List;<br>/**<br> * Production-ready utility for generating Fibonacci sequences.<br> * Designed for thread-safety, memory efficiency, and input resilience.<br> */<br>public final class ProductionFibonacci {<br>    // Strictly enforce an upper boundary to prevent CPU Starvation DoS attacks<br>    private static final int MAX_ALLOWED_TERM = 10_000;<br>    private ProductionFibonacci() {<br>        // Prevent instantiation of utility class<br>    }<br>    /**<br>     * Generates a list of Fibonacci numbers up to the specified number of terms.<br>     *<br>     * @param terms The number of terms to generate.<br>     * @return A list containing the Fibonacci sequence.<br>     * @throws IllegalArgumentException if terms is out of safe production bounds.<br>     */<br>    public static List&lt;BigInteger&gt; generateSequence(int terms) {<br>        // 1. Guard Clauses &amp; Input Validation<br>        if (terms &lt; 0) {<br>            throw new IllegalArgumentException(&quot;Sequence terms cannot be negative.&quot;);<br>        }<br>        if (terms &gt; MAX_ALLOWED_TERM) {<br>            throw new IllegalArgumentException(<br>                String.format(&quot;Input exceeds safe limits. Maximum allowed terms is %d to protect system stability.&quot;, MAX_ALLOWED_TERM)<br>            );<br>        }<br>        List&lt;BigInteger&gt; sequence = new ArrayList&lt;&gt;(terms);<br>        if (terms == 0) {<br>            return sequence;<br>        }<br>        // 2. Localized, Thread-Safe Iteration<br>        BigInteger first = BigInteger.ZERO;<br>        sequence.add(first);<br>        <br>        if (terms == 1) {<br>            return sequence;<br>        }<br>        BigInteger second = BigInteger.ONE;<br>        sequence.add(second);<br>        // O(1) auxiliary space loop (excluding the output container)<br>        for (int i = 2; i &lt; terms; i++) {<br>            BigInteger next = first.add(second); // Generates a new BigInteger safely<br>            sequence.add(next);<br>            <br>            // Shift pointers forward<br>            first = second;<br>            second = next;<br>        }<br>        return sequence;<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd4fa44da493" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Thread Pool Death Spiral: How 5% Slowdown Causes 100% Outage]]></title>
            <link>https://medium.com/@kandaanusha/the-thread-pool-death-spiral-how-10-slowdown-causes-100-outage-5b61d8131a5e?source=rss-766c27233dc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b61d8131a5e</guid>
            <category><![CDATA[asynchronous-programming]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[threads]]></category>
            <dc:creator><![CDATA[Kandaanusha]]></dc:creator>
            <pubDate>Tue, 09 Jun 2026 18:40:10 GMT</pubDate>
            <atom:updated>2026-06-09T18:40:51.384Z</atom:updated>
            <content:encoded><![CDATA[<p>It’s Black Friday. Your e-commerce gateway is humming along beautifully at a steady 300 Queries Per Second (QPS). Suddenly, your pager goes off. The checkout service is completely unresponsive, throwing 504 Gateway Timeouts.</p><p>You look at the dashboards: CPU utilization is low, database health is perfect, and 95% of your microservices are responding in a blazing-fast 100ms. Yet, your entire gateway is paralyzed.</p><p>What went wrong? A classic <strong>Thread Exhaustion Cascading Failure</strong>.</p><p>Let’s look at how traditional <strong>thread-per-request </strong>architectures (like traditional Apache Tomcat, Spring MVC, or Ruby on Rails Unicorn) fall off a cliff when faced with partial downstream degradation — and how to architect a bulletproof fix.</p><h3>The Math Behind the Meltdown</h3><p>Consider a typical synchronous web server configured with a standard thread pool:</p><ul><li><strong>Thread Pool Size:</strong> 200 threads.</li><li><strong>Healthy Latency:</strong> 100ms per request.</li><li><strong>Single Thread Capacity:</strong> 1 second/ 0.1 seconds= 10 requests/sec.</li><li><strong>Total Max Capacity:</strong> 200 threads * 10 requests/sec = 2000 QPS.</li></ul><p>At an operating load of <strong>300 QPS</strong>, your server is operating well below its 2000 QPS ceiling. You feel safe.</p><p>Now, imagine a real-world failure: a third-party <strong>Fraud Detection API</strong> or an internal <strong>Personalized Recommendations RPC</strong> experiences a network partition. Instead of failing immediately, it hangs. <strong>5% of your incoming requests now take 15 seconds to respond.</strong></p><p>Here is how your 200 available threads vanish in a matter of seconds:</p><h3>The Cascading Failure Timeline</h3><p>Time -&gt; Incoming Traffic -&gt; Blocked Threads (5% of traffic) -&gt; Threads Left Available -&gt; Max Effective Server Capacity</p><p><strong>0s -&gt; </strong>300 QPS -&gt; 0 -&gt; 200 threads -&gt; 2000 QPS</p><p>1s -&gt; 300 requests arrived -&gt; 15 threads blocked -&gt; 185 Threads Left -&gt; 1850 QPS</p><p>2s -&gt; 300 requests arrived -&gt; 30 threads blocked -&gt; 170 Threads Left -&gt; 1700 QPS</p><p>3s -&gt; 300 requests arrived -&gt; 45 threads blocked -&gt; 155 Threads Left -&gt; 1550 QPS</p><p>5s -&gt; 300 requests arrived -&gt; 75 threads blocked -&gt; 125 Threads Left -&gt; 1250 QPS</p><p>10s -&gt; 300 requests arrived -&gt; 150 threads blocked -&gt; 50 Threads Left -&gt; 500 QPS</p><p>13s -&gt; 300 requests arrived -&gt; 195 threads blocked -&gt; 5 Threads Left -&gt; 50 QPS</p><p>By <strong>Second 14</strong>, your application server is a brick. Because all 200 worker threads are sitting completely idle waiting on the network socket, the server cannot accept any new incoming requests.</p><p>Traffic doesn’t just stop, though. The operating system’s TCP backlog queue starts piling up those 300 QPS in memory.</p><h3>The Aftermath (Second 15)</h3><p>At Second 15, the first 15 requests finally hit their backend timeout limit and return a DEADLINE_EXCEEDED error. Those 15 threads are suddenly freed!</p><p>But there’s no happy ending. They immediately emerge to face a massive backlog queue of <strong>over 4500 pending requests</strong> that have been piling up in the dark. 5% of <em>those</em> requests will instantly trigger the same 15-second backend delay. The server falls right back into thread starvation. Latency metrics spike to infinity, and your system remains dead locked until traffic is dropped entirely.</p><h3>The Naive Fix: Scaling Threads</h3><p>If you are on an incident call dealing with this right now, your primary goal is to rebalance the ratio of incoming QPS to available threads.</p><p>By applying <strong>Little’s Law</strong>, we can calculate the real thread capacity required to sustain this degraded state:</p><blockquote><strong>Threads = Arrival Rate (QPS) * Average Latency</strong></blockquote><p><strong>Average Latency:</strong></p><p>If 95% of requests take 0.1s and 5% take 15s, your new mathematical average latency is:</p><p>(0.95* 0.1s) + (0.05 * 15s) = 0.845 seconds</p><p><strong>Required Threads:</strong></p><p>To safely handle your steady state of 300 QPS, you suddenly need:</p><p>300 QPS * 0.845 seconds = 254 Threads required</p><p>To survive 300 QPS under these conditions, your server needs 254 threads, but it only has 200. You can temporarily fix this by:</p><ol><li><strong>Bumping Max Threads (Vertical):</strong> Increase the application server’s thread pool configuration from 200 to 300.</li><li><strong>Scaling Out (Horizontal):</strong> Spin up more server instances to distribute the 300 QPS across a larger total pool of threads.</li><li><strong>Traffic Shedding:</strong> Use a load balancer (like NGINX or AWS ALB) to drop traffic or return a fast 503 error code to non-critical requests.</li></ol><blockquote><em>⚠️ </em><strong><em>The Hidden Cost:</em></strong><em> JVM and OS threads are expensive. Each thread typically allocates 1MB of memory for its call stack. Blindly multiplying your thread count can easily push your server into </em><em>OutOfMemoryError (OOM) crashes or cause severe CPU context-switching overhead.</em></blockquote><h3>The Permanent Fix: Asynchronous, Non-Blocking Architecture</h3><p>The root cause of this vulnerability isn’t that the backend is slow — it’s that <strong>your worker threads are blocking while doing absolutely nothing.</strong></p><p>To fix this permanently, we must decouple request handling from network I/O using non-blocking frameworks (such as Netty, Spring WebFlux, or Node.js event loops).</p><h3>How Non-Blocking Saves Your Service</h3><p>Instead of locking a thread to a single user request for its entire lifecycle, an asynchronous controller utilizes promises or futures (e.g., ListenableFuture, CompletableFuture):</p><pre>// Synchronous (Bad) - Thread blocks here for 15s<br>UserPreferences prefs = recommendationClient.getWithBlocking(userId);<br>return render(prefs);<br><br>// Asynchronous (Good) - Thread is immediately freed<br>ListenableFuture&lt;UserPreferences&gt; future = recommendationClient.getAsync(userId);<br>return future.map(prefs -&gt; render(prefs));</pre><p>When using a non-blocking framework, the execution flow changes entirely:</p><ul><li>The gateway receives a request.</li><li>A worker thread kicks off the Fraud Detection RPC network call via non-blocking I/O (epoll/kqueue).</li><li>Instead of waiting, the method immediately returns a ListenableFuture object to the framework.</li><li>The framework registers a callback listener on that future and <strong>instantly releases the thread</strong> back to the pool to process other incoming users.</li><li>Fifteen seconds later, when the OS receives data from the backend network socket, a thread pool briefly wakes up to execute the callback and send the response back to the user.</li></ul><h3>Why This Prevents the Outage</h3><p>Let’s re-run our 5% slowdown scenario with an asynchronous server:</p><p>When that 5% of slow traffic hits, <strong>no threads are blocked</strong>. Your 200 threads can comfortably handle thousands of QPS because they only spend microseconds handing off I/O operations rather than sitting idle.</p><ul><li><strong>At 15 seconds:</strong> Your server is still processing 300 QPS perfectly. 95% of your users see a 100ms response time.</li><li><strong>The Only Trade-off:</strong> Because requests stay open longer, you will see a progressive buildup of ListenableFuture objects in heap memory, along with open TCP sockets.</li></ul><p>An async server shifts the failure domain from <strong>Thread Exhaustion</strong> (which causes sudden, total catastrophic collapse) to <strong>Memory Accumulation</strong> (which grows linearly and is vastly easier to manage via standard techniques like circuit breakers and rate limiters).</p><h3>The New Trade-Off: Trading Memory for Stability</h3><p>If 5% of your requests start taking 15 seconds in a non-blocking architecture, your 200 worker threads <strong>will continue to process the healthy 95% of traffic perfectly.</strong> However, engineering always involves trade-offs. While you won’t experience thread starvation, those slow, open requests must sit somewhere. They will accumulate as ListenableFuture references and un-flushed TCP buffers on the heap.</p><p>If the backend slowdown persists indefinitely under heavy load, your server will eventually hit a different ceiling: <strong>Running out of JVM Heap Memory</strong> or running out of OS file descriptors.</p><h3>Best Practice Checklist</h3><p>To completely bulletproof your system against cascading latency, combine asynchronous code with defensive patterns:</p><ul><li><strong>Strict Timeouts:</strong> Never let a backend call wait for 15 seconds. Set aggressive read timeouts (e.g., 500ms).</li><li><strong>Circuit Breakers:</strong> Use a pattern like Resilience4j. If the backend fails or slows down consistently, trip the circuit breaker to short-circuit and return a fallback response instantly without making the network call.</li></ul><p>If your microservices rely heavily on downstream network calls, <strong><em>going async isn’t just an optimization — it’s a resiliency requirement.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b61d8131a5e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Consumer Driven Contracts]]></title>
            <link>https://medium.com/@kandaanusha/consumer-driven-contracts-4d7d305502c4?source=rss-766c27233dc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d7d305502c4</guid>
            <category><![CDATA[cdc]]></category>
            <category><![CDATA[api-quality]]></category>
            <category><![CDATA[consumer-driven-contract]]></category>
            <dc:creator><![CDATA[Kandaanusha]]></dc:creator>
            <pubDate>Fri, 17 Apr 2026 16:17:46 GMT</pubDate>
            <atom:updated>2026-04-17T16:17:46.761Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Consumer-Driven Contract (CDC)</strong> is a collaborative pattern used to ensure that two services (a <strong>Provider</strong> and a <strong>Consumer</strong>) can communicate successfully, even as they evolve independently.</p><p>In the traditional world, the Provider (the API owner) dictates the schema. In CDC, the <strong>Consumer</strong> tells the Provider: <em>“Here is exactly what I need from you to function.”</em></p><h3>The “Gold” Rule of CDC</h3><blockquote><strong><em>Only specify what you actually use.</em></strong></blockquote><p>If a provider returns 50 fields but your consumer only needs id and email, your contract should <em>only</em> mention those two. This allows the provider to delete or change the other 48 fields without breaking your build, maximizing <strong>evolutionary architecture.</strong></p><h3>Popular Tools</h3><p>If you’re looking to implement this, these are the industry standards:</p><ul><li><strong>Pact:</strong> The most popular framework. It supports multiple languages (Java, JS, Python, Go, etc.) and uses a “Pact Broker” to share contracts between teams.</li><li><strong>Spring Cloud Contract:</strong> A powerhouse for the Java/Spring ecosystem that integrates deeply with WireMock.</li></ul><h3>Pact</h3><p>To implement <strong>Consumer-Driven Contracts (CDC)</strong> in Java, the most common tool is <strong>Pact</strong>. It allows the consumer to define their requirements in code, which then generates a “contract” (JSON file) that the provider must satisfy.</p><h4>1. The Consumer Side (Defining the Need)</h4><p>The consumer writes a test that defines the expected JSON structure. This test acts as a “mock” for the consumer’s unit tests, but it also generates the contract file.</p><pre>@ExtendWith(PactConsumerTestExt.class)<br>@PactTestFor(providerName = &quot;UserService&quot;)<br>public class UserContractTest {<br>@Pact(consumer = &quot;OrderService&quot;)<br>    public RequestResponsePact createPact(PactDslWithProvider builder) {<br>        return builder<br>            .given(&quot;User 123 exists&quot;)<br>            .uponReceiving(&quot;A request for User 123&quot;)<br>                .path(&quot;/users/123&quot;)<br>                .method(&quot;GET&quot;)<br>            .willRespondWith()<br>                .status(200)<br>                .body(new PactDslJsonBody()<br>                    .stringType(&quot;id&quot;, &quot;123&quot;)<br>                    .stringType(&quot;email&quot;) // Only checks that email is a String<br>                    .integerType(&quot;age&quot;, 25)<br>                    .close())<br>            .toPact();<br>    }<br>    @Test<br>    @PactTestFor<br>    void testGetUser(MockServer mockServer) {<br>        // Execute the real Java call against the mockServer<br>        // This ensures your Java DTOs can actually parse the defined contract<br>    }<br>}</pre><h4>2. The Pact Broker (The Handshake)</h4><p>Once the test passes, a .json contract file is generated. In a CI/CD pipeline, you upload this to a <strong>Pact Broker</strong>.</p><h4>3. The Provider Side (The Verification)</h4><p>The Provider (the service sending the JSON) pulls the contract from the broker and runs it against their actual controller. If they renamed email to user_email, this test will <strong>fail</strong> in their build pipeline.</p><pre>@Provider(&quot;UserService&quot;)<br>@PactBroker(url = &quot;https://your-broker-url.com&quot;)<br>public class PactProviderTest {<br>@TestTemplate<br>    @ExtendWith(PactVerificationInvocationContextProvider.class)<br>    void pactVerificationTestTemplate(PactVerificationContext context) {<br>        context.verifyInteraction();<br>    }<br>    <br>    @BeforeEach<br>    void before(PactVerificationContext context) {<br>        // Point to your running local server or use a MockMVC target<br>        context.setTarget(new HttpTestTarget(&quot;localhost&quot;, 8080));<br>    }<br>}</pre><h4>How this handles Evolution in CI/CD</h4><ul><li><strong>Breaking Change Prevention</strong>: If a developer on the Provider team deletes a field that the Consumer still has in their contract, the Provider’s CI build fails immediately.</li><li><strong>Safe Deletion</strong>: The Provider can see exactly which fields are <em>not</em> in any consumer contracts. If a field isn’t in a contract, it is safe to delete.</li><li><strong>Independent Deployments</strong>: Since the contract is verified during the build, you don’t need to coordinate deployments. If the build passes, you know the services are compatible.</li></ul><h3>Summary Checklist for Implementation</h3><ul><li><strong>Identify Consumers</strong>: Who is calling your API?</li><li><strong>Write Pacts</strong>: Focus only on the fields you actually use (The Tolerant Reader).</li></ul><p><strong>Automate in CI</strong>:</p><ul><li><strong>Consumer CI</strong>: Runs tests -&gt; Publishes Pact.</li><li><strong>Provider CI</strong>: Pulls Pact -&gt; Verifies -&gt; Deploys only if “Can-I-Deploy” check passes.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d7d305502c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling JSON evolution in Java]]></title>
            <link>https://medium.com/@kandaanusha/handling-json-evolution-in-java-52c173fa9495?source=rss-766c27233dc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/52c173fa9495</guid>
            <category><![CDATA[json-schema]]></category>
            <category><![CDATA[contracts]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[json]]></category>
            <dc:creator><![CDATA[Kandaanusha]]></dc:creator>
            <pubDate>Fri, 17 Apr 2026 16:09:08 GMT</pubDate>
            <atom:updated>2026-04-17T16:09:08.906Z</atom:updated>
            <content:encoded><![CDATA[<p>Handling JSON evolution in a live Java production environment is like trying to change the tires on a car while it’s moving at 70 mph. You can’t stop the traffic (the data flow), so you have to ensure your application is resilient to both “additive” and “destructive” changes.</p><h3>1. New Fields Added</h3><blockquote><strong>The Golden Rule: “Ignore Unknown Properties”</strong></blockquote><p>By default, many Java JSON libraries (like Jackson) will throw an exception if they encounter a field in the JSON that doesn’t exist in your Java POJO. In a live environment, this is a recipe for disaster when the producer adds a new feature.</p><p><strong>The Fix:</strong> Configure your Object Mapper to be “permissive.”</p><ul><li><strong>Jackson:</strong> Use @JsonIgnoreProperties(ignoreUnknown = true) at the class level, or configure the global mapper: mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);</li><li><strong>Gson:</strong> This is the default behavior, but ensure you aren’t using strict configurations.</li></ul><h3>2. Fields Removed</h3><blockquote><strong>The Golden Rule: “Use Wrappers. Use Optional /Default Values”</strong></blockquote><p>When fields are removed , they arrive as null. Your code should be defensive.If a field is missing from the JSON, Jackson tries to assign null to the Java field. If your field is a primitive (like int or boolean), the application will crash.</p><ul><li><strong>Avoid primitives:</strong> Use Integer instead of int. Primitives will throw an error if the field is missing, whereas Integer will simply be null.</li><li><strong>Default Values:</strong> Initialize your fields to a safe “fallback” value.</li></ul><pre>public class SettingsDto {<br>    private String theme = &quot;light&quot;; // Default value if JSON is missing &quot;theme&quot;<br>    private int timeoutMs = 5000;<br>}</pre><h3><strong>3. Fields Renamed</strong></h3><blockquote><strong>The Golden Rule: “Use Aliases”</strong></blockquote><p>If a producer renames a field , your app will usually see the old field as null and ignore the new one. You don&#39;t want to break your internal logic. The @JsonAlias annotation allows you to accept multiple names for the same field during deserialization.</p><pre>public class UserDto {<br>    @JsonAlias({ &quot;user_id&quot;, &quot;id&quot;, &quot;account_number&quot; })<br>    private Long id;<br>}</pre><blockquote><strong><em>Note:</em></strong><em> Jackson will still use the field name (or </em><em>@JsonProperty) for serialization, but it will accept any of the aliases when reading.</em></blockquote><h3>4.Field Data Type Changed (Polymorphism)</h3><p>Sometimes a producer changes a String to an Object, or a single Object to a List. To handle this without crashing, you can use a <strong>Custom Deserializer</strong>.</p><pre>public class FlexibleDeserializer extends JsonDeserializer&lt;List&lt;String&gt;&gt; {<br>    @Override<br>    public List&lt;String&gt; deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {<br>        JsonNode node = p.getCodec().readTree(p);<br>        if (node.isArray()) {<br>            // Handle as list<br>            return new ObjectMapper().convertValue(node, new TypeReference&lt;List&lt;String&gt;&gt;(){});<br>        } else {<br>            // Handle single string as a list of one<br>            return Collections.singletonList(node.asText());<br>        }<br>    }<br>}</pre><h3>5. The “Catch-All” (Forward Compatibility)</h3><p>In microservices, you often have “Pass-through” services that receive JSON, modify one field, and send the rest along. If you don’t map every field, you lose data.</p><p>If you need to ensure you don’t lose data even if you don’t have a specific field for it, use @JsonAnySetter. This captures all &quot;extra&quot;/unampped fields into a Map preserving them for later.</p><pre>public class FlexibleDto {<br>    private String knownField;<br><br>    // This map catches everything not explicitly defined above<br>    private Map&lt;String, Object&gt; extraFields = new HashMap&lt;&gt;();<br><br>    @JsonAnySetter<br>    public void addExtra(String key, Object value) {<br>        extraFields.put(key, value);<br>    }<br>    <br>    @JsonAnyGetter<br>    public Map&lt;String, Object&gt; getExtra() {<br>        return extraFields;<br>    }<br>}</pre><h3>Advanced Techniques</h3><p>Beyond the Jackson-specific annotations, handling evolution at scale — especially in microservices — often requires architectural patterns that go beyond just “ignoring” fields.</p><p>Here are the advanced strategies for managing long-term JSON evolution:</p><h3>1. The Schema Registry (The “Contract” Method)</h3><p>Instead of letting the JSON be a “surprise” at runtime, you use a Schema Registry (like <strong>Confluent</strong> or <strong>Apurio</strong>).</p><ul><li><strong>How it works:</strong> You define your data structure using <strong>Avro</strong>, <strong>Protobuf</strong>, or <strong>JSON Schema</strong>.</li><li><strong>Evolution Rules:</strong> The registry enforces “Backward,” “Forward,” or “Full” compatibility. If a producer tries to push a breaking change (like deleting a required field), the registry rejects the change before it ever hits the consumer.</li></ul><h3>2. Header-Based Versioning</h3><p>When a change is too big for @JsonAlias to handle, you should move to explicit versioning. This allows the consumer to &quot;negotiate&quot; which version of the data it can handle.</p><ul><li><strong>Media Type Versioning:</strong> Accept: application/vnd.myapi.v2+json</li><li><strong>Custom Header:</strong> X-API-Version: 2</li></ul><p>In your Java code, you can use <strong>Spring’s </strong><strong>@RequestMapping</strong> to route different versions to different DTOs:</p><pre>@GetMapping(value = &quot;/user&quot;, produces = &quot;application/vnd.myapi.v1+json&quot;)<br>public UserV1 getUserV1() { ... }<br><br>@GetMapping(value = &quot;/user&quot;, produces = &quot;application/vnd.myapi.v2+json&quot;)<br>public UserV2 getUserV2() { ... }</pre><h3>3. The “Tolerant Reader” Pattern</h3><p>This is a design philosophy rather than a library feature. A <strong>Tolerant Reader</strong> only extracts the data it absolutely needs to perform its job and ignores everything else.</p><ul><li><strong>Implementation:</strong> Instead of mapping the entire JSON to a massive POJO with 50 fields, use JsonPath or a small, targeted DTO.</li></ul><h3>4. Handling Type Widening (The JsonNode Fallback)</h3><p>Sometimes a field starts as a simple int but needs to become a String or a complex Object later. To avoid mapping errors, you can use JsonNode as a catch-all for a specific field:</p><pre>public class EventDto {<br>    private String eventName;<br>    private JsonNode payload; // This can be a String, Number, or Object<br>}</pre><p>You then use payload.isObject() or payload.isTextual() at runtime to decide how to process it.</p><h3>5. Post-Deserialization Validation</h3><p>Since you’ve turned off FAIL_ON_UNKNOWN_PROPERTIES, your JSON parser is now very &quot;quiet.&quot; It won&#39;t complain if critical data is missing.</p><ul><li><strong>The Solution:</strong> Use <strong>Bean Validation (JSR 380)</strong>.</li><li>Even if the JSON parses successfully, @NotNull or @Min(1) will ensure the evolved JSON still meets your business requirements.</li></ul><pre>public class UserDto {<br>    @NotNull // Ensures that even if the schema evolved, this vital field exists<br>    private String email;<br>}</pre><h3>Automate the checks</h3><p>This moves the “check” from the runtime (where it crashes your app) to the build time (where it prevents the deployment of breaking changes).</p><h3>1. Consumer-Driven Contracts (Pact / Spring Cloud Contract)</h3><p>Instead of the Provider dictating the schema, the <strong>Consumer</strong> defines a “contract” (a JSON file) of exactly what fields they need and what the response should look like.</p><ul><li><strong>The Flow:</strong> The Consumer generates a contract -&gt; The Provider runs this contract against their code → If the Provider changes a field name that the Consumer relies on, the Provider’s build <strong>fails</strong>.</li><li><strong>Benefit:</strong> This eliminates “integration hell” where one team deploys a change that unknowingly breaks three other services.</li></ul><h3>2. Backward Compatibility Testing with OpenAPI</h3><p>If you use Swagger/OpenAPI, you can automate schema comparison using tools like <strong>OpenAPI Diff</strong>.</p><ul><li><strong>In your Pipeline:</strong> You compare the swagger.json of the new version against the production version.</li><li><strong>The Check:</strong> If a field was deleted or a type was changed (e.g., string to integer), the tool flags it as a <strong>Breaking Change</strong>.</li><li><strong>The Integration:</strong> You can break the Jenkins/GitHub Actions build if a breaking change is detected without a corresponding version bump.</li></ul><h3>3. Feature Toggles for Gradual Migration</h3><p>When the JSON structure changes significantly, you can’t always update all consumers at once. Use <strong>Feature Toggles</strong> to handle the transition.</p><ol><li><strong>Phase 1:</strong> Producer sends <em>both</em> old and new fields.</li><li><strong>Phase 2:</strong> Consumer is updated to read the new field but falls back to the old one if the new is null.</li><li><strong>Phase 3:</strong> Toggle the consumer to strictly use the new field.</li><li><strong>Phase 4:</strong> Producer stops sending the old field.</li></ol><h3>4. Shadow Mirroring</h3><p>For high-stakes JSON changes, you can use <strong>Shadow Mirroring</strong>. Your Java application receives the “new” JSON format in a background thread or a secondary “shadow” environment.</p><ul><li>You compare the result of the new parsing logic against the old logic.</li><li>If the results match for 24 hours of production traffic, you promote the new schema to live status.</li></ul><h3>Summary Checklist for Resilient JSON</h3><ul><li><strong>New fields added: </strong>FAIL_ON_UNKNOWN_PROPERTIES = false</li><li><strong>Field removed: </strong>Use Wrapper classes (Integer) + Default values</li><li><strong>Field renamed: </strong>@JsonAlias</li><li><strong>Data preservation</strong>@JsonAnySetter / @JsonAnyGetter</li><li><strong>Structure change: </strong>Custom JsonDeserializer</li></ul><h3>Summary of Advanced Techniques</h3><ul><li><strong>Schema Registry: </strong>Large-scale microservices using Kafka or Event-driven logic.</li><li><strong>Versioning: </strong>Massive structural changes that would break old code.</li><li><strong>Tolerant Reader: </strong>Minimizing the “surface area” of potential breaks.</li><li><strong>Bean Validation: </strong>Ensuring data quality in a “lenient” parsing environment.</li></ul><h3>Summary of Advanced Lifecycle Strategies</h3><ul><li><strong>CDC (Pact): </strong>When you have many internal microservices. Complexity is High (Requires team buy-in)</li><li><strong>OpenAPI Diff: </strong>When you provide a public API.Complexity is Low (Automated tool)</li><li><strong>Feature Toggles: </strong>To avoid “Big Bang” deployments.Medium COmplexity,</li><li><strong>Shadow Mirroring: </strong>For mission-critical financial/medical data.High complexity(Infrastructure heavy)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52c173fa9495" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering JSON to Java Mapping: From Basics to Production-Grade Architecture]]></title>
            <link>https://medium.com/@kandaanusha/mastering-json-to-java-mapping-from-basics-to-production-grade-architecture-c74e67811735?source=rss-766c27233dc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/c74e67811735</guid>
            <category><![CDATA[json-schema]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Kandaanusha]]></dc:creator>
            <pubDate>Thu, 16 Apr 2026 13:46:49 GMT</pubDate>
            <atom:updated>2026-04-16T13:46:49.725Z</atom:updated>
            <content:encoded><![CDATA[<p>Mapping JSON (JavaScript Object Notation) to Java objects is the process of <strong>deserialization</strong>, while the reverse is <strong>serialization</strong>.</p><p>If you have this JSON:</p><pre>{<br>  &quot;id&quot;: 101,<br>  &quot;username&quot;: &quot;java_dev&quot;,<br>  &quot;roles&quot;: [&quot;admin&quot;, &quot;editor&quot;]<br>}</pre><p>Your <strong>Java POJO</strong> (Plain Old Java Object) would look like this:</p><pre>public class User {<br>    private int id;<br>    private String username;<br>    private List&lt;String&gt; roles;<br>// Standard Getters and Setters are required for the Mapper to work<br>    public int getId() { return id; }<br>    public void setId(int id) { this.id = id; }<br>    // ... etc<br>}</pre><h3>Popular Libraries</h3><p>While you could parse JSON manually, almost every professional project uses one of these two industry standards:</p><h4>Jackson (The Industry Leader)</h4><p>Used by default in Spring Boot. It is highly performant and feature-rich.</p><ul><li><strong>Main Class:</strong> ObjectMapper</li><li><strong>Example:</strong> ObjectMapper mapper = new ObjectMapper(); User user = mapper.readValue(jsonString, User.class);</li></ul><h4>Gson (By Google)</h4><p>Lightweight and very easy to use for simple projects or Android development.</p><ul><li><strong>Main Class:</strong> Gson</li><li><strong>Example:</strong> Gson gson = new Gson(); User user = gson.fromJson(jsonString, User.class);</li></ul><h3>Advanced Configurations</h3><p>Production JSON is rarely “perfect.” Your code must handle unexpected API changes without crashing.</p><ul><li><strong>Handling Field Name Mismatches: </strong>Often, JSON uses snake_case while Java uses camelCase. You can bridge this using <strong>Annotations</strong> so you don&#39;t have to rename your Java variables.</li></ul><p>Jackson<strong>:</strong> @JsonProperty(&quot;first_name&quot;)</p><p>Gson<strong>:</strong> @SerializedName(&quot;first_name&quot;)</p><ul><li><strong>Ignore Unknowns:</strong> Prevent your application from failing if the producer adds a new field you don’t need yet.</li></ul><p>objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);</p><ul><li><strong>Fail on Null Primitives:</strong> If a JSON field is missing but your Java field is a primitive int, Jackson defaults it to 0. In production, this can hide data bugs.</li></ul><p>objectMapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, true);</p><ul><li><strong>Standardize Dates:</strong> Never rely on default date formats. Force ISO-8601 to ensure cross-platform compatibility.</li></ul><h3>Production Grade:</h3><p>Moving from basic JSON mapping to <strong>production-grade</strong> implementation requires a shift in focus from “making it work” to “making it resilient, performant, and maintainable.”</p><p>In a high-traffic environment, a naive ObjectMapper setup can become a bottleneck or a source of silent failures.</p><h4>1. Thread-Safety and Global Configuration Strategy</h4><p>The most common production mistake is creating a new ObjectMapper (Jackson) or Gson instance for every request.</p><ul><li><strong>The Rule:</strong> Create a single, static instance and reuse it. ObjectMapper is fully thread-safe after configuration.Use a <strong>Singleton</strong> or a Spring Bean</li><li><strong>Why?</strong> The mapper builds a massive internal cache of the classes it inspects. Re-instantiating it destroys this cache, leading to significant CPU spikes and GC pressure.</li></ul><p>If you are using <strong>Spring Boot 3.x+</strong>, don’t configure ObjectMapper in every service. Use a centralized configuration bean to enforce consistency across the entire microservice.</p><pre>@Configuration<br>public class JsonMappingConfig {<br><br>@Bean<br>    @Primary<br>    public ObjectMapper productionMapper() {<br>        return JsonMapper.builder()<br>            // 1. Support for Java 8 Dates/Times<br>            .addModule(new JavaTimeModule())<br>            // 2. Support for Java Records and Parameter Names<br>            .addModule(new ParameterNamesModule())<br>            // 3. Resilience: Don&#39;t crash on new API fields<br>            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)<br>            // 4. Precision: Avoid floating point issues in financial data<br>            .configure(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS, true)<br>            // 5. Cleanliness: Don&#39;t send &#39;null&#39; fields back to the client<br>            .serializationInclusion(JsonInclude.Include.NON_NULL)<br>            .build();<br>    }<br>}</pre><h4>2. High-Performance Mapping: Records vs. Classes</h4><p>With Java 17+, <strong>Records</strong> are the gold standard for DTOs (Data Transfer Objects).</p><ul><li><strong>Memory Efficiency:</strong> Records are immutable and have a smaller footprint than standard classes.</li><li><strong>Jackson Integration:</strong> Jackson handles records natively. Because they are immutable, they prevent “accidental mutation” of data as it moves through your service layers.</li></ul><pre>public record UserResponse(<br>    long id,<br>    String email,<br>    @JsonProperty(&quot;is_active&quot;) boolean isActive<br>) {}</pre><p><strong>Pro-Tip:</strong> Use <strong>Lombok</strong> (@Data) if you are stuck on older Java versions to eliminate boilerplate getters and setters.</p><h4>3. The “Contract-First” Layer</h4><p>Instead of manually writing Java classes to match JSON, use <strong>OpenAPI (Swagger)</strong>.</p><ul><li><strong>Source of Truth:</strong> Define your JSON structure in a .yaml file.</li><li><strong>Code Generation:</strong> Use the openapi-generator-maven-plugin to generate your DTOs (Data Transfer Objects) during the build phase.</li><li><strong>Benefit:</strong> This ensures that your Java code and your documentation are never out of sync. It also generates the Jackson annotations automatically.</li></ul><h4>4. Data Integrity &amp; Validation</h4><p>Mapping only checks if the <strong>format</strong> is correct. You need <strong>Bean Validation</strong> to ensure the <strong>data</strong> is valid.</p><ul><li><strong>Pattern:</strong> Integration of hibernate-validator with your DTOs.</li><li><strong>Implementation:</strong></li></ul><pre>public record UserSignupRequest(<br>    @NotBlank @Size(min = 3, max = 20) String username,<br>    @Email String email,<br>    @Past LocalDate birthDate<br>) {}</pre><ul><li><strong>Production Rule:</strong> Always use @Valid or @Validated in your controllers to trigger the validation logic immediately after the JSON is mapped to the object.</li></ul><h4>5. Handling Evolutionary Changes</h4><p>In a microservices architecture, JSON structures <em>will</em> change. Use <strong>Shadow Mapping</strong> or <strong>DTO Versioning</strong>.Modern systems favor a <strong>Three-Layer Model</strong> (DTO, Domain, and Persistence) to ensure that changes in an external API don’t break your internal business logic.</p><ul><li><strong>The Strategy:</strong> Never expose your internal @Entity (database) classes as JSON.</li><li><strong>The Flow:</strong> JSON -&gt; DTO (Versioned) -&gt; MapStruct (Mapper) -&gt;Domain Model. Eg: Controller layer receives JSON and deserializes it into a UserRequestDTO. In Mapping Layer MapStruct converts the UserRequestDTO into a User Domain Object. In Service Layer, business logic is performed using User Domain Object</li><li><strong>MapStruct:</strong> Use this library to map your JSON DTOs to internal objects. It generates code at compile-time, making it significantly faster than reflection-based mappers like ModelMapper.</li><li><strong>Decoupling:</strong> If the API changes “full_name” to “userName”, you only update the DTO and the Mapper. Your 10,000 lines of business logic remain untouched.</li></ul><h4>6. Handling “Excessive” Data</h4><p>JSON processing is often a hidden CPU hog.</p><ul><li><strong>Micrometer Metrics:</strong> Wrap your mapping logic or use the built-in Spring Boot instrumentation to track how long deserialization takes.</li><li><strong>Thresholds:</strong> If you notice mapping takes &gt;10ms for a standard payload, it’s a sign that your object graph is too deep or you need to switch to the <strong>Jackson Streaming API</strong></li></ul><p>Instead of loading the entire JSON into memory, use JsonParser to process tokens one by one. This allows you to process a 1GB file with only a few kilobytes of RAM.</p><pre>JsonFactory factory = new JsonFactory();<br>try (JsonParser parser = factory.createParser(new File(&quot;huge_data.json&quot;))) {<br>    while (parser.nextToken() != JsonToken.END_ARRAY) {<br>        // Process individual objects here without loading the whole list<br>    }<br>}</pre><h4>7. Security: Avoiding Remote Code Execution (RCE)</h4><p>“Gadget chains” in JSON deserialization are a major security vector.</p><ul><li><strong>Never</strong> enable “Default Typing” (enableDefaultTyping()) on an ObjectMapper that processes untrusted input. This can allow attackers to force the JVM to instantiate malicious classes.</li><li><strong>Use a Validator:</strong> Always combine mapping with <strong>Bean Validation (JSR 380)</strong>. Mapping only ensures the structure is right; validation ensures the <em>data</em> is sane.</li></ul><pre>public record PaymentRequest(<br>    @Positive long amount, <br>    @NotBlank String currency<br>) {}</pre><p>By decoupling your internal domain models from your JSON DTOs and utilizing compile-time mapping, you ensure your Java application remains fast, secure, and easy to maintain.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c74e67811735" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>