<?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 CodeCraft by Ramcharan on Medium]]></title>
        <description><![CDATA[Stories by CodeCraft by Ramcharan on Medium]]></description>
        <link>https://medium.com/@yramcharanteja?source=rss-e072c7cbc844------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by CodeCraft by Ramcharan on Medium</title>
            <link>https://medium.com/@yramcharanteja?source=rss-e072c7cbc844------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 11:42:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yramcharanteja/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[Amazon ECR for Spring Boot Developers: Where Your Docker Image Lives Before AWS Runs It]]></title>
            <link>https://medium.com/@yramcharanteja/amazon-ecr-for-spring-boot-developers-where-your-docker-image-lives-before-aws-runs-it-ff71a1cda592?source=rss-e072c7cbc844------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff71a1cda592</guid>
            <category><![CDATA[aws-ecr]]></category>
            <dc:creator><![CDATA[CodeCraft by Ramcharan]]></dc:creator>
            <pubDate>Wed, 18 Nov 2026 02:34:00 GMT</pubDate>
            <atom:updated>2026-11-18T02:34:00.947Z</atom:updated>
            <content:encoded><![CDATA[<h4>The missing link between docker build and your ECS deployment</h4><p>You’ve built a Spring Boot app on Java 21 and packaged it with Gradle:</p><pre>./gradlew clean bootJar<br>docker build -t springboot-demo:1.0.0 .<br>docker run -p 8080:8080 springboot-demo:1.0.0</pre><p>It works on your laptop. Time to ship it to AWS.</p><p>But <strong>how does ECS or Fargate get the image you just built?</strong></p><p>It can’t. That image exists only in your local Docker environment, and AWS has no way to reach into your machine. You need a central place to store it, and that’s what a <strong>container registry</strong> is for.</p><p>Available container registries: Docker Hub, Amazon ECR, GitHub Container Registry, GitLab Container Registry, <strong>Google Artifact Registry</strong>, JFrog Artifactory.</p><h4>What is Amazon ECR?</h4><p>Amazon Elastic Container Registry (ECR) is a fully managed AWS registry for storing, managing, and distributing Docker and OCI-compatible images.</p><p>Instead of keeping your image on your laptop, you push it to an ECR repository. ECS then pulls it whenever it needs to start your containers.</p><h4>How it all fits together</h4><ol><li>Build the Spring Boot app with Gradle.</li><li>Package it into a Docker image.</li><li>Authenticate Docker to ECR and push the image to a repository.</li><li>Point your ECS task definition at the image.</li><li>Run the containers on Fargate.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4sCfyUjqDGEptMlOmxPisg.png" /></figure><p><strong>A common misconception </strong>is that ECR runs your containers. <br>It doesn’t. ECR is an image registry, not a runtime or an orchestrator. It holds the image, and something else runs it.</p><h4>Core Components of Amazon ECR</h4><p><strong>Registry</strong>: The top-level namespace that holds your repositories. Every AWS account gets one private registry <strong>per Region</strong>, with an endpoint like this</p><pre>&lt;aws-account-id&gt;.dkr.ecr.&lt;region&gt;.amazonaws.com<br>For example: 123456789012.dkr.ecr.us-east-1.amazonaws.com</pre><p><strong>Repository: </strong>A named collection of images for one application. If you have three microservices, you’d typically create three repositories. <br>Each repository holds multiple versions of its service. Repositories also carry settings like tag mutability, encryption, access permissions, and lifecycle policies.</p><p><strong>Image: </strong>The packaged application: code, runtime, libraries, and startup configuration. For a typical Spring Boot service, that means the Java 21 runtime, the executable JAR, and its dependencies.</p><p><strong>Image tag: </strong>A human-readable label for a version, such as 1.0.0, 1.1.0, or latest.</p><p>By default, ECR repositories allow tags to act as movable pointers rather than permanent labels. When you push a new image using a tag name that already exists (such as latest or v1.0), ECR simply reassigns that tag to the new image.</p><p>Set explicitly immutable tags when creating a repository. ECR rejects any push that reuses an existing tag.</p><p><strong>Image digest: </strong>It is a permanent, cryptographic fingerprint of a container’s exact contents.</p><p>Using a <strong>digest </strong>guarantees you run the same code every time, whereas a <strong>tag </strong>can be reassigned to a newer build.</p><p><strong>Image URI:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L7WvzQrvt8rnrLPbrU_xDg.png" /></figure><h4>Hands-on: Push a Spring Boot Docker Image to Amazon ECR Using CI/CD</h4><p>Now that we understand Amazon ECR, let’s see how to publish a Spring Boot Docker image using GitLab CI/CD.</p><ol><li><strong>Create a Spring Boot application:</strong> Develop a simple REST API using Java 21, Spring Boot, and Gradle. Add a Dockerfile to package the executable JAR into a Docker image.</li><li><strong>Create an ECR repository:</strong> In the AWS Console, navigate to <strong>Amazon ECR → Private repositories → Create repository</strong>. This repository will store our Docker images.</li><li><strong>Host the source code:</strong> Push the Spring Boot project to a Git hosting platform such as GitLab, GitHub, or Bitbucket.</li><li><strong>Establish authentication with AWS:</strong> Configure secure authentication between the CI/CD platform and AWS. GitLab CI/CD and GitHub Actions support <strong>OpenID Connect (OIDC)</strong>, allowing pipelines to assume an AWS IAM role and obtain temporary credentials without storing long-lived access keys.</li><li><strong>Configure IAM permissions:</strong> Create an IAM role with the required ECR push permissions and restrict access to the intended repository. Configure the role’s trust policy to allow the authorized GitLab or GitHub project to assume it.</li><li><strong>Configure the CI/CD pipeline:</strong> Add .gitlab-ci.yml for GitLab or a workflow YAML file under .github/workflows/ for GitHub. The pipeline builds the Spring Boot JAR, runs tests, builds the Docker image, authenticates with AWS, and pushes the image to ECR.</li><li><strong>Verify the published image:</strong> Trigger the pipeline by pushing code to the repository. Once it succeeds, open <strong>AWS Console → ECR → Private repositories → Images</strong> to verify the image tag, digest, and push timestamp.</li></ol><h4>My GitLab Implementation</h4><p>I implemented this workflow using <strong>GitLab CI/CD, AWS IAM OIDC, Docker, and Amazon ECR</strong>.</p><p><strong>Source code:</strong> <a href="https://gitlab.com/CodeCraftByRamcharan/aws-ecr-demo">CodeCraftByRamcharan/aws-ecr-demo</a></p><p>The repository contains the Spring Boot application, Dockerfile, and GitLab CI/CD configuration.</p><p>The pipeline automates the process:</p><p><strong>Git Push → Gradle Build &amp; Tests → Docker Build → AWS OIDC Authentication → ECR Push</strong></p><p>The Docker image is built and published entirely through a GitLab-hosted runner, without requiring Docker or AWS CLI on my local machine.</p><p>Once the image is successfully published to ECR, the next step is to deploy it using <strong>Amazon ECS and AWS Fargate</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff71a1cda592" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Load Balancing Evolved]]></title>
            <link>https://medium.com/@yramcharanteja/how-load-balancing-evolved-e26cb3775b8c?source=rss-e072c7cbc844------2</link>
            <guid isPermaLink="false">https://medium.com/p/e26cb3775b8c</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[load-balancing]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-alb]]></category>
            <dc:creator><![CDATA[CodeCraft by Ramcharan]]></dc:creator>
            <pubDate>Thu, 12 Nov 2026 19:12:08 GMT</pubDate>
            <atom:updated>2026-11-12T19:12:08.096Z</atom:updated>
            <content:encoded><![CDATA[<p>At first, an application ran on a<strong> single server</strong>. This was simple, but risky: if the server crashed, the whole app went down, and growing traffic meant buying a bigger machine.</p><p>So teams ran several copies of the app on different servers, which raised a new question: which server should the client call? <strong>DNS round robin</strong> couldn’t tell if a server was dead. Hardware load balancers like <strong>F5</strong> were expensive. Software ones like <strong>Nginx </strong>and <strong>HAProxy required the team to install, patch, and scale them</strong>.</p><p>Microservices made it harder, since requests now needed to reach the right service first and then the right copy of it. Spring Cloud solved this with <strong>Zuul, Eureka,</strong> and <strong>Ribbon</strong>, but teams had to build and run all of it themselves.</p><h4>Before AWS Application Load Balancer (ALB)</h4><p>Before ALB arrived in 2016, AWS offered the Classic Load Balancer (CLB), launched in 2009. It distributed incoming traffic across multiple EC2 instances and checked their health. CLB supported Layer 4 (TCP/SSL) and basic Layer 7 (HTTP/HTTPS) load balancing, but without content-based routing.</p><p>That worked well for monolithic applications. As systems moved to microservices, developers needed more. Imagine an application with two Spring Boot services:</p><ul><li><strong>User Service:</strong> handles /users/*</li><li><strong>Order Service:</strong> handles /orders/*</li></ul><p>CLB could spread HTTP requests across instances, but it could not send /users/* to one service and /orders/* to another. Teams had to run a separate load balancer for each service, or place a reverse proxy such as Nginx or HAProxy in front.</p><p>AWS introduced ALB in 2016 to solve this. ALB brought Layer 7 routing, so a single load balancer could inspect each HTTP request and send it to the right backend based on its path, hostname, or other conditions.</p><h4>What is AWS Application Load Balancer (ALB)?</h4><p>AWS Application Load Balancer (ALB) is a fully managed Layer 7 load balancer that distributes incoming HTTP and HTTPS requests across multiple application instances or services.</p><p>Layer 7 is the application layer, where the actual HTTP request (URL, headers, cookies) is visible. Unlike a Layer 4 load balancer, which only sees IP addresses and ports, ALB can inspect the URL path, hostname, and headers to decide where to route traffic.</p><pre>              Users<br>                |<br>                v<br>             AWS ALB<br>                |<br>       +--------+--------+<br>       |                 |<br>    /users/*         /orders/*<br>       |                 |<br>       v                 v<br>  User Service      Order Service<br>  (Spring Boot)     (Spring Boot)</pre><p>A single ALB can route traffic to multiple microservices, so you no longer need a separate load balancer for each one.</p><p><strong>Key capabilities</strong></p><ul><li><strong>Path- and host-based routing:</strong> Route requests to different services based on URL paths or domains.</li><li><strong>Health checks:</strong> Stop sending requests to unhealthy targets, and resume when they recover.</li><li><strong>Multi-AZ availability:</strong> Spread traffic across healthy targets in multiple Availability Zones, so the app keeps running even if one data center fails.</li><li><strong>HTTPS termination:</strong> Manage TLS certificates through AWS Certificate Manager (ACM).</li><li><strong>Fully managed:</strong> AWS handles the infrastructure, maintenance, and patching.</li></ul><h4>How does ALB relate to Zuul, Ribbon, and Eureka?</h4><p>If you have worked with Spring Cloud, these concepts will feel familiar.</p><pre>Spring Cloud      |  AWS ALB equivalent<br>---------------------------------------------------------------------<br>Zuul              |  Listener rules route requests by path or host<br>Ribbon            |  ALB distributes requests across healthy targets<br>Eureka            |  Target groups keep a list of registered targets</pre><p>The jobs are similar, but the placement differs. Ribbon is client-side and runs inside your application, while ALB is server-side and runs as a separate AWS service.</p><p>Also, target groups don&#39;t fully replace Eureka. They track registered targets and their health, but they do not provide general service discovery for application-to-application calls.</p><h4>Understanding ALB Architecture</h4><p>An ALB has three building blocks: Listeners, Listener Rules, and Target Groups.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HwaKC1zLKHCAmSgqrmLn-A.png" /></figure><h4><strong>Listeners</strong></h4><p>The entry point to an ALB. It accepts incoming connections on a specific protocol and port, then uses listener rules to decide how to handle requests.<br>ALB supports <strong>two listener protocols</strong>:</p><ul><li><strong>HTTP (Port 80):</strong> Accepts unencrypted HTTP requests.</li><li><strong>HTTPS (Port 443):</strong> Accepts encrypted requests and terminates TLS using an SSL/TLS certificate, typically managed through AWS Certificate Manager (ACM).</li></ul><p>An ALB can have multiple listeners, each with its own rules. Every listener requires a <strong>default action</strong>, which is executed when no higher-priority rule matches.</p><p>HTTPS listeners also require a TLS security policy that determines supported TLS versions and ciphers. ALB supports multiple certificates using <strong>Server Name Indication (SNI)</strong>, allowing a single listener to serve multiple domains.</p><p><strong>Why Do We Need Both Port 80 and 443?<br>HTTP:80 → </strong>Redirect incoming HTTP requests to HTTPS using a 301 permanent redirect<br><strong>HTTPS :443 → </strong>Securely process requests and forward them to the appropriate target groups</p><p><strong>Forward vs Redirect</strong></p><ul><li><strong>Forward:</strong> The ALB passes the request to a target group. The browser doesn’t know which backend answered, and the URL stays the same.</li><li><strong>Redirect:</strong> The ALB doesn’t call a backend at all. It replies to the browser with a 301 or 302 status and a new URL, and the browser makes a fresh request to that URL.</li></ul><h4><strong>Listener Rules</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3UvnoE5asBc6TpdQipw5QQ.png" /></figure><h4><strong>Target Groups</strong></h4><p>A target group is a collection of backend targets that receive requests forwarded by an ALB listener rule. In a microservices architecture, each service typically gets its own target group.</p><p>A target group defines four things:</p><ul><li><strong>Targets:</strong> which instances, IPs, or functions receive traffic</li><li><strong>Protocol and port:</strong> how the ALB talks to the backend</li><li><strong>Health checks:</strong> how the ALB decides whether a target is healthy</li><li><strong>Load balancing:</strong> how requests are spread among healthy targets</li></ul><p><strong>Target types</strong></p><ul><li><strong>Instance:</strong> EC2 instances registered by instance ID. Common with EC2 Auto Scaling.</li><li><strong>IP:</strong> targets registered by private IP address. Common for ECS Fargate tasks, EKS pods, and servers reachable over VPN or Direct Connect.</li><li><strong>Lambda:</strong> an AWS Lambda function that the ALB invokes to handle the request.</li></ul><p>The target type is chosen when you create the target group and cannot be changed afterward.</p><p><strong>Protocol and port<br></strong>For instance and IP target groups, the ALB forwards traffic over HTTP or HTTPS to a configured port. A Spring Boot application, for example, might listen on 8080.</p><pre>Browser<br>   |<br>   | HTTPS :443<br>   v<br>AWS ALB<br>   |<br>   | HTTP :8080<br>   | HTTP because it is private VPC if you want you also use HTTPS<br>   v<br>Target Group (users-tg)<br>   |<br>   +---- Spring Boot Instance 1<br>   |<br>   +---- Spring Boot Instance 2</pre><p>Lambda targets have no port or protocol setting, because the ALB invokes the function directly.</p><p>Two practical points:</p><ul><li><strong>Security groups:</strong> the targets’ security group must allow inbound traffic from the ALB’s security group on the target port, or health checks will fail.</li><li><strong>Path is forwarded unchanged:</strong> a request to /users/123 reaches your app as /users/123.</li></ul><p><strong>How targets are registered</strong></p><ul><li><strong>Manual:</strong> register an EC2 instance or IP address directly.</li><li><strong>EC2 Auto Scaling:</strong> registers and deregisters instances as capacity changes.</li><li><strong>Amazon ECS:</strong> registers running tasks automatically when the service is linked to the target group.</li><li><strong>Amazon EKS:</strong> the AWS Load Balancer Controller registers pods.</li></ul><h4>Health Checks</h4><p>A health check is how the ALB decides whether a target can receive traffic. The ALB sends a request to each target on a schedule. Targets that respond correctly receive traffic, and targets that don’t are skipped until they recover. Each target group has its own health check settings.</p><p><strong>Health check settings<br></strong>When you configure a target group, you will see these fields:</p><ul><li><strong>Protocol:</strong> HTTP or HTTPS, used for the check.</li><li><strong>Path:</strong> the URL the ALB calls, for example /actuator/health. The default is /.</li><li><strong>Port:</strong> either <strong>Traffic port</strong> (the same port the target receives requests on) or an <strong>Override</strong> port, such as a separate management port.</li><li><strong>Interval:</strong> how often the ALB checks each target. Default is 30 seconds.</li><li><strong>Timeout:</strong> how long the ALB waits for a response before counting the check as failed. Default is 5 seconds.</li><li><strong>Healthy threshold:</strong> how many consecutive successful checks make a target healthy. Default is 5.</li><li><strong>Unhealthy threshold:</strong> how many consecutive failed checks make a target unhealthy. Default is 2.</li><li><strong>Success codes:</strong> the HTTP status codes that count as a pass. Default is 200, and you can use a list (200,204) or a range (200-299).</li></ul><p><strong>Target states:</strong></p><ul><li><strong>initial:</strong> the target was just registered and is being checked.</li><li><strong>healthy:</strong> passing checks and receiving traffic.</li><li><strong>unhealthy:</strong> failing checks and receiving no new requests.</li><li><strong>draining:</strong> being removed and finishing in-flight requests.</li></ul><h4>Load Balancing Algorithms</h4><p>After health checks remove the unhealthy targets, the ALB needs a rule for picking one of the healthy ones. That rule is the <strong>load balancing algorithm</strong>, and you set it per target group.</p><ul><li><strong>Round robin(default):</strong> takes turns and ignores how busy each target is.</li><li><strong>Least outstanding requests:</strong> picks the target that is <strong>least busy right now</strong>.</li><li><strong>Weighted random:</strong> picks randomly, but <strong>automatically sends less traffic to a target that looks sick</strong>.</li></ul><p><strong>Which Algorithm Fits?<br></strong>Imagine an order-service running on three instances: A, B, and C.<br><strong>Round robin: all requests are quick and similar<br></strong>Every request is quick GET /orders/123. The ALB takes turns: A, B, C, A, B, C. Everyone gets an equal share.</p><p><strong>Least outstanding requests: some requests are slow<br></strong>Instance A is busy with three slow report exports, while C is idle. A new request arrives, and the ALB sends it to C, the least busy instance, instead of piling more work on A.</p><p><strong>Weighted random: one instance is quietly failing<br></strong>Instance B’s health check still returns 200, but real requests to it are slow or failing. The ALB notices and automatically sends B less traffic until it recovers.</p><p><strong>Anomaly Mitigation<br></strong>Health checks have a blind spot. An instance can pass its health check but still fail real user requests. For example, /actuator/health returns 200, but calls that need a slow database connection return errors.</p><p><strong>Anomaly mitigation</strong> closes that gap. It is a target group feature that works with the <strong>weighted random</strong> algorithm. The ALB watches real traffic and handles a misbehaving target in three steps:</p><ol><li><strong>Detect:</strong> the ALB compares each target with the others and notices one that returns more errors or connection failures.</li><li><strong>Reduce:</strong> it sends that target less traffic, but keeps it registered. It is not marked unhealthy.</li><li><strong>Recover:</strong> when the target behaves normally again, its share of traffic goes back to normal.</li></ol><p><strong>Two Related Features: Stickiness and Weighted Target Groups<br></strong>These work alongside the algorithm rather than replacing it.</p><p><strong>Stickiness<br></strong>Imagine the order-service runs on instances A, B, and C. A user logs in, and instance A saves their session in its own memory. Their next request goes to B, which has never seen this user, so it asks them to log in again.</p><pre>Without stickiness:<br>Login    → A  (session saved in A&#39;s memory)<br>Next req → B  (B doesn&#39;t know the user → &quot;please log in&quot;)<br><br>With stickiness:<br>Login    → A  (ALB gives the browser a cookie)<br>Next req → A  (cookie says &quot;send me to A&quot;)<br>Next req → A</pre><p>With stickiness enabled, the ALB sets a cookie in the browser and uses it to send the user back to the same instance.</p><p><strong>The downside:</strong> a few heavy users can get stuck on one instance while others sit idle. If that instance restarts, those users lose their sessions anyway.</p><p><strong>The better fix:</strong> store sessions in Redis or a database so any instance can serve any user, and use stickiness only when you can’t change the app.</p><p><strong>Weighted target groups<br></strong>Say orders-v1 is running in production and you have built orders-v2. Switching everyone at once is risky, because a bug would affect all users.</p><p>Instead, create one target group per version and let the listener rule split the traffic:</p><pre>Rule: Path = /orders/*  → forward<br><br>   90%  → orders-v1-tg   (current version)<br>   10%  → orders-v2-tg   (new version)</pre><p>Only about 1 in 10 requests reaches v2. If v2 looks healthy, move to 50/50 and then 100%. If it has a problem, you can shift back to 100% v1 in seconds, and only a small share of users is affected. This is called a <strong>canary release</strong>.</p><p>Weighted target groups are configured in the listener rule, not on the target group itself.</p><p><strong>How they differ</strong></p><ul><li><strong>Stickiness</strong> decides which <em>instance</em> a returning user goes to.</li><li><strong>Weighted target groups</strong> decide which <em>version</em> a request goes to.</li></ul><p>They can be combined. For example, send 10% of users to v2 and use stickiness to keep each of them on v2, so they don’t switch between versions mid-session.</p><h3>Conclusion</h3><p>AWS Application Load Balancer (ALB) simplifies how we manage incoming traffic in modern applications. Instead of maintaining separate load balancers or custom routing infrastructure, ALB provides HTTP routing, load balancing, health checks, and HTTPS termination in a fully managed service.</p><p>By combining <strong>listeners, listener rules, and target groups</strong>, ALB makes it easier to route requests to the right microservice and distribute traffic across healthy application instances.</p><p>Features such as <strong>multi-AZ availability, stickiness, and weighted routing</strong> further help improve application reliability and support safer deployments.</p><p>Whether you’re running Spring Boot microservices on EC2 or ECS Fargate, understanding ALB is an important step toward designing scalable and highly available applications on AWS.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e26cb3775b8c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CloudFront for Full-Stack Developers: Serving React and Spring Boot Faster with a CDN]]></title>
            <link>https://medium.com/@yramcharanteja/cloudfront-for-full-stack-developers-serving-react-and-spring-boot-faster-with-a-cdn-65cfe92617b6?source=rss-e072c7cbc844------2</link>
            <guid isPermaLink="false">https://medium.com/p/65cfe92617b6</guid>
            <category><![CDATA[aws-cloudfront]]></category>
            <category><![CDATA[cloudfront]]></category>
            <category><![CDATA[cdn]]></category>
            <dc:creator><![CDATA[CodeCraft by Ramcharan]]></dc:creator>
            <pubDate>Sun, 18 Oct 2026 23:05:34 GMT</pubDate>
            <atom:updated>2026-10-19T01:10:17.752Z</atom:updated>
            <content:encoded><![CDATA[<p>What a CDN is, how CloudFront works, and how to put it in front of S3 and ECS Fargate, with a hands-on lab.</p><p>When we build a full-stack application, most of our time goes into the frontend, backend APIs, database, and deployment.</p><p>Let’s take a simple example. We have a React app, a Spring Boot backend, and a PostgreSQL database. The React build is hosted on Amazon S3. The Spring Boot services run on ECS Fargate behind an Application Load Balancer.</p><p>Everything works fine.</p><p>But what happens when users from different countries start using our app? And do thousands of users really need to download the same JavaScript file from the same place, again and again?</p><p>This is where a Content Delivery Network (CDN) helps.</p><p>In this article, we will learn what a CDN is, how Amazon CloudFront works, and how it fits into a React and Spring Boot application on AWS. We will also try it hands-on and watch a cache miss turn into a cache hit.</p><h4>How a Web Page Reaches the Browser</h4><p>Before we talk about CDNs, let’s understand what happens when someone opens a website. If this part is clear, everything else in the article will make sense.</p><p><strong>What happens when you type a URL in Chrome<br></strong>Let’s say a user types www.example.com and presses Enter.</p><pre>1. DNS lookup    -&gt; Browser asks: What is the IP address of www.example.com?<br>2. Connection    -&gt; Browser connects to that server (TCP first, then TLS for HTTPS)<br>3. HTTP request  -&gt; Browser asks: GET /index.html<br>4. HTTP response -&gt; Server sends back index.html<br>5. More requests -&gt; Browser reads the HTML and asks for main.js, styles.css, logo.png<br>6. Rendering     -&gt; Browser runs the JavaScript and shows the page</pre><p>The important point is that the browser does not get the whole website in one shot. It first gets an HTML file, and that file tells it which other files to download.</p><p><strong>The traditional way: a web server<br></strong>Years ago, websites were served from a <strong>web server</strong>, a machine running software like Apache, Nginx, or Tomcat. The team would rent or buy a server, install the software, copy the HTML, CSS, and JS files onto it, and keep it running.</p><pre>Browser -&gt; Web Server (Apache / Nginx / Tomcat) -&gt; HTML, CSS, JS files</pre><p>In many applications, the server also built the page. When a user requested a page, the server (running Java with JSP, PHP, and so on) fetched data from the database, created the full HTML, and sent it to the browser. Every page view meant work for the server.</p><p>This approach had some problems:</p><ul><li>We had to manage servers: patching, monitoring, and restarting them.</li><li>We had to plan capacity. A traffic spike could slow down or crash the server, so we often paid for a bigger server just to survive peak traffic.</li><li>One server in one location meant slow responses for faraway users.</li><li>We paid for the server even when nobody was using the site.</li></ul><p><strong>How React changed this<br></strong>With React (and Angular), the model is different. These are <strong>Single Page Applications (SPAs)</strong>.</p><p>When we run the production build (npm run build), we get a folder of plain files:</p><pre>build/<br>  index.html<br>  static/js/main.8f3a2c.js<br>  static/css/main.5d1e9b.css<br>  static/media/logo.png</pre><p>These files are <strong>static</strong>. They are the same for every user, and no server needs to create them on each request. The browser downloads the JavaScript, runs it, and React builds the page on the user&#39;s device. When it needs data, it calls our Spring Boot APIs.</p><p>So the work is split cleanly:</p><pre>React files (HTML, JS, CSS)  -&gt; only need to be stored and delivered<br>Spring Boot APIs             -&gt; run business logic and talk to the database</pre><p><em>Note: this applies to SPAs. Frameworks that render pages on the server, such as Next.js with SSR, still need a running server.</em></p><p><strong>Why we put React in Amazon S3<br></strong>Since the React build is just a set of files, we do not need a server to run it. We only need a place to store the files and deliver them over HTTP. That is exactly what Amazon S3 does.</p><p>S3 is a good fit because:</p><ul><li><strong>No servers to manage.</strong> We upload the files, and we are done.</li><li><strong>Scales automatically.</strong> It handles a few users or millions.</li><li><strong>Cheap.</strong> We pay for storage and requests, not for an idle machine.</li><li><strong>Durable.</strong> Files are stored safely across multiple Availability Zones.</li></ul><p>So the setup looks like this:</p><pre>Browser -&gt; S3 (React files)<br>Browser -&gt; ALB -&gt; Spring Boot on Fargate -&gt; PostgreSQL (APIs and data)</pre><p>This works, but in production we should not expose S3 directly to users. We will fix that shortly.</p><h4>Why Do We Need a CDN?</h4><p>Let’s say our application runs in AWS us-east-1 Region (Northern Virginia):</p><ul><li>React frontend on Amazon S3</li><li>Spring Boot APIs on ECS Fargate behind an Application Load Balancer</li><li>PostgreSQL on Amazon RDS (it sits behind the backend, so a CDN is not part of its story)</li></ul><p>Now imagine three users opening our website: one in Virginia, one in London, and one in Hyderabad. Without a CDN, every request goes to us-east-1, both for files like main.js and styles.css and for API calls.</p><p><strong>Problem 1: Distance<br></strong>The farther the user is from our server, the longer each request takes. This delay is called <strong>latency</strong>. A round trip to us-east-1 takes roughly 10 ms from Virginia, 80 ms from London, and 200 ms or more from Hyderabad (approximate values; they change with the network). Before a file even starts downloading, the browser also needs a DNS lookup, a TCP handshake, and a TLS handshake. Each one costs at least one round trip, so the delay adds up fast for faraway users.</p><p><strong>Problem 2: Repetition<br></strong>If 50,000 users open our app, all of them download the same main.js and styles.css from the same S3 bucket in Virginia. We pay for every request and every byte, even though the content is identical.</p><p>So why should every user fetch the same file from one faraway place, when it could be served from somewhere close to them? That is the problem a CDN solves.</p><h4>What Is a CDN?</h4><p>A Content Delivery Network (CDN) is a network of servers spread across many locations around the world. Instead of every user going to one origin server, a CDN keeps copies of our content closer to them.</p><p>These locations are called <strong>edge locations</strong> (or Points of Presence, PoPs). The server where the original content lives, such as our S3 bucket in Virginia, is called the <strong>origin</strong>.</p><p>Let’s take a simple example. A user in Hyderabad requests /assets/logo.png.</p><p>Without a CDN, the request travels all the way to Virginia and back:</p><pre>User (Hyderabad) → Origin (Virginia) → User</pre><p>With a CDN, the request first goes to a nearby edge location:</p><pre>User (Hyderabad) → Nearby Edge Location<br>                        |<br>              Is the image cached?<br>                 |            |<br>                Yes           No<br>                 |            |<br>          Return image    Fetch from origin,<br>          directly        store a copy, return it</pre><p>This gives us two important terms:</p><ul><li><strong>Cache hit:</strong> the edge already has the content and returns it immediately.</li><li><strong>Cache miss:</strong> the edge does not have it, so it fetches it from the origin first.</li></ul><p>Only the first user at each edge location pays the cost of a miss. The next users nearby get a hit. This is how a CDN solves both problems: distance becomes shorter, and the origin is asked far less often.</p><p>CDNs work best for static files like images, JavaScript, CSS, fonts, and downloads. They can also sit in front of dynamic requests such as backend APIs, as we will see.</p><h4>What Is Amazon CloudFront?</h4><p>Amazon CloudFront is the CDN service from AWS. It uses AWS’s global network of edge locations to deliver websites, APIs, and other web content.</p><p>CloudFront sits between our users and our application. It does not replace S3 or our Spring Boot services. It is an extra layer in front of them.</p><pre>             Users<br>                |<br>                v<br>           CloudFront<br>                |<br>          Is it cached?<br>           /          \<br>         Yes           No<br>          |             |<br>    Return from      Fetch from origin<br>      cache          (S3 or ALB)</pre><p>To understand how CloudFront works, we need to know four things.</p><p><strong>Origin: </strong>An origin is where CloudFront gets the content from. It can be S3, an Application Load Balancer, API Gateway, or any web server.</p><p>In our application, we use two origins:</p><ul><li><strong>Amazon S3:</strong> stores the React build</li><li><strong>Application Load Balancer:</strong> routes requests to the Spring Boot services</li></ul><p><strong>Edge Location: </strong>An edge location is a CloudFront server close to the user. When a request comes in, CloudFront sends it to a nearby edge location. If the content is cached there, it is returned right away. If not, CloudFront fetches it from the origin.</p><p><strong>Cache Behavior: </strong>A cache behavior tells CloudFront what to do for a given URL pattern.</p><p>For example:</p><ol><li>/api/* → Origin is ALB and caching is disabled.</li><li>/static/* → Origin is S3 and longer cache time.</li><li>Default(*) →Origin is S3 and shorter cache time for index.html</li></ol><p>CloudFront checks the patterns, picks the most specific match, and uses the default behavior when nothing else matches. This is how one distribution can serve both the frontend and the backend APIs.</p><p><strong>Distribution: </strong>It is the CloudFront configuration for our application. It decides which origins to use, how requests are routed, what to cache, and which security settings to apply. It is only configuration. It does not store our app, and it is global, so we do not pick a Region for it.</p><p>When we create one, AWS gives us a domain name like this:</p><pre>d123example.cloudfront.net</pre><p>This is the address of the distribution, not of our application. Our S3 bucket and ALB keep their own addresses.</p><p><strong>Using our own domain<br></strong>Users should not have to type d123example.cloudfront.net. To usewww.example.com, we do three things once:</p><ol><li>Add www.example.com to the distribution as an alternate domain name.</li><li>Request a certificate for it in AWS Certificate Manager (ACM) and attach it. For CloudFront, the certificate must be created in us-east-1.</li><li>Create a DNS record (a Route 53 alias, or a CNAME in other DNS providers) that points www.example.com to the distribution.</li></ol><p>Now, when a user opens www.example.comDNS returns the address of a CloudFront edge location near them. A user in Hyderabad and a user in London get different answers for the same domain. That is how the nearby edge is chosen. The user only sees <a href="http://www.example.com./">www.example.com</a> .</p><h4>How a Request Flows Through CloudFront</h4><p>Let’s follow a real user journey: a login page, then a profile page.</p><pre>Step 1: User opens www.example.com/login<br>   Browser -&gt; CloudFront -&gt; (hit: cache / miss: S3) -&gt; index.html, JS, CSS<br>Step 2: User enters credentials and clicks Login<br>   Browser -&gt; CloudFront -&gt; ALB -&gt; Spring Boot -&gt; PostgreSQL<br>   POST /api/auth/login -&gt; returns a token or session cookie<br>Step 3: React shows the /profile page<br>   Done inside the browser. No request to S3 for the page.<br>Step 4: Profile component loads its data<br>   Browser -&gt; CloudFront -&gt; ALB -&gt; Spring Boot -&gt; PostgreSQL<br>   GET /api/profile (with token) -&gt; returns profile JSON<br>Step 5: React builds the profile page using that JSON</pre><p>A few things to notice.</p><p><strong>The page is built in the browser.</strong> The JavaScript downloaded in step 1 already contains the code for every page. After login, React Router just swaps the Login component for the Profile component. S3 is asked again only when the user refreshes, opens /profile directly, or when the app loads extra JS chunks on demand.</p><p><strong>Static files and API calls use the same domain but different origins.</strong> The URL pattern decides which one: /api/* goes to the ALB; everything else goes to S3.</p><p><strong>API responses are not cached.</strong> POST Requests are never cached. And GET /api/profile returns data for one specific user, so caching it could show one user&#39;s profile to another. That is why the /api/* behavior has caching disabled and forwards the Authorization header or cookie to the backend.</p><h4>Caching Rules That Matter</h4><p>Caching is where most of the benefit comes from, and also where most mistakes happen.</p><p><strong>Cache policy.</strong> A cache policy defines what makes two requests the same (headers, cookies, query strings) and how long to keep the response. If we forward too many headers or cookies, every request looks different and the hit ratio drops close to zero. Forward only what the origin really needs.</p><p><strong>TTL (time to live).</strong> This is how long CloudFront keeps a copy.</p><p><strong>Invalidation.</strong> After a deployment, index.html may still be cached at the edge. We can tell CloudFront to drop it.</p><h4>Keeping the Origins Private</h4><p>If users can reach S3 or the ALB directly, they skip CloudFront and lose caching and protection. So we lock both origins.</p><ul><li><strong>S3:</strong> keep the bucket private and use <strong>Origin Access Control (OAC)</strong>. Only our CloudFront distribution can read from it.</li><li><strong>ALB:</strong> allow incoming traffic only from CloudFront, for example by using the CloudFront managed prefix list in the ALB security group.</li></ul><p>One Spring Boot detail: since the app now runs behind proxies, set server.forward-headers-strategy=framework so it reads the X-Forwarded-* headers correctly.</p><h4>Hands-On: Try It Yourself</h4><p>This takes about two to three hours in the AWS console.</p><ol><li><strong>Host the static site.</strong> Build your React or Angular app, upload the build folder to a private S3 bucket, and create a CloudFront distribution with OAC. Open the *.cloudfront.net URL.</li><li><strong>Watch the cache.</strong> Request a JS file twice: <br>curl -I <a href="https://d123example.cloudfront.net/static/js/main.8f3a2c.js">https://d123example.cloudfront.net/static/js/main.8f3a2c.js</a></li><li>The first response shows X-Cache: Miss from cloudfront. The second shows X-Cache: Hit from cloudfront and an Age header.</li><li><strong>Break and fix routing.</strong> Refresh on/profile, see the 403, then add the custom error response (403 and 404 to/index.html, status 200).</li><li><strong>Deploy a change.</strong> Upload a new build withaws s3 sync, notice the staleindex.html, then invalidate /index.html.</li><li><strong>Add the API.</strong> Add your ALB as a second origin and create a /api/* behavior with the CachingDisabled cache policy, the AllViewerExceptHostHeader origin request policy, and all HTTP methods allowed.</li><li><strong>Try API caching.</strong> Add a Spring Boot GET endpoint that returnsCache-Control: max-age=60, use a cache policy that respects origin headers, and watch Miss turn into Hit.</li><li><strong>Clean up.</strong> Disable and delete the distribution and empty the bucket to avoid charges.</li></ol><h4>Common Mistakes</h4><ul><li><strong>403 on page refresh:</strong> missing the custom error response.</li><li><strong>Old UI after deployment:</strong> index.html was cached and not invalidated.</li><li><strong>No cache hits:</strong> too many headers or cookies are forwarded.</li><li><strong>User data cached by accident:</strong> an authenticated API response was cached.</li><li><strong>Certificate not found:</strong> the ACM certificate was created outside us-east-1.</li><li><strong>Users bypass the CDN:</strong> S3 or the ALB is still publicly reachable.</li></ul><h4>Real-World Scenarios: Redirects and Routing at the Edge</h4><p>Sometimes we want CloudFront to decide where a request goes. For example, we may move users from an old page to a new one, or show a new Dashboard to only some users. There are two ways to do this.</p><p><strong>Redirect vs rewrite<br> → External routing (redirect):</strong> CloudFront tells the browser to go to a new URL. The user sees the address bar change.<br> → <strong>Internal routing (rewrite):</strong> CloudFront quietly fetches a different page. The address bar stays the same.</p><pre>Redirect:  /old-profile -&gt; browser is told to go to /profile<br>Rewrite:   /dashboard   -&gt; CloudFront fetches /v2/dashboard, user still sees /dashboard</pre><p><strong>Who does the routing<br></strong>Simple routing needs no code. A cache behavior such as /api/* going to the ALB is enough. For anything with conditions, like checking a cookie, we attach a small piece of code to CloudFront:</p><ul><li><strong>CloudFront Function:</strong> very small and fast JavaScript. Good for simple redirects and cookie checks.</li><li><strong>Lambda@Edge:</strong> a full Lambda function running at the edge. Good for complex logic.</li></ul><p>The 4 places where code can run</p><p>Code can be attached at four points in the life of a request:</p><pre>User -&gt; [1 Viewer request] -&gt; CloudFront cache -&gt; [2 Origin request] -&gt; Origin (S3 / ALB)<br>User &lt;- [4 Viewer response] &lt;- CloudFront cache &lt;- [3 Origin response] &lt;- Origin</pre><ol><li><strong>Viewer request:</strong> runs on every request, before the cache. Good for redirects and rewrites.</li><li><strong>Origin request:</strong> runs only on a cache miss, just before going to S3 or the ALB. Good for changing the origin.</li><li><strong>Origin response:</strong> runs when the origin replies, before the response is cached.</li><li><strong>Viewer response:</strong> runs just before the response goes back to the user. Good for adding headers.</li></ol><p>The difference between the two options is simple:</p><ul><li><strong>Lambda@Edge</strong> can run at <strong>all 4</strong> places.</li><li><strong>CloudFront Function</strong> can run at only <strong>2</strong> places: viewer request (1) and viewer response (4).</li></ul><p>So if we need to change the origin, which happens at the origin request, we must use Lambda@Edge.</p><p><strong>CloudFront Function example</strong><br>This function runs at the viewer request. It redirects an old URL to a new one:</p><pre>function handler(event) {<br>  var request = event.request;<br><br>  if (request.uri === &#39;/old-profile&#39;) {<br>    return {<br>      statusCode: 301,<br>      statusDescription: &#39;Moved Permanently&#39;,<br>      headers: { location: { value: &#39;/profile&#39; } }<br>    };<br>  }<br>  return request;   // no match: let the request continue<br>}</pre><p>If the path is /old-profile, CloudFront answers the browser right away from the edge. Otherwise, the request continues as normal.</p><p><strong>Lambda@Edge example<br></strong>This function runs at the origin request. Users with the beta cookie are sent to the new S3 bucket, and everyone else stays on the old one:</p><pre>exports.handler = async (event) =&gt; {<br>  const request = event.Records[0].cf.request;<br>  const cookie = request.headers.cookie ? request.headers.cookie[0].value : &#39;&#39;;<br><br>  if (request.uri.startsWith(&#39;/dashboard&#39;) &amp;&amp; cookie.includes(&#39;dashboard=on&#39;)) {<br>    const newBucket = &#39;new-ui-bucket.s3.amazonaws.com&#39;;<br><br>    // Change the origin to the new bucket<br>    request.origin = {<br>      s3: {<br>        domainName: newBucket,<br>        region: &#39;us-east-1&#39;,<br>        authMethod: &#39;origin-access-identity&#39;,<br>        path: &#39;&#39;,<br>        customHeaders: {}<br>      }<br>    };<br>    request.headers[&#39;host&#39;] = [{ key: &#39;host&#39;, value: newBucket }];<br>  }<br>  return request;     // no match: continue to the original origin<br>};</pre><p>A Lambda@Edge function is created in the us-east-1 Region, and AWS then copies it to the edge locations. Because the origin request runs only on a cache miss, the cookie must be part of the cache key. Otherwise, a user may get the other version&#39;s cached page.</p><p><strong>Real project example: rules in a JSON file<br></strong>In many projects, the rules are kept in a JSON file, and one routing Lambda reads it. CloudFront does not read the file itself. It only runs the Lambda, and the Lambda applies the rules. Here is a simplified example:</p><pre>{<br>  // Placeholders: ${HOST_NAME} is replaced with the real value before rules run<br>  &quot;replacementVariable&quot;: [<br>    { &quot;variableName&quot;: &quot;HOST_NAME&quot;, &quot;replacement&quot;: &quot;www.example.com&quot; }<br>  ],<br><br>  // INTERNAL routing: the user&#39;s URL stays the same<br>  &quot;rewriteRules&quot;: [<br>    {<br>      // Scenario 1: beta users get the new Dashboard<br>      // (the backend sets the cookie for about 10% of users)<br>      &quot;description&quot;: &quot;New Dashboard for beta users&quot;,<br>      &quot;andConditions&quot;: [                         // ALL conditions must match<br>        { &quot;testString&quot;: &quot;$URI&quot;,    &quot;pattern&quot;: &quot;^/dashboard(.*)&quot; },<br>        { &quot;testString&quot;: &quot;$COOKIE&quot;, &quot;pattern&quot;: &quot;dashboard=on&quot; }<br>      ],<br>      &quot;targetUri&quot;: &quot;/v2/dashboard${1}&quot;           // ${1} = the part captured by (.*)<br>    },<br>    {<br>      // Scenario 2: move a page to the new app for everyone (no cookie needed)<br>      &quot;description&quot;: &quot;Settings page moved to the new app&quot;,<br>      &quot;andConditions&quot;: [<br>        { &quot;testString&quot;: &quot;$URI&quot;, &quot;pattern&quot;: &quot;^/settings(.*)&quot; }<br>      ],<br>      &quot;targetUri&quot;: &quot;/v2/settings${1}&quot;<br>    },<br>    {<br>      // Scenario 3: serve some files from a different S3 bucket (change the origin)<br>      // Changing the origin needs the Lambda to run on the origin request<br>      &quot;description&quot;: &quot;Images from the new bucket&quot;,<br>      &quot;andConditions&quot;: [<br>        { &quot;testString&quot;: &quot;$URI&quot;, &quot;pattern&quot;: &quot;^/images/(.*)&quot; }<br>      ],<br>      &quot;targetUri&quot;: &quot;/images/${1}&quot;,<br>      &quot;originTarget&quot;: { &quot;domainName&quot;: &quot;new-ui-bucket.s3.amazonaws.com&quot; }<br>    }<br>  ],<br><br>  // EXTERNAL routing: the browser is sent to a new URL<br>  &quot;redirectRules&quot;: [<br>    {<br>      // Scenario 4: temporary redirect (use 302 while testing)<br>      &quot;description&quot;: &quot;Old Dashboard URL to new URL&quot;,<br>      &quot;andConditions&quot;: [<br>        { &quot;testString&quot;: &quot;$URI&quot;, &quot;pattern&quot;: &quot;^/old-dashboard&quot; }<br>      ],<br>      &quot;redirectUrl&quot;: &quot;https://${HOST_NAME}/dashboard&quot;,<br>      &quot;redirectHttpStatus&quot;: 302<br>    },<br>    {<br>      // Scenario 5: permanent redirect (301 is cached by browsers, use when sure)<br>      &quot;description&quot;: &quot;Old Profile page moved for good&quot;,<br>      &quot;andConditions&quot;: [<br>        { &quot;testString&quot;: &quot;$URI&quot;, &quot;pattern&quot;: &quot;^/old-profile&quot; }<br>      ],<br>      &quot;redirectUrl&quot;: &quot;https://${HOST_NAME}/profile&quot;,<br>      &quot;redirectHttpStatus&quot;: 301<br>    },<br>    {<br>      // Scenario 6: ANY one condition is enough (orConditions)<br>      &quot;description&quot;: &quot;Two old URLs, one new page&quot;,<br>      &quot;orConditions&quot;: [<br>        { &quot;testString&quot;: &quot;$URI&quot;, &quot;pattern&quot;: &quot;^/home-old&quot; },<br>        { &quot;testString&quot;: &quot;$URI&quot;, &quot;pattern&quot;: &quot;^/start&quot; }<br>      ],<br>      &quot;redirectUrl&quot;: &quot;https://${HOST_NAME}/&quot;,<br>      &quot;redirectHttpStatus&quot;: 302<br>    },<br>    {<br>      // Scenario 7: send example.com to www.example.com<br>      &quot;description&quot;: &quot;Non-www to www&quot;,<br>      &quot;andConditions&quot;: [<br>        { &quot;testString&quot;: &quot;$HOST&quot;, &quot;pattern&quot;: &quot;^example.com$&quot; }<br>      ],<br>      &quot;redirectUrl&quot;: &quot;https://${HOST_NAME}/&quot;,<br>      &quot;redirectHttpStatus&quot;: 301<br>    }<br>  ]<br>}</pre><p>The // comments are only for explanation. Plain JSON does not allow comments, so remove them in a real file or keep the explanation in the description field. The check names such as $URI, $COOKIE, and $HOST depend on how your project&#39;s Lambda is written.</p><p>Each rule has conditions. WithandConditions, all of them must match. WithorConditions, any one is enough. rewriteRules are internal routing, and redirectRules are external routing. For each request, the Lambda checks the rules like this:</p><pre>/dashboard with cookie dashboard=on -&gt; rewrite  -&gt; new Dashboard, URL stays the same<br>/settings                           -&gt; rewrite  -&gt; new app for everyone, URL stays the same<br>/images/logo.png                    -&gt; rewrite  -&gt; served from the new S3 bucket<br>/old-dashboard                      -&gt; redirect -&gt; browser goes to /dashboard (302)<br>/old-profile                        -&gt; redirect -&gt; browser goes to /profile (301)<br>/home-old or /start                 -&gt; redirect -&gt; browser goes to /<br>example.com                         -&gt; redirect -&gt; browser goes to www.example.com<br>Anything else                       -&gt; continues unchanged</pre><p>The big advantage is that adding a new route means editing the JSON, not the code.</p><p><strong>Two tips</strong></p><ul><li>Use 302 while testing. Browsers remember a 301 for a long time, so a mistake is hard to undo.</li><li>If routing depends on a cookie and the page is cached, the cookie must be part of the cache key. Otherwise, a user may get the other version&#39;s cached page.</li></ul><h4>Conclusion and What to Explore Next</h4><p>A React build is just static files, so S3 is a great place to store it. But S3 alone serves everyone from one Region. CloudFront adds a global layer in front: static files are cached near users, API calls travel through the same domain to Spring Boot, and the origins stay private.</p><p>Once this is clear, good next topics are AWS WAF, CloudFront Functions and Lambda@Edge, Origin Shield, signed URLs, and building the whole setup with Terraform or CDK.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65cfe92617b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing with DynamoDB: A Different Way to Think About Data]]></title>
            <link>https://medium.com/@yramcharanteja/designing-with-dynamodb-a-different-way-to-think-about-data-f3a4caf83ee6?source=rss-e072c7cbc844------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3a4caf83ee6</guid>
            <category><![CDATA[nosql-database]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[CodeCraft by Ramcharan]]></dc:creator>
            <pubDate>Tue, 11 Aug 2026 00:31:24 GMT</pubDate>
            <atom:updated>2026-08-11T00:31:24.270Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A Hands-On Guide to Access-Pattern-First Data Modeling — with a Spring Boot Walkthrough</em></p><blockquote>This article builds on “<a href="https://medium.com/@yramcharanteja/designing-with-mongodb-a-java-developers-guide-to-document-based-architecture-42912dcebf01">Designing with MongoDB: A Java Developer’s Guide to Document-Based Architecture</a>”. If you haven’t read it, start there — it covers why modern, API-driven applications outgrow table-first relational design.</blockquote><p>If you read my previous MongoDB article, you already know that modern applications are designed around how data is accessed, not just how it’s stored. DynamoDB takes this idea even further by encouraging you to model data based on your application’s access patterns. This approach is different from traditional databases but enables massive scalability with minimal operational overhead. In this article, we’ll explore the core concepts and design principles that make DynamoDB a popular choice for serverless applications on AWS.</p><p><strong>What’s different about DynamoDB is how far it pushes that philosophy.</strong> <br>Imagine a <strong>Books</strong> collection containing <strong>1 million documents</strong>. Most of your application retrieves books by <strong>author</strong>, so you’ve created an index on the <strong>author</strong> field.</p><p>Now a new requirement appears: <em>“Get me all books published in 2022.”</em></p><p>In MongoDB,<strong> </strong>it can still execute this query correctly, even though it wasn’t one of the primary query patterns you originally optimized for.</p><p>Without an index on <strong>publishYear</strong>, MongoDB must examine documents to find the matching results, which can be slow on a large collection. If this query becomes common, you create an index on <strong>publishYear</strong>. From that point on, MongoDB uses the new index to retrieve the matching documents efficiently, without requiring you to redesign your data model.</p><p><strong>In DynamoDB, </strong>now imagine the same dataset stored in DynamoDB, where <strong>Author</strong> is the <strong>Partition Key,</strong> and <strong>PublishDate</strong> is the <strong>Sort Key</strong>. Since <strong>PublishYear</strong> isn’t part of either key, DynamoDB has no direct path to the 2022 books.</p><p>It can still answer the query, but only by performing a <strong>Scan</strong> — reading all <strong>1 million</strong> items and returning only those published in 2022. Because DynamoDB charges for every item read, not just the matching results, a Scan becomes increasingly expensive and slower as the table grows.</p><p>If retrieving books by publication year becomes a common requirement, the correct solution is to create a <strong>Global Secondary Index (GSI)</strong> with <strong>PublishYear</strong> as its partition key. With the GSI in place, DynamoDB can jump directly to the matching books instead of scanning the entire table.</p><p><strong>Why Would AWS Design It This Way?<br></strong>At first, this may seem like a limitation compared to MongoDB. In reality, it’s a deliberate architectural trade-off. DynamoDB is designed to deliver <strong>predictable single-digit millisecond latency</strong> regardless of whether a table contains thousands or billions of items. It achieves that by ensuring efficient queries always use a <strong>Partition Key</strong>, <strong>Sort Key</strong>, or <strong>Global Secondary Index</strong> to locate data directly, rather than searching the entire dataset. Scans exist for occasional administrative or analytical tasks, but it isn’t intended to be the foundation of an application’s query patterns.</p><p><strong>The Key Difference</strong><br>Both MongoDB and DynamoDB can answer queries they weren’t originally optimized for. The difference is how they handle them.</p><p>With <strong>MongoDB</strong>, an unexpected query is usually a performance issue that you can solve later by adding an index.</p><p>With <strong>DynamoDB</strong>, an unexpected query is a data-modeling issue. Efficient queries must be planned around your application’s access patterns from the beginning. That’s the trade-off DynamoDB makes: you invest more thought in designing your keys and indexes up front, and in return, you get predictable performance that remains consistent as your application scales.</p><h4><strong>What Is DynamoDB, Exactly?</strong></h4><p>At its core, DynamoDB is AWS’s fully managed NoSQL database. It supports both key-value and document data models, but what really sets it apart isn’t the data model — it’s the way it expects you to design your application.</p><p>To achieve that goal, DynamoDB makes several architectural trade-offs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d_oN4EQDpIuW40R2QUIQDQ.png" /></figure><p>Rather than optimizing for maximum query flexibility, DynamoDB optimizes for <strong>predictability at scale</strong>. Features such as arbitrary filtering, join-like operations, and complex aggregations take a back seat to fast key-based lookups.</p><p>The result is a database that can scale from thousands to billions of items while maintaining consistent performance, making it a natural fit for <strong>serverless applications</strong>, <strong>high-throughput APIs</strong>, <strong>event-driven architectures</strong>, and workloads that demand predictable latency with minimal operational management.</p><h4>Core Concepts: Tables, Items, and Attributes</h4><p>At first glance, DynamoDB’s terminology looks familiar if you’ve worked with MongoDB, but the similarities are mostly at the vocabulary level.</p><ul><li><strong>Table</strong> → Similar to a MongoDB <strong>collection</strong>.</li><li><strong>Item</strong> → Similar to a <strong>document</strong>. Each item can be up to <strong>400 KB</strong> in size.</li><li><strong>Attribute</strong> → Similar to a field within a MongoDB document.</li></ul><pre>Table: Orders<br>Item:<br>{<br>  &quot;orderId&quot;: &quot;order_101&quot;,<br>  &quot;customerId&quot;: &quot;user_501&quot;,<br>  &quot;status&quot;: &quot;SHIPPED&quot;,<br>  &quot;totalAmount&quot;: 4597,<br>  &quot;items&quot;: [<br>    { <br>      &quot;productId&quot;: &quot;prod_2001&quot;, <br>      &quot;name&quot;: &quot;Wireless Headphones&quot;, <br>      &quot;price&quot;: 2999, <br>      &quot;quantity&quot;: 1 <br>    }<br>  ]<br>}</pre><p>Although the structure looks much like a MongoDB document, the difference lies in <strong>how DynamoDB stores and retrieves the data</strong>, which we’ll explore when we discuss primary keys and access patterns.</p><h3>Supported Data Types</h3><p>DynamoDB supports a smaller, fixed set of data types than MongoDB’s BSON:</p><ul><li><strong>Scalar:</strong> String (S), Number (N), Binary (B), Boolean (BOOL), and Null (NULL)</li><li><strong>Document:</strong> List (L) and Map (M) for nested arrays and objects</li><li><strong>Set:</strong> String Set (SS), Number Set (NS), and Binary Set (BS)—collections of unique values with no duplicates or guaranteed order</li></ul><p>For most applications, you’ll primarily work with <strong>String</strong>, <strong>Number</strong>, <strong>Map</strong>, and <strong>List</strong>, which cover most common use cases.</p><h4>The Primary Key: The Single Most Important Design Decision</h4><p>This is where DynamoDB diverges sharply from MongoDB’s _id. In MongoDB, _id uniquely identifies a document, but you can query other fields and add indexes as your application evolves. In DynamoDB, the primary key is the foundation of your data model—it determines how data is stored and how it can be queried efficiently.</p><p><strong>Simple Primary Key (Partition Key)<br></strong>A single attribute. DynamoDB hashes it to decide which physical partition stores the item. No two items can share the same partition key.</p><pre>Table: Users<br>Partition Key: userId</pre><p><strong>Composite Primary Key (Partition Key + Sort Key)<br></strong>Two attributes. Items with the same partition key are stored together, physically sorted by the sort key. This is how you model one-to-many relationships and enable range queries within a partition.</p><pre>Table: Orders<br>Partition Key: customerId<br>Sort Key: orderDate</pre><p><strong>A Few Design Rules</strong></p><ul><li><strong>Choose your primary key carefully.</strong> Unlike MongoDB, you can’t change it later. A poor choice usually means creating a new table and migrating your data.</li><li><strong>Use high-cardinality partition keys.</strong> Keys such as customerId or orderId distribute data evenly. Using a low-cardinality attribute like status would concentrate many requests on the same partition key, creating a <strong>hot partition</strong>.</li><li><strong>Watch for traffic hotspots.</strong> Even with a good partition key, one value may receive far more traffic than others. For example, if one tenant generates significantly more requests than everyone else, you can distribute the load using <strong>write sharding</strong>, with keys such as Acme#1, Acme#2, and Acme#3.</li></ul><h4>Capacity Modes: Pay-Per-Request vs Provisioned</h4><p>Unlike MongoDB, where you typically scale by resizing or adding database nodes, DynamoDB lets you choose <strong>how to manage read and write capacity</strong>.</p><ul><li><strong>On-Demand</strong>: You pay only for the read and write requests your application makes. There’s no capacity planning, making it ideal for unpredictable workloads, prototypes, and applications with spiky traffic.</li><li><strong>Provisioned</strong>: You specify how much read and write throughput your application needs using <strong>Read Capacity Units (RCUs)</strong> and <strong>Write Capacity Units (WCUs)</strong>. This is often more cost-effective for steady, predictable workloads, and you can enable auto scaling to adjust capacity as demand changes. If the provisioned capacity is too low, requests may be throttled until more capacity becomes available.</li></ul><h4>Secondary Indexes: GSI vs LSI</h4><p>DynamoDB can efficiently query data only through a table’s primary key. When your application needs additional lookup patterns, you use <strong>secondary indexes</strong>. Unlike MongoDB, where indexes are primarily a performance optimization, secondary indexes are often part of the initial data model in DynamoDB.</p><p>Suppose our <strong>Orders</strong> table is designed like this:</p><pre>Orders table  --&gt; PK: customerId SK: orderDate</pre><p><strong>Global Secondary Index (GSI)<br></strong>Now imagine customer support needs to look up an order by its <strong>orderId</strong> instead of by customer.</p><p>Since orderId isn&#39;t part of the primary key, we create a <strong>Global Secondary Index (GSI)</strong>:</p><pre>GSI: ByOrderId <br>PK: orderId</pre><p>A GSI creates another logical view of the same data using a different partition key, allowing DynamoDB to efficiently support a completely different access pattern. One of its biggest advantages is that it can be added <strong>after</strong> the table has been created.</p><p><strong>Local Secondary Index (LSI)<br></strong>Now suppose we still want to query a customer’s orders, but sort them by <strong>totalAmount</strong> instead of <strong>orderDate</strong>.</p><p>An <strong>LSI</strong> keeps the same partition key but uses a different sort key:</p><pre>LSI: ByAmount <br>PK: customerId <br>SK: totalAmount</pre><p>LSIs must be defined <strong>when the table is created</strong> and cannot be added later.</p><p><strong>Rule of Thumb: </strong>In practice, you’ll use <strong>GSIs</strong> far more often because they support entirely new access patterns and can be added as your application evolves. Use an <strong>LSI</strong> only when you know from the beginning that you’ll need multiple sort orders for items sharing the same partition key.</p><h4>The Architectural Shift (and Why It’s Bigger Than MongoDB’s)</h4><p>In the MongoDB article, we saw how the mindset evolves:</p><ul><li><strong>RDBMS asks:</strong> <em>How should I structure my tables?</em></li><li><strong>MongoDB asks:</strong> <em>How will my application access this data?</em></li></ul><p>DynamoDB takes it one step further:</p><blockquote><strong><em>What are all of my application’s access patterns before I design the table?</em></strong></blockquote><p>This is the mindset shift that catches many developers coming from SQL or MongoDB. In MongoDB, if a new query appears, you can often add an index and move on. In DynamoDB, an unplanned query may require a full table <strong>Scan</strong> or a new secondary index, making data modeling much more deliberate from the start.</p><p>Instead of designing your schema first, DynamoDB encourages you to follow a different sequence:</p><ol><li>Identify every access pattern your application needs.</li><li>Design the <strong>Partition Key</strong>, <strong>Sort Key</strong>, and any <strong>Global Secondary Indexes (GSIs)</strong> to support those access patterns.</li><li>Then build the application.</li></ol><p>Once you embrace this shift, DynamoDB becomes much easier to understand. You’re no longer designing tables — you are designing efficient paths to your data.</p><h4>Single-Table Design: DynamoDB’s Signature Pattern</h4><p>This is probably the biggest conceptual shift for developers coming from MongoDB. In MongoDB, you’d naturally create separate collections — <strong>Users</strong>, <strong>Orders</strong>, <strong>Products</strong>, and <strong>Reviews</strong> — that mirror your domain model.</p><p>In DynamoDB, a common best practice is <strong>single-table design</strong>, where multiple entity types share the same physical table and are distinguished by prefixed partition and sort keys. It may seem unusual at first, but it’s designed around one goal: keeping related data together so a single <strong>Query</strong> can retrieve everything needed for a common access pattern.</p><pre>Table: EcommerceTable<br>Partition Key: PK<br>Sort Key: SK<br><br>// Customer profile<br>{ &quot;PK&quot;: &quot;CUSTOMER#user_501&quot;, &quot;SK&quot;: &quot;PROFILE&quot;,<br>  &quot;name&quot;: &quot;Rahul Sharma&quot;, &quot;email&quot;: &quot;rahul@example.com&quot; }<br><br>// Customer&#39;s orders (same partition as the customer!)<br>{ &quot;PK&quot;: &quot;CUSTOMER#user_501&quot;, &quot;SK&quot;: &quot;ORDER#2026-02-12#order_101&quot;,<br>  &quot;status&quot;: &quot;SHIPPED&quot;, &quot;totalAmount&quot;: 4597 }<br><br>{ &quot;PK&quot;: &quot;CUSTOMER#user_501&quot;, &quot;SK&quot;: &quot;ORDER#2026-02-15#order_104&quot;,<br>  &quot;status&quot;: &quot;PROCESSING&quot;, &quot;totalAmount&quot;: 1299 }<br><br>// Order line items, snapshotted at purchase time (own partition)<br>{ &quot;PK&quot;: &quot;ORDER#order_101&quot;, &quot;SK&quot;: &quot;ITEM#prod_2001&quot;,<br>  &quot;name&quot;: &quot;Wireless Headphones&quot;, &quot;price&quot;: 2999, &quot;quantity&quot;: 1 }<br><br>{ &quot;PK&quot;: &quot;ORDER#order_101&quot;, &quot;SK&quot;: &quot;ITEM#prod_2002&quot;,<br>  &quot;name&quot;: &quot;Laptop Sleeve&quot;, &quot;price&quot;: 799, &quot;quantity&quot;: 2 }<br><br>// Product catalog entry<br>{ &quot;PK&quot;: &quot;PRODUCT#prod_2001&quot;, &quot;SK&quot;: &quot;METADATA&quot;,<br>  &quot;name&quot;: &quot;Wireless Headphones&quot;, &quot;currentPrice&quot;: 3299 }<br><br>// A review, referencing both user and product<br>{ &quot;PK&quot;: &quot;PRODUCT#prod_2001&quot;, &quot;SK&quot;: &quot;REVIEW#user_777&quot;,<br>  &quot;rating&quot;: 5, &quot;comment&quot;: &quot;Excellent sound quality!&quot; }</pre><p>Now a single <strong>Query</strong> on PK = CUSTOMER#user_501 returns the customer&#39;s profile and order history in one request. Instead of joining data after it&#39;s retrieved, DynamoDB encourages you to model data so related information is already stored together.</p><p><strong>When NOT to Use Single-Table Design<br></strong>Single-table design isn’t mandatory.</p><p>If your application is small or you’re just getting started with DynamoDB, using separate tables for <strong>Customers</strong>, <strong>Orders</strong>, and <strong>Products</strong> is often simpler and easier to maintain. As your application grows and your access patterns become clearer, you can decide whether the additional complexity of single-table design is justified.</p><p>It’s also not a good fit for reporting or analytical workloads. Queries such as <strong>“<em>What’s the total revenue this month?</em>”</strong> are better handled by streaming data into an analytics platform rather than querying DynamoDB directly.</p><p><strong>The Snapshot Pattern<br></strong>Another common DynamoDB pattern is storing a <strong>snapshot</strong> of data at the time an event occurs.</p><p>Imagine a customer buys a pair of wireless headphones for <strong>$150</strong>. Six months later, the product price increases to <strong>$250</strong>. If the order only stores a productId, looking up the product later would show the new price instead of the price the customer actually paid.</p><p>Instead, store the product details inside the order when it’s created.</p><pre>{<br>  &quot;productId&quot;: &quot;prod_2001&quot;,<br>  &quot;name&quot;: &quot;Wireless Headphones&quot;,<br>  &quot;price&quot;: 2999,<br>  &quot;quantity&quot;: 1<br>}</pre><p>This ensures the order always reflects what the customer purchased, even if the product changes later.</p><p>Snapshotting is useful in any database, but it’s especially important in DynamoDB because there’s no efficient way to reconstruct historical values through joins. In practice, storing the data you need at write time is often the simplest and most scalable solution.</p><h4>CRUD and Query Operations</h4><p>Before we begin, remember that every DynamoDB operation uses the same building blocks we introduced earlier: <strong>Tables</strong> store <strong>Items</strong>, and each Item is made up of <strong>Attributes</strong>. We’ll use those concepts throughout the following examples.</p><p><strong>Key-Value vs. Document Items<br>A key-value item</strong> has a key and a small number of flat attributes — nothing nested.</p><pre>//Key-value Example<br>{ <br>  &quot;userId&quot;: { &quot;S&quot;: &quot;user_501&quot; }, <br>  &quot;name&quot;: { &quot;S&quot;: &quot;Rahul Sharma&quot; }, <br>  &quot;age&quot;: { &quot;N&quot;: &quot;28&quot; } <br>}</pre><p><strong>A document item</strong> uses the same primary key, but its attributes can include nested Maps (M) and Lists (L) — an entire structured object inside a single item.</p><pre>//Document item<br>{ <br>  &quot;userId&quot;: { &quot;S&quot;: &quot;user_501&quot; }, <br>  &quot;name&quot;: { &quot;S&quot;: &quot;Rahul Sharma&quot; }, <br>  &quot;address&quot;: { <br>    &quot;M&quot;: { <br>      &quot;city&quot;: { &quot;S&quot;: &quot;Bangalore&quot; },<br>       &quot;pincode&quot;: { &quot;S&quot;: &quot;560001&quot; }<br>     } <br>   }, <br>  &quot;recentOrderIds&quot;: { <br>     &quot;L&quot;: [ <br>       { &quot;S&quot;: &quot;order_101&quot; }, <br>       { &quot;S&quot;: &quot;order_104&quot; } <br>      ] <br>    } <br>  }</pre><p>Both are retrieved the same way — by primary key, with GetItem. The difference is entirely in <em>how much is packed into one item</em>. Simple lookups (settings, counters, flags) usually stay key-value. Anything representing a real-world entity with related data — a user with an address, an order with line items — tends to become a document.</p><p><strong>Understanding the DynamoDB CLI Commands<br></strong>Before we jump into CRUD operations, it’s helpful to understand the general structure of a DynamoDB CLI command.</p><pre>aws dynamodb &lt;operation&gt; \<br>  --table-name &lt;TableName&gt; \<br>  --key &#39;&lt;JSON&gt;&#39; \<br>  --other-options</pre><p>The important parts are:</p><ul><li><strong>&lt;operation&gt;</strong> – <strong>&lt;operation&gt;</strong> – The action you want to perform, such as put-item, get-item, update-item, delete-item, query, or scan. Single-item operations (get-item, update-item, delete-item) use --key; query and scan work with a group of items instead and use different parameters, covered later</li><li><strong>--table-name</strong> – The DynamoDB table to operate on.</li><li><strong>--key / </strong><strong>--item</strong> – The item or key represented as JSON.</li></ul><p>One thing that surprises developers coming from SQL or MongoDB is that every value must include its data type.</p><pre>{&quot;userId&quot;: {&quot;S&quot;: &quot;user_501&quot;}}<br><br>//userId is attribute name<br>//s means String<br>//user_501 is actual value</pre><p><strong>CRUD Operations on the Users Table<br></strong>We’ll use the following <strong>User</strong> item throughout this section. It demonstrates that DynamoDB items can contain nested objects (<strong>Map</strong>) and arrays (<strong>List</strong>), not just simple key-value pairs.</p><pre>{<br>  &quot;userId&quot;: { &quot;S&quot;: &quot;user_501&quot; },<br>  &quot;name&quot;: { &quot;S&quot;: &quot;Rahul Sharma&quot; },<br>  &quot;address&quot;: {<br>    &quot;M&quot;: {<br>      &quot;city&quot;: { &quot;S&quot;: &quot;Bangalore&quot; },<br>      &quot;pincode&quot;: { &quot;S&quot;: &quot;560001&quot; }<br>    }<br>  },<br>  &quot;recentOrderIds&quot;: {<br>    &quot;L&quot;: [ { &quot;S&quot;: &quot;order_101&quot; }, { &quot;S&quot;: &quot;order_104&quot; } ]<br>  }<br>}</pre><p><strong>Create an Item (PutItem): </strong>It creates a new item. If an item with the same primary key already exists, <strong>the entire item is replaced</strong>.</p><pre>aws dynamodb put-item \<br>  --table-name User \<br>  --item &#39;{<br>    &quot;userId&quot;: {&quot;S&quot;: &quot;user_501&quot;},<br>    &quot;name&quot;: {&quot;S&quot;: &quot;Rahul Sharma&quot;},<br>    &quot;address&quot;: {&quot;M&quot;: {<br>      &quot;city&quot;: {&quot;S&quot;: &quot;Bangalore&quot;},<br>      &quot;pincode&quot;: {&quot;S&quot;: &quot;560001&quot;}<br>    }},<br>    &quot;recentOrderIds&quot;: {&quot;L&quot;: [<br>      {&quot;S&quot;: &quot;order_101&quot;},<br>      {&quot;S&quot;: &quot;order_104&quot;}<br>    ]}<br>  }&#39;</pre><p><strong>Tip:</strong> If you want to create an item only when it doesn’t already exist, use a <strong>Condition Expression</strong> such as attribute_not_exists(userId).</p><pre>aws dynamodb put-item \<br>  --table-name User \<br>  --item &#39;{&quot;userId&quot;: {&quot;S&quot;: &quot;user_501&quot;}, &quot;name&quot;: {&quot;S&quot;: &quot;Rahul Sharma&quot;}}&#39; \<br>  --condition-expression &quot;attribute_not_exists(userId)&quot;</pre><p><strong>Read an Item (GetItem): </strong>retrieves a single item using its primary key.</p><pre>aws dynamodb get-item \<br>  --table-name User \<br>  --key &#39;{&quot;userId&quot;: {&quot;S&quot;: &quot;user_501&quot;}}&#39;</pre><p><strong>Update an Item (UpdateItem): </strong>Unlike PutItem, which replaces the entire item, UpdateItem modifies only the attributes you specify.<br>Two parameters work together:</p><ul><li><strong>--update-expression</strong>tells DynamoDB <strong>what to change</strong>.</li><li><strong>--expression-attribute-values</strong> provides the values used in the update expression. Values are referenced using placeholders that begin with :.</li></ul><pre>//Update a field inside address, without touching the rest of it<br>aws dynamodb update-item \<br>  --table-name User \<br>  --key &#39;{&quot;userId&quot;: {&quot;S&quot;: &quot;user_501&quot;}}&#39; \<br>  --update-expression &quot;SET address.city = :c&quot; \<br>  --expression-attribute-values &#39;{&quot;:c&quot;: {&quot;S&quot;: &quot;Hyderabad&quot;}}&#39;<br><br>// Add a new order to the list<br>aws dynamodb update-item \<br>  --table-name User \<br>  --key &#39;{&quot;userId&quot;: {&quot;S&quot;: &quot;user_501&quot;}}&#39; \<br>  --update-expression &quot;SET recentOrderIds = list_append(recentOrderIds, :newOrder)&quot; \<br>  --expression-attribute-values &#39;{&quot;:newOrder&quot;: {&quot;L&quot;: [{&quot;S&quot;: &quot;order_108&quot;}]}}&#39;</pre><p><strong>Delete an Item (DeleteItem): </strong>It<strong> </strong>removes an item using its primary key.</p><pre>aws dynamodb delete-item \<br>  --table-name User \<br>  --key &#39;{&quot;userId&quot;: {&quot;S&quot;: &quot;user_501&quot;}}&#39;</pre><p><strong>Query vs. Scan<br></strong>If there’s one concept to remember about DynamoDB, it’s the difference between <strong>Query</strong> and <strong>Scan</strong>.</p><ul><li><strong>GetItem</strong> retrieves a single item using its complete primary key.</li><li><strong>Query</strong> retrieves one or more items that share the same <strong>Partition Key</strong> (and can optionally filter by the <strong>Sort Key</strong>).</li><li><strong>Scan</strong> reads every item in the table before applying any filters.</li></ul><p>In a well-designed DynamoDB application, <strong>GetItem</strong> and <strong>Query</strong> handle almost all requests. In application code, frequent Scans often indicate that your data model could be improved with a different key design or a Global Secondary Index (GSI).</p><pre>// Query — efficient, uses the partition key<br>QueryRequest queryRequest = QueryRequest.builder()<br>    .tableName(&quot;EcommerceTable&quot;)<br>    .keyConditionExpression(&quot;PK = :pk AND begins_with(SK, :skPrefix)&quot;)<br>    .expressionAttributeValues(Map.of(<br>        &quot;:pk&quot;, AttributeValue.builder().s(&quot;CUSTOMER#user_501&quot;).build(),<br>        &quot;:skPrefix&quot;, AttributeValue.builder().s(&quot;ORDER#&quot;).build()<br>    ))<br>    .build();<br><br>// Scan — avoid in production hot paths<br>ScanRequest scanRequest = ScanRequest.builder()<br>    .tableName(&quot;Orders&quot;)<br>    .filterExpression(&quot;status = :status&quot;)<br>    .expressionAttributeValues(Map.of(<br>        &quot;:status&quot;, AttributeValue.builder().s(&quot;SHIPPED&quot;).build()<br>    ))<br>    .build();</pre><p>A FilterExpression (used with either Query or Scan) is applied <strong>after</strong> DynamoDB reads the data — it still consumes read capacity for every item read, filtered or not. This is a common source of surprise cost. If you find yourself relying heavily on FilterExpression, it&#39;s usually a sign you need a GSI instead.</p><p><strong>Conditional Writes and Optimistic Locking<br></strong>Imagine two support agents open the same order while its status is <strong>PROCESSING</strong>. One updates it to <strong>SHIPPED</strong>, while the other changes it to <strong>CANCELLED</strong>. Without any safeguards, both updates succeed, and the last write silently overwrites the first. This is known as a <strong>lost update</strong>.</p><p>DynamoDB solves this with <strong>conditional writes</strong>. You can tell DynamoDB to perform an update only if the item is still in the expected state.</p><pre>aws dynamodb update-item \ <br>  --table-name Orders \ <br>  --key &#39;{&quot;orderId&quot;: {&quot;S&quot;: &quot;order_101&quot;}}&#39; \ <br>  --update-expression &quot;SET #s = :newStatus&quot; \ <br>  --condition-expression &quot;#s = :expectedStatus&quot; \ <br>  --expression-attribute-names &#39;{&quot;#s&quot;: &quot;status&quot;}&#39; \ <br>  --expression-attribute-values &#39;{<br>     &quot;:newStatus&quot;: {&quot;S&quot;: &quot;SHIPPED&quot;},<br>     &quot;:expectedStatus&quot;: {&quot;S&quot;: &quot;PROCESSING&quot;} }&#39;</pre><p>This command says: <strong>Update the order to </strong><strong>SHIPPED, but only if its current status is still </strong><strong>PROCESSING.</strong> If another process has already changed the status, DynamoDB rejects the update instead of silently overwriting the data.</p><p>This pattern is known as <strong>optimistic locking</strong>. Rather than locking the item, DynamoDB assumes conflicts are rare and verifies that the item hasn’t changed before applying the update. Many applications implement this using a <strong>version</strong> attribute instead of checking a business field like status, but the underlying idea is the same.</p><h4>Advanced Features</h4><p>Once you’re comfortable with DynamoDB’s core concepts, these are some of the features you’ll encounter in real-world applications.</p><p><strong>Transactions<br></strong>TransactWriteItems and TransactGetItems let you group multiple operations into a single atomic transaction. Either every operation succeeds, or none of them do. This is useful for scenarios such as creating an order while simultaneously deducting inventory.</p><p><strong>DynamoDB Streams<br></strong>DynamoDB Streams capture every insert, update, and delete made to a table. They’re commonly used to trigger AWS Lambda functions for tasks such as sending notifications, updating search indexes, maintaining aggregate tables, or feeding analytics pipelines.</p><p><strong>Time-to-Live (TTL)<br></strong>TTL automatically removes expired items based on a timestamp attribute. It’s ideal for temporary data such as user sessions, shopping carts, cache entries, or one-time tokens, without requiring cleanup jobs.</p><p><strong>Global Tables<br></strong>Global Tables automatically replicate data across multiple AWS Regions, enabling low-latency access and disaster recovery for globally distributed applications.</p><p><strong>DynamoDB Accelerator (DAX)<br></strong>DAX is an in-memory cache for DynamoDB that delivers microsecond read latency without requiring changes to your application’s data access code. It’s useful for read-heavy workloads where every millisecond matters.</p><p><strong>Read Consistency<br></strong>By default, DynamoDB uses <strong>eventually consistent reads</strong>, which are lower cost but may briefly return stale data after a write. When an application requires the latest committed data, you can request a <strong>strongly consistent read</strong>, which consumes more read capacity and isn’t supported on Global Secondary Indexes (GSIs).</p><h4>Using DynamoDB in a Spring Boot Application</h4><p>So far, we’ve explored DynamoDB using the AWS CLI because it makes the underlying concepts easy to understand. In a real Spring Boot application, however, you rarely work directly with CLI commands or manually build AttributeValue objects. Instead, you&#39;ll typically use the <strong>AWS SDK for Java v2</strong> along with the <strong>DynamoDB Enhanced Client</strong>, which provides an object-mapping layer similar to what JPA provides for relational databases.</p><p>The Enhanced Client lets you work with plain Java objects while handling the conversion to and from DynamoDB items automatically.</p><p><strong>Model Your DynamoDB Item<br></strong>The first step is to create a Java class that represents an item in your DynamoDB table.</p><pre>@DynamoDbBean <br>public class User { <br>  private String userId; <br>  private String name; <br>  private Address address;<br>  private String city;  <br>  private List&lt;String&gt; recentOrderIds; <br><br>  @DynamoDbPartitionKey <br>  public String getUserId() { return userId; } <br><br>  @DynamoDbSecondaryPartitionKey(indexNames = &quot;byCity&quot;) <br>  public String getCity() { return city; } <br><br>  // getters and setters... <br>}</pre><p>This class maps directly to the <strong>User</strong> item we’ve been using throughout this article.</p><p>A few annotations are worth understanding:</p><ul><li><strong>@DynamoDbBean</strong> tells the Enhanced Client that this class represents a DynamoDB item.</li><li><strong>@DynamoDbPartitionKey</strong> identifies the table&#39;s Partition Key (userId).</li><li><strong>@DynamoDbSecondaryPartitionKey</strong> maps the city field to the <strong>byCity</strong> Global Secondary Index (GSI), allowing users to be queried by city without performing a Scan.</li></ul><p>Notice that the address field is another Java object rather than a collection of AttributeValue objects.</p><pre>@DynamoDbBean <br>public class Address { <br>  private String city; <br>  private String pincode; <br>  // getters and setters... <br>}</pre><p>The Enhanced Client automatically stores this object as a DynamoDB <strong>Map (M)</strong> attribute. Likewise, List&lt;String&gt; is automatically mapped to a DynamoDB <strong>List (L)</strong>. One of the biggest advantages of the Enhanced Client is that you work with normal Java objects while it handles the DynamoDB data types behind the scenes.</p><p><strong>Configure the Enhanced Client<br></strong>The next step is configuring the AWS SDK.</p><pre>@Bean <br>public DynamoDbClient dynamoDbClient() {... } <br><br>@Bean <br>public DynamoDbEnhancedClient dynamoDbEnhancedClient( <br>DynamoDbClient dynamoDbClient) { ... } <br><br>@Bean public DynamoDbTable&lt;User&gt; userTable( <br>DynamoDbEnhancedClient enhancedClient) { <br>return enhancedClient.table( tableName, TableSchema.fromBean(User.class)); }</pre><p>Three components work together:</p><ul><li><strong>DynamoDbClient</strong> is the low-level client responsible for communicating with DynamoDB.</li><li><strong>DynamoDbEnhancedClient</strong> sits on top of the low-level client and performs the object mapping using your annotations.</li><li><strong>DynamoDbTable&lt;User&gt;</strong> represents a typed handle to the <strong>Users</strong> table. This is the object your service layer uses for all CRUD operations.</li></ul><p><strong>Perform CRUD Operations<br></strong>Once the table has been configured, the service layer becomes surprisingly simple.</p><pre>userTable.putItem(user); <br><br>User existingUser = userTable<br>      .getItem( Key.builder() .partitionValue(userId) .build()); <br><br>userTable.updateItem(user); <br><br>userTable.deleteItem( Key.builder() .partitionValue(userId) .build());<br><br></pre><p>If you’ve followed the CLI examples earlier in this article, these methods should look familiar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MV5RNuiVQgiQi-yFLN4OGA.png" /></figure><p>The concepts haven’t changed — only the API has.</p><p><strong>Querying a Global Secondary Index<br></strong>Earlier we created a <strong>Global Secondary Index (GSI)</strong> named <strong>byCity</strong> to avoid scanning the entire table when searching for users by city.</p><p>Using the Enhanced Client, querying the index is straightforward.</p><pre>DynamoDbIndex&lt;User&gt; cityIndex = userTable.index(&quot;byCity&quot;); <br><br>QueryConditional query = <br>  QueryConditional.keyEqualTo(Key.builder() <br>              .partitionValue(city).build()); <br><br>List&lt;User&gt; users = cityIndex.query(query).stream().flatMap(page -&gt; <br>                          page.items().stream()) .toList();</pre><p>Instead of performing a Scan, DynamoDB uses the <strong>byCity</strong> index to locate matching users efficiently — the same principle we discussed in the <strong>Query vs. Scan</strong> section.</p><p><strong>Conditional Writes<br></strong>The Enhanced Client also supports conditional writes.</p><p>In the sample project, creating a user uses the same attribute_not_exists(userId) condition that we implemented earlier with the AWS CLI.</p><pre>userTable.putItem(PutItemEnhancedRequest.builder(User.class).item(user)<br>    .conditionExpression(Expression.builder()<br>    .expression(&quot;attribute_not_exists(userId)&quot;)<br>    .build()).build());</pre><p>This ensures that an existing user cannot be accidentally overwritten. If another item already exists with the same userId, DynamoDB throws a ConditionalCheckFailedException, allowing the application to handle the conflict gracefully.</p><p>If you’d like to see these concepts in a complete Spring Boot application, I’ve published the full source code on GitLab:</p><ul><li><strong>User CRUD Application: </strong><a href="https://gitlab.com/CodeCraftByRamcharan/aws-springboot-demos/-/tree/main/springboot-dynamodb-crud?ref_type=heads">https://gitlab.com/CodeCraftByRamcharan/aws-springboot-demos/-/tree/main/springboot-dynamodb-crud?ref_type=heads</a></li><li><strong>CSV Batch Status Tracker</strong>: <a href="https://gitlab.com/CodeCraftByRamcharan/aws-springboot-demos/-/tree/main/dynamodb-batch-status-tracker?ref_type=heads">https://gitlab.com/CodeCraftByRamcharan/aws-springboot-demos/-/tree/main/dynamodb-batch-status-tracker?ref_type=heads</a></li></ul><h4>Conclusion</h4><p>DynamoDB isn’t just another NoSQL database — it’s a different way of thinking about data modeling. Instead of designing a schema first and optimizing queries later, you design your table around your application’s access patterns from the start.</p><p>That trade-off is what makes DynamoDB so powerful. By giving up some query flexibility, it delivers predictable, single-digit millisecond performance at virtually any scale with minimal operational overhead.</p><p>If you’re coming from MongoDB or Spring Boot development, the biggest mindset shift is simple: <strong>design for how your application reads data, not just how it stores it.</strong> Once that clicks, the rest of DynamoDB starts to make sense.</p><p>The companion Spring Boot projects in the GitLab repository demonstrate these concepts with working examples, so you can explore the code and experiment with DynamoDB yourself.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3a4caf83ee6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From On-Premise Databases to AWS: RDS, Aurora, Redshift, and Data Migration Explained]]></title>
            <link>https://medium.com/@yramcharanteja/from-on-premise-databases-to-aws-rds-aurora-redshift-and-data-migration-explained-5f09c17b2e67?source=rss-e072c7cbc844------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f09c17b2e67</guid>
            <category><![CDATA[aws-rds]]></category>
            <category><![CDATA[aws-dms]]></category>
            <category><![CDATA[aws-glue]]></category>
            <category><![CDATA[aws-aurora]]></category>
            <category><![CDATA[aws-redshift]]></category>
            <dc:creator><![CDATA[CodeCraft by Ramcharan]]></dc:creator>
            <pubDate>Wed, 29 Jul 2026 03:55:55 GMT</pubDate>
            <atom:updated>2026-07-29T03:55:55.819Z</atom:updated>
            <content:encoded><![CDATA[<h4>How Traditional Databases Actually Work</h4><p>Before we jump into AWS RDS and Aurora, it’s worth pausing and understanding what a database really <em>is</em> under the hood and what it traditionally took to run one. Once this clicks, RDS and Aurora will make a lot more sense — you’ll clearly see exactly what problem AWS is solving for you.</p><p><strong>The Three Layers of a Database System<br></strong>Think of a database system as three layers stacked on top of each other:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KO0YB1GKFPxk7mFcrJdDNQ.png" /></figure><ul><li><strong>Disk</strong> — where data lives permanently</li><li><strong>RAM</strong> — fast, temporary memory used while processing queries</li><li><strong>Database engine</strong> <strong>—</strong> the software that manages both and connects to your application</li></ul><p><strong>Commonly Used Database Engines</strong><br>MySQL, PostgreSQL, Oracle Database, Microsoft SQL Server, MariaDB</p><p><strong>What Exactly Does a Database Engine Do?<br></strong>The database engine is the actual software responsible for:</p><ul><li>Stores data on disk</li><li>Executes SQL queries</li><li>Manages transactions and concurrency</li><li>Caches data in memory for speed</li></ul><p><strong>What It Takes to Set Up a Database On-Premise<br></strong>Running a database in-house means procuring servers, installing and patching the OS and the engine, and manually configuring replication, failover, backups, and monitoring. None of this is one-time work — it has to be maintained continuously by a dedicated team for as long as the database runs.</p><p><strong>The Simple Alternative: AWS RDS and Aurora<br></strong>This is exactly what <strong>AWS RDS</strong> and <strong>Aurora</strong> eliminate. They run the same database engines you already know — but remove the manual, ongoing work involved in keeping them running:</p><ul><li><strong>No hardware to manage</strong> — no procuring servers, racking, or capacity planning</li><li><strong>Automated patching</strong> — OS and engine patches are applied for you, on a schedule you control</li><li><strong>Built-in high availability</strong> — Multi-AZ failover is a checkbox, not a custom script</li><li><strong>Automated backups</strong> — point-in-time recovery is available out of the box</li><li><strong>Easy scaling</strong> — resize compute or storage in minutes, without manual server migrations</li><li><strong>Built-in monitoring</strong> — CloudWatch metrics (CPU, memory, connections) are available immediately, no setup required</li></ul><p>In short: the database engine stays the same — MySQL is still MySQL — but AWS takes over everything <em>around</em> it.</p><h3><strong>RDS (Relational Database Service)</strong></h3><p>It is AWS’s managed service for running relational databases in the cloud. It’s not a database engine itself — it’s the platform that hosts engines like MySQL, PostgreSQL, Oracle, and SQL Server for you.</p><p>You just choose an engine, an instance size, and storage — and AWS handles the server, patching, backups, and monitoring.</p><p>Your application connects to it exactly like any traditional database — same drivers, same SQL, same connection string. Only the operational work behind the scenes has changed.</p><p><strong>Supported Database Engines in RDS</strong> are MySQL, PostgreSQL, MariaDB, Oracle Database, and Microsoft SQL Server.</p><p><strong>DB instance classes<br></strong>A <strong>DB instance class</strong> defines the compute capacity of your RDS database — essentially, how much CPU, RAM, and network performance it gets. Choosing the right instance class directly affects your database’s performance, and it’s one of the first decisions you make when creating an RDS or Aurora database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Jqvs8Ja5tEDgIYGc9peDw.png" /></figure><p><strong>Storage Types<br></strong>RDS storage determines how your database’s data is physically stored and how fast it can be read from or written to disk. Choosing the right storage type affects both performance and cost, and it’s configured separately from your instance class.</p><p>RDS offers three main storage types:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zv-0wqNxfHCb57dSbeMQLA.png" /></figure><p><strong>High Availability &amp; Scaling<br></strong>RDS offers two distinct features that are often confused with each other — <strong>Multi-AZ</strong> and <strong>Read Replicas</strong>. They solve different problems, and understanding the difference is important for real-world architecture decisions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CyA2ND3mzsaEIwk7h7XhJA.png" /></figure><p><strong>Backup &amp; Recovery<br></strong>RDS provides two types of backups, each serving a different purpose.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Oh_c6az2e3Nhz8S0g4-EZQ.png" /></figure><p><strong>Security: </strong>RDS should sit in a <strong>private subnet</strong>, not reachable from the internet. <strong>Security groups</strong> act as a firewall, controlling which resources (like your Spring Boot app on EC2) can connect and on which port. RDS also supports <strong>encryption at rest</strong> (KMS) and <strong>in transit</strong> (SSL/TLS). <strong>IAM database authentication</strong> replaces hardcoded passwords with short-lived, AWS-generated tokens — a more secure alternative.</p><p><strong>Parameter Groups vs Option Groups<br>Parameter groups</strong> control engine-level settings — things like max connections or memory allocation. <strong>Option groups</strong> enable extra features for specific engines, like encryption tools for Oracle or SQL Server. In short: parameter groups tune <em>how the engine behaves</em>; option groups turn on <em>extra features</em>.</p><p><strong>Monitoring</strong>: RDS automatically sends metrics to <strong>CloudWatch</strong> — CPU usage, free memory, number of connections, and free storage space — so you can see database health without setting anything up yourself. <strong>Performance Insights</strong> goes a level deeper, showing which specific queries are consuming the most database load.</p><p><strong>Maintenance: </strong>AWS applies OS and engine patches during a <strong>maintenance window</strong> you choose. If <strong>Multi-AZ</strong> is enabled, AWS patches the standby first, fails over to it, then patches the original primary — minimizing downtime during updates.</p><p><strong>Pricing: </strong>You pay for RDS based on the <strong>instance running</strong> (on-demand, or cheaper with a Reserved Instance commitment), the <strong>storage</strong> you provision, and <strong>backup storage</strong> beyond the free allowance. If you use <strong>cross-region read replicas</strong>, you also pay for data transfer between regions.</p><h3><strong>Aurora</strong></h3><p>It is AWS’s own relational database engine, built specifically for the cloud. It comes in two flavors — <strong>Aurora MySQL</strong> and <strong>Aurora PostgreSQL</strong> — and is compatible with those engines at the protocol level. That means your existing SQL, JDBC drivers, and Spring Boot/JPA code work without any changes.</p><p>But under the hood, Aurora isn’t just “managed MySQL.” AWS re-architected how the database stores and replicates data.</p><p><strong>How is Aurora different?<br></strong>In a traditional engine (including standard RDS), the database engine and its storage are tightly coupled — one server holds both the compute and the disk. Aurora separates the two:</p><ul><li><strong>Compute</strong> (the database engine) runs on one or more instances</li><li><strong>Storage</strong> is a separate, distributed layer that automatically replicates your data <strong>6 times across 3 Availability Zones</strong></li></ul><p>This separation is what gives Aurora its key advantages:</p><ul><li><strong>Faster failover</strong> — typically under 30 seconds, since a new instance can attach to the same shared storage instead of waiting for replication to catch up</li><li><strong>Auto-scaling storage</strong> — grows automatically up to 128TB, with no manual provisioning</li><li><strong>More read replicas</strong> — up to 15 Aurora Replicas (vs 5 for standard RDS), and they share the same underlying storage, so replication lag is much lower</li><li><strong>Better resilience</strong> — losing a copy of data (or even an entire AZ) doesn’t mean losing availability, since 6 copies exist across 3 AZs</li></ul><p><strong>Where Aurora Fits<br></strong>If you’re already comfortable with MySQL or PostgreSQL, Aurora gives you the same interface with a more resilient, cloud-native storage layer underneath — usually at a higher cost than standard RDS, but with less manual tuning needed for performance and availability.</p><p><strong>Aurora Cluster: Writer and Reader Instances<br></strong>Unlike a standalone RDS instance, an Aurora database runs as a <strong>cluster</strong> — a group of instances that all share the same underlying storage layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q2N31KzT8_sJphHIOyD8UA.png" /></figure><p><strong>Aurora Serverless v2<br></strong>Aurora Serverless v2 automatically scales compute up and down based on actual traffic, instead of you choosing a fixed instance size. Capacity is measured in <strong>Aurora Capacity Units (ACUs)</strong> — you set a min/max range, and Aurora adjusts within it in real time.</p><p><strong>Best for:</strong> unpredictable or spiky workloads, dev/test environments, or new applications where traffic patterns aren’t known yet. You pay based on actual usage rather than a fixed instance running 24/7.</p><p>Connecting to it works exactly like connecting to a regular Aurora cluster — same connection string, no application changes needed.</p><p><strong>Aurora Global Database<br></strong>Aurora Global Database replicates your data to up to 5 other AWS regions in under 1 second, letting users in those regions <strong>read</strong> data locally instead of round-tripping to the primary region.</p><p><strong>Scenario:</strong> Your Aurora database runs in the US, but you have an India office. Without Global Database, every request from India travels to the US and back. With it, India reads from a local copy — much faster. Writes still go to the US primary, since only the primary accepts writes.</p><p><strong>Disaster recovery:</strong> If the US region goes down entirely, you can promote the India secondary to become the new primary in about a minute, instead of losing your database until AWS restores the region.</p><p><strong>Key limitation:</strong> Secondaries are read-only — writes always reach the primary first, either handled by your app or automatically via write forwarding.</p><p><strong>Aurora Backup &amp; Storage Behavior<br></strong>Aurora handles backups and storage differently from standard RDS, with less manual overhead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ed2xPSIhWvfxXznUtGFYbg.png" /></figure><h3>RDS versus Aurora</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r2gYz4hWKsKjavO0mLMs6A.png" /></figure><h3>Amazon Redshift</h3><p>The Core Problem Redshift Solves<br>Imagine your Loan system has been running for 3 years on RDS/Aurora, and the business asks:</p><p><em>“Show me total loan amount disbursed per region, per quarter, for the last 3 years.”</em></p><p>This query has to scan millions of rows and aggregate across them. Running it directly on RDS would be slow, and it would compete for resources with your live application — real customers checking their accounts could see slowdowns.</p><p>RDS/Aurora are built for many small, fast queries (fetch one customer, insert one loan) — not massive aggregations across millions of rows. This is exactly the gap Redshift fills.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CTPRgdeHhNw1ukpi95zg-A.png" /></figure><p><strong>Row-Based vs Column-Based Storage<br></strong>This is the key reason Redshift is fast for analytics.</p><p>Take a simple employees table:</p><pre>| id | name  | department  | salary |<br>|----|-------|-------------|--------|<br>| 1  | Alice | Engineering | 85000  |<br>| 2  | Bob   | Sales       | 60000  |<br>| 3  | Carol | Engineering | 90000  |</pre><p>Query: SELECT department, SUM(salary) FROM employees GROUP BY department;<strong><br>Row-based storage (RDS/Aurora)</strong> stores data row by row:</p><pre>Row 1: [id=1, name=Alice, dept=Eng, salary=85000]<br>Row 2: [id=2, name=Bob, dept=Sales, salary=60000]</pre><p>This is efficient when you want an entire row — like “get everything about customer #123.” But if you only need the salary column across a million rows, the engine still has to read every row in full, wasting effort on columns you don&#39;t need.</p><p><strong>Column-based storage (Redshift)</strong> stores data column by column instead:</p><pre>id column:     [1, 2, ...]<br>name column:   [Alice, Bob, ...]<br>dept column:   [Eng, Sales, ...]<br>salary column: [85000, 60000, ...]</pre><p>Now, summing salaries across a million rows only touches the salary column — nothing else. This makes aggregation-heavy queries much faster, and columns compress better too, since similar values sit together.</p><p><strong>Redshift Cluster Architecture<br></strong>A Redshift cluster consists of:</p><ul><li><strong>Leader Node</strong> — receives your query, creates an execution plan, coordinates the compute nodes, and returns the final combined result. You never query compute nodes directly — always through the leader node.</li><li><strong>Compute Nodes</strong> — do the actual work, each holding a portion of your data. Your query gets split into pieces, and each compute node processes its slice of data <strong>in parallel</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fbz0ZaTCgjyTC8jgrxI8tA.png" /></figure><p><strong>How Data Actually Gets Into Redshift<br></strong>Unlike RDS/Aurora, your application typically <strong>doesn’t write directly to Redshift</strong> in real time. Common patterns:</p><ul><li><strong>COPY command</strong> — the standard way to bulk-load data, usually from files sitting in <strong>S3</strong>, in parallel across all nodes (fast)</li><li><strong>AWS Glue</strong> — a managed ETL (Extract, Transform, Load) service that can pull data from RDS/Aurora, transform it, and load it into Redshift on a schedule</li><li><strong>AWS DMS</strong> — can also be used for continuous replication from RDS/Aurora into Redshift</li><li><strong>Redshift Spectrum</strong> (below) — lets you skip loading entirely for some use cases</li></ul><p>A realistic pattern for your Loan system: a nightly job exports yesterday’s loan_applications and accounts data from RDS/Aurora into S3, then COPY it into Redshift, where analysts and dashboards query the accumulated historical data.</p><pre>//Query to load data in Redshift from S3 <br>COPY table_name<br>FROM &#39;s3://bucket-name/path/to/file.csv&#39;<br>IAM_ROLE &#39;arn:aws:iam::&lt;account-id&gt;:role/&lt;role-name&gt;&#39;<br>CSV<br>IGNOREHEADER 1;</pre><p><strong>Redshift Spectrum<br></strong>Redshift Spectrum lets you run SQL queries directly against data sitting in S3, without loading it into Redshift’s storage.</p><ul><li>Useful for huge historical datasets that would be expensive to store fully inside Redshift</li><li>Redshift’s compute nodes do the processing, but the data stays in S3 (Parquet, ORC, CSV)</li><li>Good middle ground: keep recent data in Redshift, keep historical data in S3, and query both together</li></ul><p>Setting up Spectrum takes three steps:<br>1. Create an External Schema: Connects Redshift to the Glue Data Catalog, which holds metadata about your S3 data.</p><pre>CREATE EXTERNAL SCHEMA spectrum_schema<br>FROM DATA CATALOG<br>DATABASE &#39;spectrum_db&#39;<br>IAM_ROLE default<br>CREATE EXTERNAL DATABASE IF NOT EXISTS;</pre><p>2. Create an External Table: Tells Redshift what the S3 data looks like. No data is moved; it’s just metadata pointing at S3.</p><pre>CREATE EXTERNAL TABLE spectrum_schema.loan_disbursements_historical (<br>    loan_id BIGINT,<br>    region VARCHAR(50),<br>    risk_category VARCHAR(20),<br>    disbursed_amount DECIMAL(15,2),<br>    disbursed_date DATE<br>)<br>STORED AS PARQUET<br>LOCATION &#39;s3://my-bank-demo-bucket/historical-loans/&#39;;</pre><p><strong>3. </strong>Query the Data Present in S3: Run a normal SQL query against the external table; Redshift reads the data directly from S3 on the fly.</p><p><strong>Redshift Serverless<br></strong>Similar concept to Aurora Serverless v2 — Redshift also offers a serverless option where compute capacity automatically scales based on query load, and you pay based on usage rather than maintaining an always-on cluster. Good fit for sporadic reporting workloads (e.g., a monthly finance report) where a permanently running cluster would be wasteful.</p><p><strong>Distribution Keys and Sort Keys<br></strong>Redshift spreads your table’s data across multiple compute nodes. <strong>Distribution Key</strong> and <strong>Sort Key</strong> control how that happens, and both affect query performance.</p><p><strong>Distribution Key (DISTKEY)</strong> decides which node each row lands on.</p><ul><li>DISTKEY (column) — rows with the same value (e.g., same region) land on the same node. This speeds up joins on that column, since matching rows are already together — no data has to move between nodes.</li><li>DISTSTYLE ALL — copies the entire table to every node. Good for small lookup tables that get joined often.</li><li>DISTSTYLE EVEN — spreads rows evenly with no particular logic. A safe default when there&#39;s no clear join pattern.</li></ul><p><strong>Sort Key (SORTKEY)</strong> decides the order data is physically stored <em>within</em> each node.<br>If a table is sorted by disbursed_date, a query filtering WHERE disbursed_date BETWEEN ... can skip straight to the relevant range instead of scanning everything — much faster for range-based queries.</p><p><strong>SQL Differences</strong><br>Basic SQL — SELECT, WHERE, GROUP BY, JOIN — works the same on both. <br>Redshift is PostgreSQL-based, so it’s closer to Aurora PostgreSQL than MySQL. Core queries are portable; engine-specific functions and features (like DISTKEY/SORTKEY) are not.</p><h3>AWS Glue</h3><p>It is a <strong>serverless ETL (Extract, Transform, Load) service</strong> — it moves data from one place to another, transforming it along the way, without you managing any servers.</p><ul><li><strong>Extract</strong> — pull data from a source (RDS, Aurora, S3, on-prem databases via JDBC, etc.)</li><li><strong>Transform</strong> — clean, reshape, or convert the data (e.g., rename columns, filter bad rows, convert CSV to Parquet)</li><li><strong>Load</strong> — write the result somewhere (S3, Redshift, another database)</li></ul><p><strong>Core Components</strong></p><ol><li><strong>Glue Data Catalog</strong> — a central metadata repository. It doesn’t store your actual data, just information about it: table names, column names, data types, and where the data physically lives (S3, RDS, Redshift, etc.).</li><li><strong>Crawlers</strong> — scan your data source (e.g., a folder of CSV files in S3) and automatically figure out its structure, then write that information into the Data Catalog.</li><li><strong>Jobs</strong> — the actual ETL work: extracts data from a source, transforms it, and loads it into a destination. Glue generates the code for you (Python or Scala, using Apache Spark) based on the source and destination you configure.</li><li><strong>Triggers</strong> — decide when a Job runs — on a schedule, on demand, or in response to an event.</li><li><strong>Glue Studio</strong> — a drag-and-drop interface for building ETL jobs without writing code.</li></ol><h3>Migrating to RDS/Aurora</h3><p><strong>The Core Problem Migration Solves<br></strong>Imagine a company has been running their Employee/Loan system on an <strong>on-premises Oracle server</strong> for 10 years. They’ve decided to move to RDS or Aurora — but the database has millions of live rows, and the application can’t just go offline for hours while data copies over. They need a way to move the data <strong>safely, accurately, and with minimal downtime</strong>.</p><p>Manually exporting/importing SQL dumps works for small databases, but breaks down at scale — dumps take hours, data keeps changing during the export, and you risk losing transactions that happened mid-migration. This is exactly the gap AWS’s migration tools fill.</p><p><strong>The Two Main Tools<br>1. AWS Database Migration Service (DMS)</strong> — the actual data-mover<br><strong>2. AWS Schema Conversion Tool (SCT)</strong> — the translator, needed only when source and target use different database engines</p><p><strong>Migration Strategies<br>Full Load</strong> — one-time bulk copy of all existing data. Good for a database that isn’t actively changing, or as the first phase of a bigger migration.</p><p><strong>Full Load + CDC (Change Data Capture)</strong> — bulk copies existing data first, then continuously replicates every new insert/update/delete that happens on the source <em>after</em> the bulk copy started. This is the standard approach for near-zero-downtime migrations — your source database keeps taking live writes throughout the entire process, and DMS keeps the target in sync.</p><p><strong>CDC Only</strong> — used when the target already has the base data (e.g., restored from a snapshot separately) and you just need ongoing changes replicated from that point forward.</p><p><strong>Homogeneous vs Heterogeneous Migrations</strong></p><ul><li><strong>Homogeneous</strong> — same engine on both sides (MySQL → MySQL, or MySQL → Aurora MySQL). Simpler, since schema and SQL syntax match exactly.</li><li><strong>Heterogeneous</strong> — different engines (Oracle → Aurora PostgreSQL, on-prem SQL Server → Aurora MySQL). This is where <strong>AWS Schema Conversion Tool (SCT)</strong> comes in — it analyzes the source schema, stored procedures, and functions, and automatically converts as much as possible into the target engine’s syntax (e.g., translating Oracle’s PL/SQL into PostgreSQL’s PL/pgSQL). Anything it can’t auto-convert, it flags for manual review.</li></ul><p><strong>Cutover<br></strong>It is the actual moment of switching your live application from the old database to the new one.</p><p><strong>Example: Migrating Oracle to Aurora MySQL Using SCT and DMS<br></strong>This is a <strong>heterogeneous migration</strong> — Oracle and Aurora MySQL are different engines, so both SCT (schema) and DMS (data) are needed.</p><p><strong>Step 1: Convert the Schema Using SCT</strong></p><ol><li>Download and install AWS Schema Conversion Tool on your local machine (it’s a desktop application, not a console feature)</li><li>Open SCT → Create New Project</li><li>Set Source: Oracle (host, port, credentials)</li><li>Set Target: Aurora MySQL (your cluster’s connection details)</li><li>Connect to both source and target</li><li>SCT analyzes your Oracle schema and shows a compatibility report — what percentage of tables, stored procedures, and triggers can convert automatically vs what needs manual fixes</li><li>Review the report — simple tables usually convert cleanly; complex PL/SQL procedures often need manual adjustment</li><li>Click Convert Schema — SCT generates the equivalent MySQL-compatible schema</li><li>Apply the converted schema to Aurora MySQL — this creates the empty tables/structure (no data yet)</li></ol><p><strong>Step 2: Set Up DMS to Move the Actual Data</strong></p><ol><li>Create a DMS replication instance — the “worker” that performs the data copy</li><li>Create a Source Endpoint (Oracle) and a Target Endpoint (Aurora MySQL), testing both connections</li><li>Create a Migration Task, selecting <strong>“Migrate existing data and replicate ongoing changes”</strong> (Full Load + CDC)</li><li>Start the task — DMS copies all existing Oracle data into the Aurora tables SCT created, then switches to CDC mode, continuously replicating new changes</li></ol><p><strong>Step 3: Monitor Progress</strong></p><p>The DMS console shows full load progress and CDC latency — how far behind the target is from the source. This should approach near-zero once caught up.</p><p><strong>Step 4: Cutover</strong></p><p>Once CDC latency is near zero:</p><ol><li>Briefly pause writes to Oracle</li><li>Let DMS apply the last remaining changes</li><li>Point your application to the Aurora MySQL endpoint instead of Oracle</li><li>Resume traffic</li></ol><h3>Conclusion</h3><p>We started with how a traditional database works and what it took to run one on-premises, then saw how RDS and Aurora take over that operational burden — Aurora with a cloud-native storage architecture built for speed and resilience.</p><p>Beyond the application database, we covered Redshift for analytics at scale, Glue for automating data movement, and DMS/SCT for migrating existing databases into AWS.</p><p>Together, these services cover the full lifecycle of a real system: running live data (RDS/Aurora), analyzing it (Redshift), moving it between systems (Glue), and migrating it into AWS in the first place (DMS/SCT). These aren’t just exam concepts — they’re the same building blocks used in production systems everywhere.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f09c17b2e67" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java 8 to Java 25: A Complete Feature Comparison for Developers]]></title>
            <link>https://medium.com/@yramcharanteja/java-8-to-java-25-a-complete-feature-comparison-for-developers-7a48205d9a0d?source=rss-e072c7cbc844------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a48205d9a0d</guid>
            <category><![CDATA[java-21-features]]></category>
            <category><![CDATA[java-17-features]]></category>
            <category><![CDATA[java-11-features]]></category>
            <category><![CDATA[java25]]></category>
            <category><![CDATA[java-8-feature]]></category>
            <dc:creator><![CDATA[CodeCraft by Ramcharan]]></dc:creator>
            <pubDate>Wed, 15 Jul 2026 18:21:31 GMT</pubDate>
            <atom:updated>2026-07-29T18:09:24.031Z</atom:updated>
            <content:encoded><![CDATA[<p>Java has been the backbone of enterprise applications for decades, powering everything from banking systems to large-scale e-commerce platforms. But unlike many legacy technologies, Java hasn’t stood still — it has <strong>evolved rapidly</strong> to keep up with modern software development needs.</p><p>Today, many organizations are still running on <strong>Java 8</strong> or <strong>Java 11</strong> 🏢, while newer projects have embraced <strong>Java 17</strong> and <strong>Java 21</strong>. And now, with the release of <strong>Java 25 (2025 LTS) 🎉</strong>, we’re seeing another <strong>big leap in performance, scalability, and developer productivity</strong>.</p><p>What makes Java special is its ability to <strong>balance stability and innovation</strong>. Enterprises trust its <strong>LTS releases</strong> for long-term reliability, while developers enjoy the constant stream of <strong>language upgrades, JVM improvements, and library enhancements</strong>. From <strong>lambdas and streams (Java 8)</strong> ➝ <strong>records, sealed classes, pattern matching, and virtual threads (Java 17–21)</strong> ➝ to the <strong>cutting-edge features in Java 25</strong>, the language has grown into a modern powerhouse.</p><p>💡 In this article, we’ll explore the <strong>major changes from Java 8 → 25</strong>, highlight the <strong>key features of each version</strong>, and help you decide <strong>why (and when) upgrading makes sense</strong> for your projects.</p><h3>☕ Java 8 (2014) — The Game Changer</h3><p>Java 8 wasn’t just another upgrade — it was a <strong>paradigm shift</strong>. For nearly two decades, Java had been an <strong>object-oriented, imperative language</strong>. But in 2014, with Java 8, it embraced <strong>functional programming concepts</strong> and modernized its API ecosystem, making developers rethink how they wrote Java.</p><p>Even today, many organizations still run on Java 8, because it introduced features that were so powerful and long-lasting that they remain core to modern Java development.</p><h4>🔑 Major Features Introduced in Java 8</h4><p><strong>1. Lambda Expressions ➝ Functional Java<br></strong>Before Java 8, passing behavior around (e.g., a function as a parameter) was clunky. Lambdas allowed developers to express this more concisely.</p><pre><br>//Before Java 8 (Anonymous Classes):<br>new Thread(new Runnable() {<br>    public void run() {<br>        System.out.println(&quot;Running in a thread&quot;);<br>    }<br>}).start();<br><br>//With Java 8 Lambda:<br>new Thread(() -&gt; System.out.println(&quot;Running in a thread&quot;)).start();</pre><p>Lambda expressions simplify code by reducing boilerplate, encourage a focus on behavior rather than objects, and enable functional-style APIs like Streams.</p><p><strong>2. Streams API ➝ Declarative Data Processing<br></strong>Before Java 8, working with collections often involved verbose loops, conditionals, and temporary lists. The Streams API introduced a functional, pipeline-based approach that makes processing data more concise and expressive. For a deeper dive into Streams and their capabilities, you can refer to <a href="https://medium.com/@yramcharanteja/beyond-loops-and-iteration-a-complete-guide-to-unlocking-java-8-streams-abcad2a59875">this detailed guide</a>.</p><p><strong>3. Default &amp; Static Methods in Interfaces<br></strong>🔴 <em>Before Java 8 (Prior)</em><br>Interfaces could only declare abstract methods. Any new method added to an interface would force <strong>all implementing classes</strong> to provide an implementation. This made it very hard to evolve libraries and APIs without breaking existing code.</p><p><strong>🟢 </strong><em>After Java 8</em><strong><br></strong>Java 8 introduced <strong>default</strong> and <strong>static methods</strong> in interfaces.</p><ul><li><strong>Default methods</strong> provide a method body inside the interface itself, ensuring backward compatibility and reducing boilerplate.</li><li><strong>Static methods</strong> allow utility functions to live directly in the interface, removing the need for separate helper classes.</li></ul><p><strong>4. New Date &amp; Time API (java.time)</strong><br>The old java.util.Date and Calendar Classes were not thread-safe, confusing, and often error-prone. To overcome these long-standing issues, Java 8 introduced the java.time package—a modern, immutable, and fluent date/time API inspired by Joda-Time. This new API provides clear and specialized classes, such as LocalDate, LocalTime, LocalDateTime, and ZonedDateTime to handle different use cases. Since these classes are immutable and thread-safe, they are well-suited for modern concurrent applications. Java 8 also introduced Period and Duration for measuring time-based differences and DateTimeFormatter for safe, customizable formatting and parsing. With these improvements, developers can easily perform common operations such as adding days, calculating age, or managing time zones without relying on cumbersome or error-prone utilities. Overall, the Java 8 Date/Time API made handling dates and times far more intuitive, reliable, and production-ready.</p><pre>// 📅 LocalDate<br>LocalDate today = LocalDate.now(); //2025-10-08<br><br>// ⏰ LocalTime<br>LocalTime nowTime = LocalTime.now();// 22:45:12.345<br><br>// 🕒 LocalDateTime<br>LocalDateTime nowDateTime = LocalDateTime.now();//2025-10-08T22:45:12.345<br><br>// 📆 Period (difference between two dates)<br>Period age = Period.between(LocalDate.of(1995, 3, 15), today);<br><br>// ⏳ Duration (difference between two times)<br>Duration workHours = Duration.between(LocalTime.of(9, 0), LocalTime.of(17, 30));//8 hours 30 minutes<br><br>// 📝 DateTimeFormatter<br>String formattedDate = nowDateTime.format(DateTimeFormatter.ofPattern(&quot;dd MMM yyyy, HH:mm&quot;));//08 Oct 2025, 22:45<br><br>// 🌍 ZonedDateTime<br>ZonedDateTime nowZone = ZonedDateTime.now();</pre><p>To explore real-world usage of these date/time classes in a Spring Boot project, take a look at:<br><a href="https://github.com/CodeCraftByRamcharan/springboot-java8-date-utils">https://github.com/CodeCraftByRamcharan/springboot-java8-date-utils</a></p><p><strong>5. Optional Class ➝ Safer Null Handling<br></strong>Before Java 8, null References were a common source of <strong>NullPointerExceptions</strong>, forcing developers to write multiple if checks before accessing values. Java 8 introduced the Optional class to provide a <strong>type-safe way to represent the presence or absence of a value</strong>. Instead of returningnull, methods can return anOptional, encouraging developers to explicitly handle missing values.</p><pre><br>//getName() is method that return String value<br>Optional&lt;String&gt; optionalName = Optional.ofNullable(getName());<br><br>// Traditional null check alternative<br>optionalName.ifPresent(name -&gt; System.out.println(&quot;Name: &quot; + name));<br><br>// Provide default value if empty<br>String nameOrDefault = optionalName.orElse(&quot;Guest&quot;);<br><br>// Throw exception if value is missing<br>optionalName.orElseThrow(() -&gt; new IllegalArgumentException(&quot;Name not found!&quot;));</pre><p><strong>Summary</strong><br>Java 8 was a <strong>watershed moment</strong> in Java history. It moved Java beyond its purely object-oriented roots, embraced functional programming, and gave developers modern APIs that are still in use today. That’s why it became the <strong>baseline enterprise version</strong> — and why many companies still rely on it, even in 2025.</p><h3>🚀 Java 11 (2018, LTS) — Modernization &amp; Cleanup</h3><p>Java 11 is built on the foundation of Java 8, bringing <strong>cleaner APIs</strong>, <strong>performance improvements</strong>, and <strong>enterprise-ready stability</strong>. It introduced <strong>String </strong>enhancements like isBlank() and strip(), and built on the immutable collection factory methods (List.of(), Set.of()) that JDK 9 had introduced, as well as the ability to run<strong> single-file Java programs</strong> without compilation. Unlike Java 9 and 10, which were short-term releases without LTS support, Java 11 became the widely <strong>adopted baseline</strong> for enterprises seeking long-term stability and modern features.</p><h4>🔑 Major Features Introduced in Java 11</h4><p><strong>1. Modern HttpClient API<br></strong>Before Java 11, developers had to rely on <strong>low-level and cumbersome code </strong><strong>HttpURLConnection</strong> or depend on <strong>third-party libraries (like Apache HttpClient or OkHttp)</strong> just to perform simple HTTP calls. The old API was verbose, hard to use, and lacked support for modern needs like <strong>asynchronous calls or HTTP/2</strong>.</p><p>Java 11 finally introduced the <strong>built-in </strong><strong>java.net.http.HttpClient</strong>, a modern, fluent, and fully-featured HTTP client that supports <strong>synchronous &amp; asynchronous calls, HTTP/2, and WebSocket communication</strong> out of the box—no external libraries required.</p><pre>// 1️⃣ Create an HttpClient instance (reusable, thread-safe)<br>HttpClient client = HttpClient.newHttpClient();<br><br>// 2️⃣ Build the HTTP request (GET by default)<br>HttpRequest request = HttpRequest.newBuilder()<br>        .uri(URI.create(&quot;https://api.example.com/data&quot;))<br>        .build();<br><br>// 3️⃣ Send the request synchronously and get the response as a String<br>HttpResponse&lt;String&gt; response =<br>        client.send(request, HttpResponse.BodyHandlers.ofString());</pre><p>If you’d like to see how HTTP requests (GET, POST, PUT, DELETE, etc.) evolved in Java — from the legacy HttpURLConnection approach to the modern one HttpClient introduced in Java 11—check out this repository:</p><p><a href="https://github.com/CodeCraftByRamcharan/java11-modern-http-vs-legacy"><strong>https://github.com/CodeCraftByRamcharan/java11-modern-http-vs-legacy</strong></a></p><p>It provides examples that illustrate both the old and new styles within the context of a Spring Boot + Maven project, making it easier to see the differences in readability, performance, and API design.</p><p><strong>2. Local-Variable Syntax in Lambdas</strong><br>var is a feature introduced in <strong>Java 10</strong> that enables <strong>local variable type inference</strong>. Instead of writing the full type of a local variable, you can usevar, and the <strong>compiler infers the type from the assigned value</strong>. It was introduced in Java to reduce verbosity and improve readability — especially when dealing with long or complex generic types.</p><pre>// Before Java 10<br>String message = &quot;Hello&quot;;<br><br>// Java 10+<br>var message = &quot;Hello&quot;;  // compiler knows it&#39;s a String</pre><p>However, in Java 10, var could only be used in <strong>local variable declarations</strong>, not in lambda parameters.In <strong>Java 11</strong>, by extending var to lambda parameters, developers could <strong>apply annotations like </strong><strong>@NotNull or </strong><strong>@Validdirectly on lambda parameters</strong> without writing full types, and enjoy <strong>consistent syntax between local variables and lambda parameters</strong> for cleaner, more readable code.</p><pre>Function&lt;String, String&gt; greet = (@NotNull var name) -&gt; &quot;Hello, &quot; + name;<br>System.out.println(greet.apply(&quot;Alice&quot;));  // Output: Hello, Alice<br><br>BiFunction&lt;Integer, Integer, Integer&gt; sum = (var a, var b) -&gt; a + b;<br>System.out.println(sum.apply(5, 3));  // Output: 8</pre><p><strong>Note:</strong> BiFunction It is a functional interface in Java that represents a function taking <strong>two arguments</strong> and producing a <strong>single result</strong>, commonly used in lambda expressions for operations like addition, concatenation, or any computation involving two inputs.</p><p><strong>Summary</strong><br>Java 11 marked a significant step in the platform’s evolution, building on Java 8’s foundation while introducing <strong>practical, developer-friendly features</strong>. <strong>String and Collection enhancements</strong>, <strong>single-file program execution</strong>, <strong>modern HttpClient</strong>, and <strong>local-variable syntax in lambdas</strong> made code <strong>cleaner, safer, and more concise</strong>. Combined with <strong>performance improvements, garbage collection enhancements, and long-term support (LTS)</strong>, Java 11 quickly became the <strong>preferred baseline for enterprises</strong>, offering both <strong>stability and modern capabilities</strong> for production-ready applications.</p><h3>🔒 Java 17 (2021, LTS) — More Expressive &amp; Secure</h3><p>It is a major <strong>Long-Term Support (LTS)</strong> release that solidified modern Java with better <strong>performance, security, and readability</strong>. It brought <strong>strong encapsulation of JDK internals</strong>, removed outdated modules, improved GC, and became the <strong>stable foundation for all future Java features</strong>.</p><h4>🔑 Major Features Introduced in Java 17</h4><p><strong>1. Sealed Classes — Controlled Inheritance</strong><br>It gives<strong> developers control over inheritance</strong>, preventing unwanted or accidental subclassing in large systems. Before this, class hierarchies were either too open (regular classes) or too restrictive (final classes), making it hard to balance flexibility and safety. With sealed classes, you can <strong>explicitly list which classes are allowed to extend</strong>, improving <strong>security and maintainability, and enabling better compiler checks and pattern matching</strong>.</p><pre>//Payment is sealed parent class<br>//Each subclass extending payment should be final<br>//Any attempts to crate a new subclass not in permit will cause compile time error<br>public sealed class Payment permits CreditCardPayment, CashPayment { <br>    public abstract void pay(double amount);<br>}<br><br>// Permitted subclass 1<br>public final class CreditCardPayment extends Payment {<br>    @Override<br>    public void pay(double amount) {<br>        System.out.println(&quot;Paid &quot; + amount + &quot; using Credit Card&quot;);<br>    }<br>}<br><br>// Permitted subclass 2<br>public final class CashPayment extends Payment {<br>    @Override<br>    public void pay(double amount) {<br>        System.out.println(&quot;Paid &quot; + amount + &quot; using Cash&quot;);<br>    }<br>}</pre><p><strong>2. Pattern Matching for instanceof — Cleaner Type Check<br></strong>Pattern matching for instanceof was introduced in JDK 16 (JEP 394) to simplify type checks and <strong>reduce boilerplate</strong>, and became part of the Java 17 LTS baseline. Instead of casting after an instanceof check, you can <strong>declare a variable directly in the condition</strong>, making code cleaner and safer. It&#39;s especially useful when working with <strong>specific subtypes in conditional logic</strong>.</p><pre>Object obj = &quot;Hello, Java!&quot;;<br><br>// Old way<br>if (obj instanceof String) {<br>    String str = (String) obj; // explicit cast<br>    System.out.println(str.length());<br>}<br><br>// New way with pattern matching<br>if (obj instanceof String str) { // variable declared inline<br>    System.out.println(str.length());<br>}</pre><p><strong>3. Records — Immutable Data Classes<br></strong>In many Java applications, we create classes to <strong>hold and transfer data</strong> (DTOs, API responses, database results). Before records, we had to write <strong>constructors, getters, equals, hashCode, toString, and final fields</strong> manually — over and over again. This led to <strong>boilerplate-heavy, repetitive, and hard-to-maintain code.</strong></p><p>Records, introduced in JDK 16 (JEP 395) and carried into the Java 17 LTS baseline, solve this problem by offering a <strong>compact syntax for immutable data classes</strong>. You only define the <strong>field names and types</strong>, and the Java compiler automatically generates <strong>private final fields, a constructor, getter methods (fieldName()), and toString()/equals()/hashCode()</strong>, eliminating boilerplate and ensuring immutability in a single line of code.</p><p><strong>Example (before vs after)</strong></p><pre>//Old way (lots of code):<br>class Student {<br>    private final Integer id;<br>    private final String name;<br><br>    // constructor, getters, toString, equals, hashCode...<br>}<br><br>//With Record (one line!):<br>public record Student(Integer id, String name) {}<br></pre><p>If you’d like to see a <strong>real-world implementation of Records in a Spring Boot application</strong>, you can explore this GitHub repository:<br><a href="https://github.com/CodeCraftByRamcharan/springboot-records-demo"><strong>https://github.com/CodeCraftByRamcharan/springboot-records-demo</strong></a></p><p>It demonstrates how records can be used as <strong>DTOs, API response objects, and value carriers</strong> in a practical project, making the code <strong>cleaner, more immutable, and free of boilerplate</strong>.</p><p><strong>Summary<br></strong>Java 17 solidified modern Java as a more expressive, safer, and maintainable platform. Sealed Classes gave developers precise control over inheritance hierarchies, Pattern Matching for instanceof eliminated repetitive casting boilerplate, and Records reduced data class verbosity to a single line. Combined with strong JDK encapsulation, improved garbage collection, and long-term support, Java 17 became the new enterprise baseline — the stable, modern foundation that every feature from Java 21 onwards is built upon.</p><h3>🧵 Java 21 (2023, LTS) — Concurrent &amp; Expressive</h3><p>Java 21 is the most significant LTS release since Java 8, building on the foundation laid by Java 17. It brought Virtual Threads for effortless concurrency, completed the pattern matching story with switch expressions and record destructuring, unified ordered collection access, and previewed unnamed variables to eliminate the last traces of noise from modern Java code. Together, these features make Java 21 the natural upgrade target for any team ready to embrace the next era of Java development.</p><h4>🔑 <strong>Major Features Introduced in Java 21</strong></h4><p><strong>1. Virtual Threads <br></strong>Traditional Java threads map 1-to-1 with OS threads — expensive to create, heavy on memory (~1MB each), and mostly idle while waiting on I/O. Scaling to thousands of concurrent requests meant managing large, carefully tuned thread pools.</p><p>Java 21 changed this with <strong>Virtual Threads</strong> (Project Loom). Managed by the JVM rather than the OS, virtual threads are incredibly lightweight — you can spin up <strong>millions</strong> of them without breaking a sweat. The JVM automatically parks a virtual thread during I/O and frees the carrier thread to handle other work, making blocking code scale like async code — without the complexity.</p><pre>// As simple as this — no pool sizing, no tuning<br>ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor();<br>executor.submit(() -&gt; handleRequest());</pre><p>Virtual Threads is a deep topic on its own — covering thread lifecycle, pinning pitfalls, Structured Concurrency, and how it compares to CompletableFuture. I&#39;ve written a dedicated deep-dive article covering all of this with real-world examples:</p><p><a href="https://medium.com/@yramcharanteja/from-threads-to-virtual-threads-the-evolution-of-concurrency-in-java-b33e7523dcc2">From Threads to Virtual Threads: The Evolution of Concurrency in Java</a></p><p><strong>2. Pattern Matching for Switch<br></strong>Before Java 21, handling multiple type checks required verbose if-else instanceof chains or limited switch Statements that only worked with primitives and Strings. The code was repetitive, error-prone, and hard to read.</p><p>Java 21 extended pattern matching to switch, allowing you to <strong>match types, deconstruct values, and add conditions</strong> — all in one clean expression.</p><pre>//Before Java 21 — verbose and repetitive:<br>static String describe(Object obj) {<br>    if (obj instanceof Integer i) {<br>        return &quot;Integer: &quot; + i;<br>    } else if (obj instanceof String s) {<br>        return &quot;String: &quot; + s;<br>    } else if (obj instanceof Double d) {<br>        return &quot;Double: &quot; + d;<br>    } else {<br>        return &quot;Unknown type&quot;;<br>    }<br>}<br><br>//With Pattern Matching for Switch (Java 21):<br>static String describe(Object obj) {<br>    return switch (obj) {<br>        case Integer i -&gt; &quot;Integer: &quot; + i;<br>        case String s  -&gt; &quot;String: &quot; + s;<br>        case Double d  -&gt; &quot;Double: &quot; + d;<br>        default        -&gt; &quot;Unknown type&quot;;<br>    };<br>}<br></pre><p><strong>Guarded Patterns — Adding Conditions Inline<br></strong>You can add conditions directly inside the case using when, eliminating extra if checks inside the branch</p><pre>static String classify(Object obj) {<br>    return switch (obj) {<br>        case Integer i when i &gt; 0  -&gt; &quot;Positive Integer: &quot; + i;<br>        case Integer i when i &lt; 0  -&gt; &quot;Negative Integer: &quot; + i;<br>        case Integer i             -&gt; &quot;Zero&quot;;<br>        case String s when s.isEmpty() -&gt; &quot;Empty String&quot;;<br>        case String s              -&gt; &quot;String: &quot; + s;<br>        default                    -&gt; &quot;Unknown&quot;;<br>    };<br>}</pre><p><strong>Works Beautifully with Sealed Classes<br></strong>Pattern matching for switch pairs perfectly with sealed classes (introduced in Java 17). Since the compiler knows all permitted subtypes, it enforces <strong>exhaustiveness</strong> — you’ll get a compile-time error if you miss a case</p><pre>public class PaymentProcessor {<br><br>    sealed interface Payment permits CreditCardPayment, UpiPayment, CashPayment {}<br><br>    record CreditCardPayment(String cardNumber, double amount) implements Payment {}<br>    record UpiPayment(String upiId, double amount) implements Payment {}<br>    record CashPayment(double amount) implements Payment {}<br><br>    static String process(Payment payment) {<br>        return switch (payment) {<br>            case CreditCardPayment c when c.amount() &gt; 10000 -&gt;<br>                &quot;High-value card payment of &quot; + c.amount() + &quot; requires OTP verification&quot;;<br><br>            case CreditCardPayment c -&gt;<br>                &quot;Processing card payment of &quot; + c.amount() + &quot; using card ending in &quot;<br>                    + c.cardNumber().substring(c.cardNumber().length() - 4);<br><br>            case UpiPayment u when u.amount() &gt; 5000 -&gt;<br>                &quot;High-value UPI payment of &quot; + u.amount() + &quot; via &quot; + u.upiId();<br><br>            case UpiPayment u -&gt;<br>                &quot;Processing UPI payment of &quot; + u.amount() + &quot; via &quot; + u.upiId();<br><br>            case CashPayment c -&gt;<br>                &quot;Processing cash payment of &quot; + c.amount();<br><br>            // No default needed — sealed interface guarantees exhaustiveness <br>        };<br>    }</pre><p><strong>3. Record Patterns<br></strong>Records, introduced in JDK 16 and adopted into the Java 17 LTS baseline, made it easy to <em>create</em> immutable data carriers, but extracting their fields still required manual calls like record.fieldName(). Java 21 introduced <strong>Record Patterns</strong>, allowing you to destructure a record’s components directly within a pattern match — no manual extraction needed.</p><pre>//Before Record Patterns — manual field access<br>record Point(int x, int y) {}<br><br>static String describe(Object obj) {<br>    if (obj instanceof Point p) {<br>        int x = p.x();<br>        int y = p.y();<br>        return &quot;Point at (&quot; + x + &quot;, &quot; + y + &quot;)&quot;;<br>    }<br>    return &quot;Not a point&quot;;<br>}<br><br>//With Record Patterns (Java 21)<br>record Point(int x, int y) {}<br><br>static String describe(Object obj) {<br>    if (obj instanceof Point(int x, int y)) {<br>        return &quot;Point at (&quot; + x + &quot;, &quot; + y + &quot;)&quot;;<br>    }<br>    return &quot;Not a point&quot;;<br>}<br></pre><p>The record is deconstructed right in the instanceof check — x and y are extracted and ready to use immediately, with no intermediate variable or method calls.</p><p><strong>Nested Record Patterns — Destructuring Complex Structures<br></strong>This is where record patterns really shine — they can destructure <strong>nested</strong> records in a single match, eliminating chains of .getX().getY() calls.</p><pre>record Address(String city, String zipCode) {}<br>record Customer(String name, Address address) {}<br>record Order(Customer customer, double amount) {}<br><br>static String summarize(Order order) {<br>    if (order instanceof Order(Customer(String name, Address(String city, String zip)), double amount)) {<br>        return name + &quot; from &quot; + city + &quot; (&quot; + zip + &quot;) ordered for &quot; + amount;<br>    }<br>    return &quot;Invalid order&quot;;<br>}</pre><p><strong>Combined with Switch — The Real Power<br></strong>Record patterns become especially powerful when paired with switch, letting you match and destructure in a single expression</p><pre>sealed interface Shape permits Circle, Rectangle {}<br>record Circle(Point center, double radius) implements Shape {}<br>record Rectangle(Point topLeft, Point bottomRight) implements Shape {}<br><br>static String describeShape(Shape shape) {<br>    return switch (shape) {<br>        case Circle(Point(int x, int y), double radius) -&gt;<br>            &quot;Circle at (&quot; + x + &quot;, &quot; + y + &quot;) with radius &quot; + radius;<br><br>        case Rectangle(Point(int x1, int y1), Point(int x2, int y2)) -&gt;<br>            &quot;Rectangle from (&quot; + x1 + &quot;, &quot; + y1 + &quot;) to (&quot; + x2 + &quot;, &quot; + y2 + &quot;)&quot;;<br>    };<br>}</pre><p><strong>Using </strong><strong>var for Cleaner Syntax<br></strong>If explicit types feel verbose, you can use var inside record patterns — the compiler still infers and checks types correctly</p><pre>if (order instanceof Order(Customer(var name, Address(var city, var zip)), var amount)) {<br>    System.out.println(name + &quot; from &quot; + city);<br>}</pre><p>Record Patterns turns records and pattern matching into a complete, cohesive feature. Combined with sealed classes (Java 17) and Pattern Matching for Switch (also Java 21), Java now lets you model data and logic together — concise, type-safe, and exhaustive — closing the gap that languages like Kotlin and Scala have had for years.</p><p><strong>4. Sequenced Collections</strong> <br>Before Java 21, accessing the first or last element of a collection was inconsistent and awkward depending on which type you used. List had get(0) and get(size()-1), Deque had getFirst()/getLast(), but LinkedHashSet and LinkedHashMap had no clean way to get the first or last entry at all — you had to rely on iterators or convert to an array.</p><p>Java 21 introduced the <strong>Sequenced Collections</strong> API — a new set of interfaces (SequencedCollection, SequencedSet, SequencedMap) that brings a <strong>uniform, predictable way</strong> to access both ends of any ordered collection, and to easily reverse it.</p><pre>//Before Java 21 — inconsistent and clunky:<br>List&lt;String&gt; list = new ArrayList&lt;&gt;(List.of(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;));<br><br>// First element<br>String first = list.get(0);<br><br>// Last element<br>String last = list.get(list.size() - 1);<br><br>// Reversing required Collections utility<br>List&lt;String&gt; reversed = new ArrayList&lt;&gt;(list);<br>Collections.reverse(reversed);<br><br>// LinkedHashSet had NO clean way to get first/last!<br>LinkedHashSet&lt;String&gt; set = new LinkedHashSet&lt;&gt;(List.of(&quot;x&quot;, &quot;y&quot;, &quot;z&quot;));<br>String firstInSet = set.iterator().next(); // clunky workaround<br><br><br>//With Sequenced Collections (Java 21)<br>// Method: getFirst()/getLast()<br>// Method: addFirst()/addLast()<br>// Method: removeFirst()/removeLast()<br>// Method: reverse()<br>List&lt;String&gt; list = new ArrayList&lt;&gt;(List.of(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;));<br><br>String first = list.getFirst();   // &quot;a&quot;<br>String last  = list.getLast();    // &quot;c&quot;<br><br>list.addFirst(&quot;start&quot;);           // adds at the beginning<br>list.addLast(&quot;end&quot;);              // adds at the end<br><br>list.removeFirst();<br>list.removeLast();<br><br>List&lt;String&gt; reversed = list.reversed(); // clean, built-in reversal<br><br>//Now LinkedHashSet Supports This Too<br>LinkedHashSet&lt;String&gt; set = new LinkedHashSet&lt;&gt;(List.of(&quot;x&quot;, &quot;y&quot;, &quot;z&quot;));<br><br>String first = set.getFirst(); // &quot;x&quot;<br>String last  = set.getLast();  // &quot;z&quot;<br><br>SequencedSet&lt;String&gt; reversedSet = set.reversed(); // &quot;z&quot;, &quot;y&quot;, &quot;x&quot;<br><br>//LinkedHashMap Gets the Same Treatment<br>// Method: firstEntry()/lastEntry()<br>LinkedHashMap&lt;String, Integer&gt; map = new LinkedHashMap&lt;&gt;();<br>map.put(&quot;one&quot;, 1);<br>map.put(&quot;two&quot;, 2);<br>map.put(&quot;three&quot;, 3);<br><br>var firstEntry = map.firstEntry();  // one=1<br>var lastEntry  = map.lastEntry();   // three=3<br><br>SequencedMap&lt;String, Integer&gt; reversedMap = map.reversed();<br>// three=3, two=2, one=1</pre><p>SequencedCollection is implemented by List, Deque, and LinkedHashSet. SequencedMap is implemented by LinkedHashMap and TreeMap. Notably, Set and Map themselves remain unordered — only the <strong>ordered implementations</strong> (LinkedHashSet, LinkedHashMap, TreeMap) gain these new capabilities.</p><p><strong>5. Unnamed Patterns and Variables (</strong><strong>_)<br></strong>As pattern matching grew more powerful across Java 17–21, a new problem emerged — you often had to declare variables just to satisfy the syntax, even when you had no intention of using them. This led to noise like unused variable warnings, meaningless names like ignored or unused, and unnecessary cognitive load for anyone reading the code.</p><p>Java 21 introduced <strong>Unnamed Patterns </strong>and<strong> Variables </strong>as a preview feature (JEP 443), using the underscore _ as a way to explicitly say <em>&quot;I know this value exists, but I don&#39;t need it.&quot; </em>The feature was later finalized in JDK 22 (JEP 456).</p><pre>// The Problem — declaring variables you never use:<br><br>// You only care about the type, not the value<br>if (obj instanceof String s) { // &#39;s&#39; is never used<br>    System.out.println(&quot;It&#39;s a String&quot;);<br>}<br><br>// You only care about some fields, not all<br>if (order instanceof Order(Customer customer, double amount)) { // &#39;amount&#39; never used<br>    System.out.println(&quot;Customer: &quot; + customer.name());<br>}<br><br>// With Unnamed Variables (Java 21) — _ signals intent clearly:<br><br>// You only care about the type<br>if (obj instanceof String _) {<br>    System.out.println(&quot;It&#39;s a String&quot;);<br>}<br><br>// You only care about some fields<br>if (order instanceof Order(Customer customer, double _)) {<br>    System.out.println(&quot;Customer: &quot; + customer.name());<br>}</pre><p>_ tells the compiler — and more importantly, the next developer reading your code — <em>&quot;this value is intentionally ignored.&quot;</em></p><p><strong>In Switch Statements: </strong>_ works naturally inside switch pattern matching too.</p><pre>sealed interface Notification permits EmailNotification, SmsNotification, PushNotification {}<br>record EmailNotification(String email, String subject, String body) implements Notification {}<br>record SmsNotification(String phone, String message) implements Notification {}<br>record PushNotification(String deviceId, String title) implements Notification {}<br><br>static void process(Notification notification) {<br>    switch (notification) {<br>        // Only need email address, ignore subject and body<br>        case EmailNotification(String email, _, _) -&gt;<br>            System.out.println(&quot;Sending email to: &quot; + email);<br><br>        // Only need phone number, ignore message<br>        case SmsNotification(String phone, _) -&gt;<br>            System.out.println(&quot;Sending SMS to: &quot; + phone);<br><br>        // Only need device ID, ignore title<br>        case PushNotification(String deviceId, _) -&gt;<br>            System.out.println(&quot;Pushing to device: &quot; + deviceId);<br>    }<br>}</pre><p><strong>In Enhanced For Loops: </strong>When you need to count iterations or trigger side effects but don’t care about the element itself</p><pre>List&lt;Order&gt; orders = List.of(<br>    new Order(&quot;order-1&quot;, 100.0),<br>    new Order(&quot;order-2&quot;, 200.0),<br>    new Order(&quot;order-3&quot;, 300.0)<br>);<br><br>int count = 0;<br>for (var _ : orders) {  // element intentionally ignored<br>    count++;<br>}<br>System.out.println(&quot;Total orders: &quot; + count); // 3</pre><p><strong>In Try-Catch Blocks: </strong>Sometimes you need to catch an exception for flow control, but have no use for the exception object itself.</p><pre>// Before — forced to name it even though it&#39;s never used<br>try {<br>    int result = Integer.parseInt(input);<br>} catch (NumberFormatException e) { // &#39;e&#39; is never used<br>    System.out.println(&quot;Invalid number format&quot;);<br>}<br><br>// After — intent is clear<br>try {<br>    int result = Integer.parseInt(input);<br>} catch (NumberFormatException _) {<br>    System.out.println(&quot;Invalid number format&quot;);<br>}</pre><p><strong>Multiple Unnamed Variables in the Same Scope<br></strong>Unlike regular variables, you can declare _ multiple times in the same scope — each one is independent and doesn&#39;t conflict</p><pre>switch (shape) {<br>    case Circle(Point(int x, int y), double _)     -&gt; System.out.println(&quot;Circle at &quot; + x + &quot;,&quot; + y);<br>    case Rectangle(Point(int x, int y), Point(_, _)) -&gt; System.out.println(&quot;Rectangle at &quot; + x + &quot;,&quot; + y);<br>}</pre><p>With regular named variables, declaring two variables with the same name in the same scope would be a compile error. With_, it&#39;s intentional and perfectly valid.</p><p><strong>Summary<br></strong>Java 21 marks the most significant LTS release since Java 8. Virtual Threads brought effortless scalability to I/O-bound applications, Pattern Matching for Switch and Record Patterns made type-safe, expressive code the new norm, Sequenced Collections unified how we navigate ordered data, and a preview of Unnamed Variables hinted at where pattern-heavy code was headed. Together, these features make Java 21 the new baseline for modern, production-ready applications — the version teams will anchor on for years to come.</p><h3>🌟 Java 25 (2025, LTS) — Simpler, Safer &amp; Performance-Ready</h3><p>Java 25 is the first LTS release since Java 21, continuing the story Java 21 started — making Java more expressive, safer, and faster, while also lowering the barrier to entry for developers new to the language. It removed decades-old ceremony from everyday Java code, modernized thread-local data sharing for the virtual-thread era, and tightened constructor safety — all while delivering meaningful runtime performance improvements under the hood.</p><h4>🔑 Major Features Introduced in Java 25</h4><p><strong>1. Compact Source Files &amp; Instance Main Methods<br></strong>For decades, the simplest Java program required a class declaration, public static void main(String[] args), and a full understanding of public, static, and String[] before printing a single line. Java 25 finally removes this ceremony.</p><pre>// Before Java 25 — required even for &quot;Hello, World!&quot;<br>public class Main {<br>    public static void main(String[] args) {<br>        System.out.println(&quot;Hello, World!&quot;);<br>    }<br>}<br><br>// Java 25 — that&#39;s it<br>void main() {<br>    System.out.println(&quot;Hello, World!&quot;);<br>}</pre><p>This feature simplifies Java for beginners while keeping full compatibility with standard Java — making it easier to write small programs without needing to learn about public, static, String[] args, or class declarations immediately. It&#39;s also a natural fit for quick scripts, prototypes, and demos without the scaffolding overhead.</p><p><strong>2. Scoped Values — A Safer Alternative to ThreadLocal<br></strong>ThreadLocal has been the standard way to share data across methods within a thread since Java 1.2. But it comes with serious problems — it&#39;s mutable, easy to forget to clean up (leading to memory leaks), and doesn&#39;t play well with virtual threads.</p><p>Java 25 finalizes <strong>Scoped Values</strong> as a modern replacement — immutable, automatically cleaned up, and designed from the ground up for virtual threads.</p><pre>// Before Java 25 — ThreadLocal (mutable, leak-prone)<br>ThreadLocal&lt;String&gt; currentUser = new ThreadLocal&lt;&gt;();<br>currentUser.set(&quot;ram&quot;);<br>System.out.println(currentUser.get()); // &quot;ram&quot;<br>// Must remember to call remove() or it leaks<br><br>// Java 25 — ScopedValue (immutable, auto-cleaned)<br>ScopedValue&lt;String&gt; CURRENT_USER = ScopedValue.newInstance();<br><br>ScopedValue.where(CURRENT_USER, &quot;ram&quot;).run(() -&gt; {<br>    System.out.println(CURRENT_USER.get()); // &quot;ram&quot;<br>    processRequest(); // value is available anywhere in this scope<br>});<br>// Value automatically gone when scope exits — no cleanup needed</pre><p><strong>3. Flexible Constructor Bodies — Validation Before </strong><strong>super()<br></strong>Before Java 25, the first statement in any constructor that called a parent class had to be super(...) — no exceptions. This forced developers into awkward workarounds when they needed to validate or compute values before calling the superclass.</p><pre>// Before Java 25 — couldn&#39;t validate before super()<br>public class BankAccount extends Account {<br>    public BankAccount(double balance) {<br>        super(balance); // Must be first — can&#39;t validate balance here<br>    }<br>}<br><br>// Workaround — ugly static helper method<br>public BankAccount(double balance) {<br>    super(validate(balance)); // only way to sneak in logic<br>}<br><br>private static double validate(double balance) {<br>    if (balance &lt; 0) throw new IllegalArgumentException(&quot;Balance cannot be negative&quot;);<br>    return balance;<br>}<br><br>// Java 25 — natural, readable validation before super()<br>public class BankAccount extends Account {<br>    public BankAccount(double balance) {<br>        if (balance &lt; 0) throw new IllegalArgumentException(&quot;Balance cannot be negative&quot;);<br>        super(balance); // super() no longer required to be the first line<br>    }<br>}</pre><p><strong>4. Module Import Declarations — One Line Instead of Many<br></strong>Before Java 25, importing multiple classes meant writing multiple import statements. Java 25 introduced module import declarations — import an entire module’s packages in a single line.</p><pre>// Before Java 25 — verbose, repetitive imports<br>import java.util.List;<br>import java.util.Map;<br>import java.util.ArrayList;<br>import java.nio.file.Path;<br>import java.nio.file.Files;<br><br>// Java 25 — import the entire module in one line<br>import module java.base;<br><br>public class Main {<br>    void main() {<br>        //code<br>    }<br>}</pre><p>Beyond these language features, Java 25 also ships a built-in <strong>Key Derivation Function API</strong>, bringing production-grade password-based encryption directly into the standard library — no more relying on third-party libraries like Bouncy Castle to derive a secure encryption key.</p><p><strong>Summary<br></strong>Java 25 rounds off an extraordinary four-year evolution since Java 21. Compact Source Files removed the ceremony that made Java intimidating for beginners, Scoped Values replaced one of Java’s oldest concurrency pain points with something immutable and virtual-thread-friendly, Flexible Constructor Bodies eliminated a long-standing restriction that forced awkward workarounds, Module Import Declarations cut import boilerplate for everyday development, and the Key Derivation Function API brought production-grade cryptography into the standard library. Combined with significant GC improvements and runtime performance gains, Java 25 is a release that rewards both new developers and seasoned teams upgrading from Java 21.</p><h4><strong>Final Thoughts — Which Version Should You Be On?</strong></h4><p>Looking back at the journey from Java 8 to Java 25, one thing is clear — Java hasn’t just survived; it has transformed. Each LTS release didn’t just add features; it responded directly to what developers and enterprises were struggling with at the time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-mzwsTFzFE2ErT_ghGnGkw.png" /></figure><p><strong>Still on Java 8 or 11?</strong> You’re missing a decade of improvements — from records and sealed classes that eliminate boilerplate to virtual threads that make your servers scale effortlessly. The upgrade path is well-documented, and the payoff is significant.</p><p><strong>On Java 17?</strong> Java 21 is your natural next step. Virtual Threads alone are worth the upgrade for any I/O-heavy application, and pattern matching for switch will immediately clean up your most complex conditional logic.</p><p><strong>On Java 21?</strong> Java 25 is a smooth upgrade — no breaking changes, just meaningful additions. If you’re building new projects, there’s no reason not to start on Java 25 today.</p><blockquote><em>Java 30 years in is not the same language it was at 10. It’s faster, cleaner, safer, and more expressive than ever — and it’s just getting started. ☕</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a48205d9a0d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learning S3 by Building It: Concepts, Java Code, and the Errors I Actually Hit]]></title>
            <link>https://medium.com/@yramcharanteja/learning-s3-by-building-it-concepts-java-code-and-the-errors-i-actually-hit-ae1e306d3392?source=rss-e072c7cbc844------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae1e306d3392</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[amazon-s3]]></category>
            <category><![CDATA[aws-s3]]></category>
            <dc:creator><![CDATA[CodeCraft by Ramcharan]]></dc:creator>
            <pubDate>Wed, 08 Jul 2026 00:48:53 GMT</pubDate>
            <atom:updated>2026-07-31T03:31:01.403Z</atom:updated>
            <content:encoded><![CDATA[<h3>What Exactly Is an S3 Bucket? (The Absolute Basics)</h3><p>If you’re new to AWS, you’ve probably already created a bucket, uploaded a file, and thought — <em>“okay… but what did I actually just do?”</em></p><p>Let’s break it down in plain English before we go any deeper.</p><h4>S3 Stands for Simple Storage Service</h4><p>Think of S3 as an infinitely large hard drive sitting in the cloud. But here’s the catch — it doesn’t work like the folders on your laptop. S3 is what’s called <strong>object storage</strong>, not traditional file storage, and that difference is the key to understanding everything else.</p><h4>The Core Building Blocks</h4><p><strong>1. Buckets: </strong>A bucket is the top-level container — like the “drive” itself. A few rules to know:</p><ul><li>Bucket names must be <strong>globally unique</strong> across <em>all</em> of AWS, not just your account. That’s why simple names like mybucket are almost always taken.</li><li>Every bucket lives in a specific <strong>AWS region</strong> (like us-east-1) that you choose when you create it.</li><li>You <em>can</em> create what looks like folders inside a bucket, but technically… There aren’t any. Which brings us to:</li></ul><p><strong>2. Objects (Not Files): </strong>Everything you upload to S3 — an image, a video, a PDF — is called an <strong>object</strong>, not a file. Each object is made up of three things:</p><ul><li><strong>A key</strong> — this is the full “path” to the object, like photos/vacation/beach.jpg. There&#39;s no real folder structure behind the scenes; those slashes <em>look</em> like folders in the AWS console.</li><li><strong>The data</strong> — the actual bytes of whatever you uploaded.</li><li><strong>Metadata</strong> — extra details like content type, file size, and last-modified date.</li></ul><p>So when you upload a file, you’re really creating an <strong>object</strong> with a unique <strong>key</strong> inside your bucket.</p><p><strong>3. Permissions: </strong>By default, a new bucket — and everything inside it — is <strong>completely private</strong>. No one can access your object through a public link unless you explicitly allow it, through bucket policies, access control lists, or by intentionally making it public. AWS keeps this locked down by default for good reason.</p><p><strong>4. The Object URL: </strong>Every object gets a unique URL that looks something like this:</p><pre>https://your-bucket-name.s3.your-region.amazonaws.com/your-key</pre><p>But don’t be surprised if it returns “Access Denied” — that’s expected unless the object is public or you’re accessing it with valid credentials.</p><h4>So What Did You Actually Do?</h4><p>When you created a bucket and uploaded a file in the AWS console, here’s what really happened:</p><ol><li>You reserved a globally unique container name (the bucket) in a specific AWS region.</li><li>You created an object inside it — your file — with a key matching its filename.</li><li>That object is now stored durably (AWS automatically replicates it across multiple facilities) and is private by default, accessible only through the console, AWS CLI, or SDKs with proper credentials.</li></ol><p>That’s it. No servers to manage, no disks to worry about — just objects, sitting safely in a bucket, waiting to be used.</p><h4>S3 Permissions and Public Access, Explained Simply</h4><p>By default, every S3 bucket you create is <strong>private</strong>. No one can see or download your files unless you explicitly allow it. This is intentional — AWS would rather you accidentally lock yourself out than accidentally expose your data to the world.</p><p>To control who can access what, S3 uses three layers working together.</p><p><strong>1. Block Public Access — The Master Switch<br></strong>This is a safety override sitting above everything else. It doesn’t grant or deny specific access — it simply refuses to let <em>any</em> public access rule take effect, even a correct one.</p><p>By default, it’s <strong>ON</strong> for every new bucket. This is why beginners often write a perfect public access policy… and it still doesn’t work. AWS is silently blocking it a level above.</p><p><strong>Example — Hosting Public Website Images</strong></p><p>Say you’re hosting product images and any visitor, with no AWS account, needs to view them in their browser. You’d need to:</p><ol><li>Turn off Block Public Access for the bucket</li><li>Add a bucket policy allowing s3:GetObject to everyone (Principal: *)</li></ol><p><strong>2. Bucket Policy — The Rulebook on the Door<br></strong>A bucket policy is a set of rules attached directly to the bucket, saying who can do what — for example, <em>“anyone can read files here”</em> or <em>“only this AWS account can upload.”</em></p><p>It’s especially useful for granting access to people or services <strong>outside your own AWS account</strong>, since IAM can’t reach identities you don’t own.</p><p><strong>Example — Sharing Data with a Partner Company</strong></p><p>Say you need a partner’s separate AWS account to read files from a specific folder in your bucket. You’d add a bucket policy naming their account as the trusted principal, granting s3:GetObject. IAM can&#39;t do this — it only controls identities inside your own account — so the bucket policy fills that gap.</p><p><strong>3. IAM Policy — The ID Badge<br></strong>An IAM policy is attached to a specific <strong>user or role</strong> in your own AWS account, defining what that identity is allowed to do — like “this app can upload files, but can’t delete them.”</p><p>It controls access from the <em>person’s</em> side, not the bucket’s side, and only works for identities you own.</p><p><strong>Example — Your App Uploading Files</strong></p><p>Say your backend app needs to upload user profile pictures to a bucket, and only this app should be allowed to. You’d attach an IAM policy to the app’s role, granting s3:PutObject on that specific path. Since the app&#39;s identity lives inside your own account, IAM is the right tool — no bucket policy needed.</p><h4>Versioning: Keeping a History of Every Object</h4><p>By default, if you upload a file with the same name (key) as an existing one, S3 just <strong>overwrites it</strong>. The old version is gone. If you delete an object, it’s just… gone.</p><p>Versioning changes that. Once enabled on a bucket:</p><ul><li>Every time you upload a file with the same key, S3 keeps <strong>both</strong> the old and new copies, each with a unique <strong>Version ID</strong>.</li><li>When you “delete” an object, S3 doesn’t actually erase it — it adds a <strong>delete marker</strong> on top. The object is hidden from normal view, but the actual data is still there and recoverable.</li></ul><p><strong>Why this matters<br></strong>Imagine someone on your team accidentally overwrites config.json with the wrong file, or deletes it entirely. Without versioning, that data is gone. With versioning, you just restore the previous version — it never actually left.</p><p><strong>A few important details</strong></p><ul><li>Versioning is <strong>off by default</strong>. You have to explicitly enable it per bucket.</li><li>Once enabled, it <strong>cannot be fully disabled</strong> — only “suspended” (new objects stop getting versions, but old versions remain).</li><li>Every version counts toward storage costs. If you upload the same 1GB file 10 times, you’re storing 10GB, not 1GB — this surprises a lot of beginners on their AWS bill.</li><li>To permanently delete something in a versioned bucket, you have to delete the specific Version ID, not just the object name.</li></ul><h4>Storage Classes: Paying for What You Actually Need</h4><p>Not all data needs the same speed of access. S3 storage classes let you match your storage cost to how often (and how fast) you actually need to retrieve a file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3WBhNxWSrNco0AyU44PLuw.png" /></figure><p><strong>The mental model<br></strong>Think of it like storing physical items:</p><ul><li><strong>Standard</strong> = things on your desk, used daily</li><li><strong>Standard-IA</strong> = things in a nearby closet, used monthly</li><li><strong>Glacier Flexible</strong> = a storage unit across town, used yearly</li><li><strong>Glacier Deep Archive</strong> = a sealed box in an underground vault, used rarely</li></ul><p><strong>Why this matters practically<br></strong>You choose the storage class <strong>per object</strong> (or set rules to move objects automatically — that’s a “lifecycle rule,” which we can cover separately). A common real setup:</p><ul><li>New files → <strong>Standard</strong></li><li>After 30 days of no access → automatically move to <strong>Standard-IA</strong></li><li>After 90 days → move to <strong>Glacier</strong></li><li>After 7 years → <strong>Deep Archive</strong>, then eventually deleted</li></ul><p>This is how companies keep old logs, backups, or compliance data around for years without paying Standard pricing forever.</p><p><strong>One connection worth noting:</strong> versioning and storage classes interact. Every old version of a file still occupies storage and still gets billed at whatever storage class it’s in — which is exactly why lifecycle rules are often paired with versioning, to automatically move or expire old versions instead of leaving them in expensive Standard storage forever.</p><h4>Lifecycle Rules: Automating Storage Class Transitions and Cleanup</h4><p>A lifecycle rule is a set of instructions you attach to a bucket (or a specific folder/prefix) that tells S3: <em>“After X days, do Y automatically.”</em> No scripts, no manual work — S3 handles it in the background.</p><p><strong>What you can automate</strong></p><ol><li>Transition objects to cheaper storage classes</li><li>Expire (delete) objects entirely</li><li>Clean up old versions (if versioning is on)</li><li>Clean up incomplete uploads</li></ol><h4>Encryption: Protecting Data at Rest and in Transit</h4><p>Encryption in S3 has two distinct parts — this trips people up because “encryption” sounds like one setting, but it’s really two separate concerns.</p><p><strong>1. Encryption in Transit<br></strong>This protects data <strong>while it’s moving</strong> — between your computer/app and S3’s servers. S3 handles this via <strong>HTTPS/TLS</strong>, the same encryption your browser uses for secure websites.</p><ul><li>Almost always on by default when using the AWS console, CLI, or SDKs.</li><li>You can enforce it with a bucket policy that denies any request not using HTTPS (aws:SecureTransport: false → deny).</li></ul><p><strong>2. Encryption at Rest<br></strong>This protects data <strong>while it’s stored</strong> on AWS’s disks — so even if someone somehow got physical access to the storage hardware, the data would be unreadable without the encryption key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s1d2KYjnTEtnwoRizKXOuA.png" /></figure><p><strong>Access control versus Encryption<br>Access control</strong> → <em>who</em> is allowed to ask for the object</p><p><strong>Encryption</strong> → protecting the object <em>if the storage itself were somehow compromised</em></p><h4>Presigned URLs: Temporary Access Without Changing Any Policy</h4><p>Here’s the problem this solves: your bucket is private (as it should be), but you need to let <em>one specific person</em> download <em>one specific file</em> — just for a little while — without making the object public or creating a whole new IAM user for them.</p><p><strong>What a presigned URL actually is<br></strong>It’s a normal S3 object URL, but with extra parameters attached — a signature, an expiration time, and the identity that generated it. Something like:</p><pre>https://my-bucket.s3.amazonaws.com/report.pdf<br>  ?X-Amz-Signature=abc123...<br>  &amp;X-Amz-Expires=3600<br>  &amp;X-Amz-Credential=...</pre><p>Anyone with this link can access the object <strong>without needing any AWS account, IAM user, or bucket policy change</strong> — but only until it expires (in this example, 3600 seconds = 1 hour).</p><p><strong>How it works, conceptually</strong></p><ol><li>Someone with valid permissions (you or your app’s IAM role) generates the URL using their own credentials.</li><li>AWS “signs” the URL cryptographically using those credentials — proving whoever asked for it truly had permission at that moment.</li><li>When someone uses the link, S3 checks the signature and expiration. If valid and not expired, it serves the object as if the <em>original</em> credential-holder had requested it.</li><li>Once expired, the link stops working entirely — no manual revocation needed.</li></ol><p><strong>Why is this genuinely useful?</strong></p><ul><li><strong>Sharing a private file temporarily</strong> — e.g., emailing a client a link to a private invoice PDF that expires in 24 hours.</li><li><strong>Letting users upload directly to S3</strong> — e.g., your app generates a presigned URL for <em>uploading</em>, so the user’s browser sends the file straight to S3 instead of routing it through your server (saves bandwidth and server load).</li><li><strong>Avoiding permanent public access</strong> — you get the convenience of a shareable link without ever touching Block Public Access or bucket policies.</li></ul><p><strong>Key things to remember</strong></p><ul><li>The link inherits the permissions of whoever generated it — if their IAM role can’t read that object, the presigned URL won’t work either.</li><li>Expiration is the built-in safety net — max validity is 7 days when generated via IAM user/role credentials.</li><li>No AWS account is needed by the <em>recipient</em> — that’s the whole point.</li></ul><h4>Event Notifications: Letting S3 Tell Other Services When Something Happens</h4><p>S3 can proactively notify other services the moment something happens in a bucket — an upload, a delete, a restore from Glacier — instead of you polling to check.</p><p><strong>Event types:</strong> s3:ObjectCreated:*, s3:ObjectRemoved:*, s3:ObjectRestore:*, s3:Replication:* — scoped with prefix/suffix filters (e.g. only incoming-orders/*.csv).</p><p><strong>Destinations:</strong> SNS, SQS, or Lambda.</p><p><strong>Example: CSV Upload → Lambda Parses → SNS Fans Out<br></strong>A partner uploads orders.csv. You want each row published as its own event, so multiple independent systems can react</p><pre>S3 (orders.csv uploaded to incoming-orders/)<br>   │  triggers via event notification<br>   ▼<br>Lambda (parses CSV, publishes one SNS message per row)<br>   │<br>   ▼<br>SNS Topic: &quot;order-events&quot;<br>   ├── SQS Queue        → batch analytics worker pulls at its own pace<br>   ├── Lambda Function   → sends a real-time email confirmation<br>   └── Spring Boot App   → HTTPS subscriber, updates the orders database</pre><h4>Building an S3 Integration in Spring Boot: A Hands-On Java Walkthrough</h4><p>Understanding S3 concepts is one thing — actually wiring it into a real application is another. In this section, we’ll build a working Spring Boot microservice that performs full CRUD operations against S3, including automatic multipart upload for large files.</p><p><strong>What We’re Building<br></strong>A REST API with five capabilities:</p><ul><li><strong>Upload</strong> files (with automatic multipart handling for large files)</li><li><strong>Download</strong> files</li><li><strong>List</strong> objects in the bucket</li><li><strong>Read and update metadata</strong> on existing objects</li><li><strong>Delete</strong> objects (single and batch)</li></ul><p><strong>Project Setup<br></strong>Using Spring Boot 4 (Gradle), the key dependencies are the web starter, JSON support, and the AWS SDK v2:</p><p>gradle</p><pre>dependencies {<br>    implementation &#39;org.springframework.boot:spring-boot-starter-webmvc&#39;<br>    implementation &#39;org.springframework.boot:spring-boot-starter-jackson&#39;<br>    implementation &#39;org.springframework.boot:spring-boot-starter-validation&#39;<br>    implementation platform(&quot;software.amazon.awssdk:bom:2.25.60&quot;)<br>    implementation &#39;software.amazon.awssdk:s3&#39;<br>}</pre><p>The AWS SDK’s BOM (Bill of Materials) keeps every AWS module on a matching, compatible version — one less thing to track manually.</p><p><strong>Architecture</strong></p><pre>Client<br>  │  HTTP multipart/form-data<br>  ▼<br>S3Controller  (REST layer)<br>  │<br>  ▼<br>S3Service     (business logic, talks to AWS)<br>  │<br>  ▼<br>S3Config      (provides the S3Client bean)<br>  │<br>  ▼<br>AWS S3</pre><p><strong>Connecting to AWS the Right Way<br></strong>The most important design decision: <strong>never hardcode credentials</strong>. Instead, use the SDK’s DefaultCredentialsProvider, which automatically checks environment variables, a local credentials file, or an IAM role — in that order — with zero code changes needed between environments:</p><pre>@Bean<br>public S3Client s3Client() {<br>    return S3Client.builder()<br>            .region(Region.of(region))<br>            .credentialsProvider(DefaultCredentialsProvider.create())<br>            .build();<br>}</pre><p>Locally, this reads from ~/.aws/credentials. In production on EC2/ECS, the same code picks up credentials from an IAM role instead — no secrets ever touch the codebase.</p><p><strong>The Two Meanings of “Multipart” — A Common Point of Confusion</strong></p><p><strong>1. HTTP Multipart (</strong><strong>multipart/form-data)</strong> — how a client sends a file to <em>your</em> Spring Boot app. Spring parses this automatically into an MultipartFile object:</p><pre>@PostMapping(value = &quot;/upload&quot;, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)<br>public ResponseEntity&lt;?&gt; upload(@RequestParam(&quot;file&quot;) MultipartFile file, ...)</pre><p><strong>2. S3 Multipart Upload</strong> — a completely separate concept, describing how <em>your app</em> sends a large file to AWS by splitting it into chunks. This only kicks in for files above a size threshold:</p><pre>public String uploadFile(MultipartFile file, String key, Map&lt;String, String&gt; metadata) {<br>    return file.getSize() &gt; multipartThresholdBytes<br>            ? multipartUpload(file, key, metadata)   // split into parts<br>            : simpleUpload(file, key, metadata);     // single PutObject call<br>}</pre><p>The S3 multipart flow itself follows three steps: createMultipartUpload (get an upload ID), loop uploadPart for each chunk, then completeMultipartUpload to stitch them together. Critically, any failure mid-upload should trigger abortMultipartUpload — otherwise, orphaned parts sit in your bucket, quietly costing storage forever.</p><p><strong>Metadata: A Design Quirk Worth Knowing<br></strong>S3 has no API to edit metadata in place. The only way to change it is to copy the object onto itself with a “replace metadata” directive:</p><pre>CopyObjectRequest.builder()<br>        .sourceBucket(bucketName).sourceKey(key)<br>        .destinationBucket(bucketName).destinationKey(key)<br>        .metadata(newMetadata)<br>        .metadataDirective(MetadataDirective.REPLACE)<br>        .build();</pre><p><strong>Real Errors I Hit Building This Springboot Application<br>“Unable to load credentials from any of the providers in the chain”</strong><br>The AWS SDK checks several places for credentials — environment variables, a local credentials file, an instance role — and struck out on all of them.</p><p><strong>“Please resend this request to the specified temporary endpoint” (HTTP 307)</strong><br>This is S3 redirecting the request because the client is pointed at the wrong regional endpoint for the bucket.</p><p><strong>“User … is not authorized to perform: s3:ListBucket” (HTTP 403)</strong><br>Credentials and region were correct, but the IAM policy didn’t grant this specific action on this resource.</p><h4>Wrapping Up</h4><p>We went from the basics — what a bucket and an object actually are — to a working Spring Boot microservice that performs real CRUD operations against S3, including multipart uploads, metadata handling, and the real errors you’ll likely hit along the way.</p><p>The biggest takeaway: S3 rewards understanding its layers rather than memorizing commands — permissions are three layers working together, “multipart” means two different things, and metadata updates are really a copy in disguise. Once that clicks, S3 stops feeling like a black box.</p><p>Full source code for the Spring Boot integration is here:</p><p><a href="https://gitlab.com/CodeCraftByRamcharan/aws-springboot-demos/-/tree/main/springboot-s3-demo?ref_type=heads"><strong>GitLab: aws-springboot-demos</strong></a></p><p>Clone it, plug in your bucket name and credentials, and you should be uploading files in minutes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae1e306d3392" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Threads to Virtual Threads: The Evolution of Concurrency in Java]]></title>
            <link>https://medium.com/@yramcharanteja/from-threads-to-virtual-threads-the-evolution-of-concurrency-in-java-b33e7523dcc2?source=rss-e072c7cbc844------2</link>
            <guid isPermaLink="false">https://medium.com/p/b33e7523dcc2</guid>
            <category><![CDATA[java-concurrency]]></category>
            <category><![CDATA[executor-framework]]></category>
            <category><![CDATA[java-virtual-threads]]></category>
            <category><![CDATA[spring-boot-async]]></category>
            <category><![CDATA[java-backend-development]]></category>
            <dc:creator><![CDATA[CodeCraft by Ramcharan]]></dc:creator>
            <pubDate>Sun, 26 Apr 2026 18:43:55 GMT</pubDate>
            <atom:updated>2026-04-26T18:43:55.514Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Every Java application starts with a single thread. One waiter, one kitchen, one customer at a time.</p><p>That was fine in 2000. Web applications were simpler, user expectations were lower, and a server handling a few hundred requests per second was considered powerful.</p><p>Then the world changed. Microservices, real-time APIs, cloud-native systems — modern applications handle thousands of concurrent requests every second. The single waiter became a bottleneck. So Java gave us more waiters. Then better ways to manage them. Then smarter ways to coordinate them. And finally — in Java 21 — an entirely new kind of waiter that costs almost nothing.</p><p>This article walks the full journey:</p><ul><li>From raw <strong>Threads</strong> — the foundation</li><li>Through <strong>Executors</strong> — managing threads at scale</li><li>Into <strong>Future and CompletableFuture</strong> — async pipelines</li><li>Past <strong>Concurrent Collections</strong> — thread-safe data structures</li><li>All the way to <strong>Virtual Threads</strong> — the evolution Java has been building toward</li></ul><p>Whether you’re debugging a race condition in production or evaluating Project Loom for your next service, this guide gives you the mental model, the tools, and the real-world intuition to write safe, efficient, concurrent Java.</p><p>All code examples in this article are backed by a working Spring Boot project. You can explore the full implementation here: 🔗 <a href="https://github.com/CodeCraftByRamcharan/springboot-java-concurrency-demo">springboot-java-concurrency-demo</a></p><h3><strong>What is a Thread?</strong></h3><p>A <strong>thread</strong> is the smallest unit of execution in a program — a lightweight sub-process that can run tasks independently while sharing memory and resources with other threads in the same process.</p><p>Simply put, a thread is like a <strong>mini program</strong> inside a bigger one. Every Java application starts with a <strong>main thread</strong> (running the main() method), and you can create more threads to perform tasks concurrently.</p><p><strong>Analogy: </strong>Your program is a <strong>restaurant (process)</strong>, and each <strong>waiter (thread)</strong> serves a customer using the same <strong>kitchen (memory)</strong>. Multiple waiters working together make the restaurant faster and more efficient.</p><h4>Types of Threads</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gVcho0TJ2JBgmUUucaSd3g.png" /></figure><p>A <strong>thread</strong> in Java allows a program to execute multiple tasks concurrently, enabling <strong>multithreading</strong>. Multithreading is the ability of a program to run two or more threads simultaneously, improving efficiency and performance.</p><p><strong>Why Multithreading Matters:</strong><br> It maximizes <strong>CPU utilization</strong>, keeps applications <strong>responsive</strong>, and enables <strong>parallel execution</strong> on multiple cores, allowing tasks to complete faster.</p><h3>Thread Life Cycle in Java</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N6zR413jS-v7TQe54wsqCA.png" /></figure><p>🟠 <strong>New (Born State)</strong><br> A thread is created using new Thread() but hasn’t started yet.<br> It’s just an object — no system resources are allocated.<br> 👉 Moves to <strong>Runnable</strong> when start() is called.</p><p>🟢 <strong>Runnable (Ready to Run)</strong><br> The thread is ready for execution and waiting for CPU scheduling.<br> The JVM thread scheduler decides when it gets CPU time.<br> 👉 Once scheduled, it enters the <strong>Running</strong> state.</p><p>🔵 <strong>Running (Active Execution)</strong><br> The thread is currently executing its run() method.<br> It can move to <strong>Waiting</strong>, <strong>Blocked</strong>, or <strong>Terminated</strong> based on events like <strong>I/O operations</strong>, <strong>sleep</strong>, or <strong>task completion</strong>.</p><p>🔴 <strong>Blocked</strong><br> The thread is waiting to acquire a monitor lock (for example, when entering a synchronized block).<br> 👉 Moves back to <strong>Runnable</strong> when the lock is released.</p><p>🟡 <strong>Timed Waiting / Waiting</strong><br> The thread becomes inactive either for a specific duration due to methods like sleep(time), wait(timeout), or join(timeout),<br> or remains waiting indefinitely until another thread <strong>notifies</strong> it.<br> 👉 After the waiting time or notification, it returns to <strong>Runnable</strong>.</p><p>⚫ <strong>Terminated (Dead)</strong><br> The thread has completed execution or exited due to an error.<br> It <strong>cannot be restarted</strong> once it reaches this state.</p><h3>Concurrency Hazards in Java</h3><p>When multiple threads execute simultaneously, they can sometimes interfere with each other in unexpected ways. These issues are subtle and can be hard to detect, but understanding them is key to writing safe, efficient multithreaded programs.</p><h4>Deadlock</h4><p>Occurs when two or more threads are waiting indefinitely for resources held by each other.<br><em>Analogy:</em> Two database transactions each lock different tables and then try to access the table locked by the other. Both transactions wait forever, and the system gets stuck.</p><h4>Race Condition</h4><p>Happens when the outcome of a program depends on the timing or order of thread execution.<br><em>Analogy:</em> Two threads simultaneously try to apply a discount to the same e-commerce order. Depending on which thread executes first, the final order total may be incorrect.</p><h4>Data Race</h4><p>A special kind of race condition where threads read and write shared data concurrently without proper synchronization. This can lead to corrupted or inconsistent data.<br><em>Analogy:</em> Two users update the same profile settings at the same time. One update may overwrite the other, leaving inconsistent user data.</p><h4>Starvation</h4><p>When a thread never gets CPU time because other threads with higher priority constantly take resources.<br><em>Analogy:</em> A background reporting job never executes because the main transactional threads always take priority, causing delays in analytics.</p><h4>Livelock</h4><p>Threads are active but cannot make progress because they keep reacting to each other’s actions.<br><em>Analogy:</em> Two services keep retrying each other’s failed requests in a loop. Both remain active, but nothing progresses, consuming CPU and network resources.</p><h3>Java Concurrency Tools: Managing Threads Safely</h3><p>Java provides several mechanisms to help threads work together safely, avoid hazards, and coordinate access to shared resources. Here’s a detailed look:</p><p><strong>1. Join: </strong>The join() method allows one thread to wait for another to finish before continuing.<br>Analogy: In an e-commerce system, the <strong>email notification thread</strong> waits for the <strong>payment processing thread</strong> to finish.</p><p><strong>2. Interruption: </strong>Threads can be interrupted to signal a stop or cancel a task gracefully.<br>Analogy: A background <strong>reporting service</strong> is interrupted if the server shuts down to avoid partially written reports.</p><p><strong>3. Synchronization: </strong>The synchronized keyword ensures only one thread accesses a critical section at a time.<br>Analogy: Two threads updating the same <strong>bank account</strong> must do it sequentially to prevent wrong totals.</p><p><strong>4. Volatile: </strong>volatile ensures updates to a variable are visible to all threads immediately.<br>Analogy: A f<strong>eature flag</strong> in a live application must reflect the latest state for all threads.</p><p><strong>5. Atomic Variables: </strong>Atomic classes (e.g., AtomicInteger) allow thread-safe operations without explicit synchronization.<br>Analogy: Counting <strong>page views</strong> on a high-traffic website; multiple threads can increment safely.<br>- <strong>Difference from volatile:</strong> volatile ensures visibility but not atomicity; Atomic provides atomic read-modify-write operations.</p><p><strong>6. Happens-Before: </strong>Happens-before defines ordering and visibility guarantees between operations.<br>Analogy: In a <strong>task queue</strong>, a job must be enqueued before it’s dequeued to ensure threads see it in order.</p><p><strong>7. Wait/Notify and Producer-Consumer: </strong>wait() and notify() allow threads to communicate about resource availability.<br>Analogy: A <strong>producer</strong> adds log entries; a <strong>consumer</strong> waits for new logs to process.</p><p><strong>8. Lock and ReentrantLock: </strong>A Lock controls access to a shared resource. ReentrantLock allows a thread to acquire the same lock multiple times and optionally ensures fairness.<br>Analogy: Only one thread can update an <strong>account</strong> at a time, but the same thread can re-enter safely if needed.</p><p><strong>9. ReadWriteLock: </strong>Allows multiple threads to <strong>read</strong> a resource simultaneously, but only <strong>one thread can write</strong> at a time.<br>Analogy: Multiple services can fetch a user profile from a database at the same time, but only one service can update it to prevent inconsistent data.</p><p><strong>10. Semaphore: </strong>Controls access to a <strong>limited number of resources</strong>. Threads acquire a permit before proceeding.<br>Analogy: In a web server, only a fixed number of threads can handle simultaneous database connections; additional requests wait until a connection is free.</p><p><strong>11. CyclicBarrier: </strong>Lets a group of threads <strong>wait for each other</strong> at a barrier before proceeding.<br>Analogy: In a batch processing system, multiple threads prepare parts of a report, and the final report is generated only when all threads finish their part.</p><p><strong>12. CountDownLatch: </strong>Allows threads to <strong>wait until a set of operations is complete</strong>.<br>Analogy: In a microservices architecture, a service waits for all dependent services to initialize before starting to process requests.</p><p><strong>13. Exchanger: </strong>Let <strong>two threads exchange data safely</strong>.<br>Analogy: Two services exchange configuration data at runtime — each must be ready to send and receive for consistency.</p><p><strong>14. Phaser: </strong>A flexible barrier for synchronizing threads in <strong>phases</strong>, allowing threads to <strong>arrive and leave dynamically</strong>.<br>Analogy: In a simulation system, different modules compute in phases; each phase proceeds only when all participating modules complete their computations, but modules can join or leave in different phases.</p><h3>Creating and Running Threads</h3><p>Java provides multiple ways to create and run threads. Here are the most common approaches:</p><h4>1. Extending Thread</h4><p>Create a thread by extending the Thread class and overriding its run() method.</p><pre>class MyThread extends Thread {<br>    public void run() {<br>        System.out.println(&quot;Thread running via Thread class&quot;);<br>    }<br>}<br><br>public class Main {<br>    public static void main(String[] args) {<br>        MyThread t1 = new MyThread();<br>        t1.start(); // starts the thread<br>    }<br>}</pre><p><strong>Key Point:</strong> Simple, but limits inheritance (your class cannot extend another class).</p><h4>2. Implementing Runnable</h4><p>Implement the Runnable interface and pass it to a Thread object.</p><pre>class MyRunnable implements Runnable {<br>    public void run() {<br>        System.out.println(&quot;Thread running via Runnable&quot;);<br>    }<br>}<br><br>public class Main {<br>    public static void main(String[] args) {<br>        Thread t1 = new Thread(new MyRunnable());<br>        t1.start();<br>    }<br>}</pre><p><strong>Best Practice:</strong> Decouples the task from the thread, more flexible than extending Thread.</p><h4>3. Implementing Callable</h4><p>Callable is similar to Runnable but <strong>returns a result</strong> and can <strong>throw exceptions</strong>.</p><pre>import java.util.concurrent.*;<br><br>class MyCallable implements Callable&lt;Integer&gt; {<br>    public Integer call() {<br>        return 42; // task result<br>    }<br>}<br><br>public class Main {<br>    public static void main(String[] args) throws Exception {<br>        ExecutorService executor = Executors.newSingleThreadExecutor();<br>        Future&lt;Integer&gt; result = executor.submit(new MyCallable());<br>        System.out.println(&quot;Result: &quot; + result.get());<br>        executor.shutdown();<br>    }<br>}</pre><p><strong>Use Case:</strong> When you need a <strong>return value</strong> or exception handling from a thread.</p><h4>4. Using Lambda Expressions</h4><p>For concise code, Java 8+ allows lambdas with Runnable or Callable.</p><pre>public class Main {<br>    public static void main(String[] args) {<br>        Thread t1 = new Thread(() -&gt; System.out.println(&quot;Thread running via Lambda&quot;));<br>        t1.start();<br>    }<br>}</pre><h4>Best Practices</h4><ul><li>Prefer <strong>Runnable</strong> for simple, background tasks.</li><li>Use <strong>Callable + ExecutorService</strong> for tasks that return results.</li><li>Use <strong>Lambda expressions</strong> for small, concise tasks.</li><li>Always start threads with start() rather than calling run() directly.</li><li>Avoid extending Thread unless necessary.</li></ul><h3>Thread Priorities and Thread Groups</h3><h4>Thread Priorities</h4><p>Java threads can have priorities to hint at their importance to the scheduler. Higher-priority threads are <em>more likely</em> to run first — but this is never guaranteed. The JVM and underlying OS make the final scheduling decision, and behavior can vary significantly across platforms.</p><p><strong>Priority Levels:</strong></p><p>🟡 Thread.MIN_PRIORITY = 1</p><p>🔵 Thread.NORM_PRIORITY = 5 (default)</p><p>🔴 Thread.MAX_PRIORITY = 10</p><pre>Thread lowPriority = new Thread(() -&gt; System.out.println(&quot;Background task&quot;));<br>lowPriority.setPriority(Thread.MIN_PRIORITY);<br><br>Thread highPriority = new Thread(() -&gt; System.out.println(&quot;Critical task&quot;));<br>highPriority.setPriority(Thread.MAX_PRIORITY);<br><br>lowPriority.start();<br>highPriority.start();<br>// highPriority is likely to run first — but not guaranteed</pre><p><strong>When to use priorities:</strong> Sparingly. A good use case is deprioritizing background tasks (logging, analytics) relative to user-facing operations. Never rely on priorities for correctness — use proper synchronization instead. Misusing priorities can cause <strong>starvation</strong>, where low-priority threads never get CPU time.</p><h4>Thread Groups</h4><p>A ThreadGroup is like a folder for threads — it lets you organize, monitor, and control multiple threads collectively.</p><pre>ThreadGroup group = new ThreadGroup(&quot;OrderProcessors&quot;);<br><br>Thread t1 = new Thread(group, () -&gt; System.out.println(&quot;Processing order 1&quot;));<br>Thread t2 = new Thread(group, () -&gt; System.out.println(&quot;Processing order 2&quot;));<br><br>t1.start();<br>t2.start();<br><br>System.out.println(&quot;Active threads in group: &quot; + group.activeCount());<br>group.interrupt(); // interrupts all threads in the group at once</pre><p><strong>Key Points:</strong></p><ul><li>Threads in the same group can be interrupted, listed, or monitored together</li><li>Thread groups can be nested, forming a hierarchy</li><li>group.activeCount() gives a live count of running threads in the group</li></ul><p>⚠️ <strong>Modern Java note:</strong> ThreadGroup is largely obsolete — many of its methods are deprecated and unsafe. Prefer ExecutorService to manage related tasks, or StructuredTaskScope (Java 21+) for proper lifecycle control.</p><h3>Executors</h3><p><strong>The Problem: Manual Thread Creation Doesn’t Scale</strong></p><p>Creating threads in Java is simple at first, either by extending Thread or implementing Runnable. This works well for small applications where the number of tasks is limited.</p><p>However, in real-world applications, every task may spin up a new thread. Since threads consume memory and CPU resources, too many of them slow the system down. There’s also no built-in way to limit how many threads run at once or reuse existing ones — making load management in larger applications difficult.</p><p><strong>The Solution: Thread Pool</strong></p><p>Instead of creating a new thread for every task, a thread pool maintains a fixed set of worker threads. Each incoming task is assigned to an available thread. When a thread finishes, it isn’t destroyed — it’s reused for the next task.</p><p><strong>Executor Hierarchy Overview</strong></p><p><strong>a. </strong><strong>Executor — &quot;Just get this job done; I don&#39;t care how.&quot;</strong><br><strong><em>Scenario: Fire-and-forget logging system</em></strong><br>Every user action needs to be logged, but logging shouldn’t slow down the main flow. You just want to delegate: <em>“Run this whenever possible — I don’t care about threads or results.”</em></p><pre>Executor executor = Runnable::run;<br><br>executor.execute(() -&gt; System.out.println(&quot;User clicked button - logged&quot;));</pre><p>You submit work — nothing more. No result tracking, no queuing control, no lifecycle management.</p><p>👉 Executor is a black box runner. Useful as a foundation, not as a standalone tool.</p><p><strong>b. </strong><strong>ExecutorService — &quot;I want a worker team, and I care about results.&quot;</strong></p><p><strong><em>Scenario: Logging with tracking and control</em></strong></p><p>Now logging matters more — you want to confirm it completed, catch failures, or support retries.</p><pre>ExecutorService executor = Executors.newFixedThreadPool(2);<br><br>Future&lt;?&gt; future = executor.submit(() -&gt; {<br>    System.out.println(&quot;Logging action: user_checkout&quot;);<br>    // write to file / DB<br>});<br><br>future.get(); // wait for confirmation<br>System.out.println(&quot;Request handled&quot;);<br><br>executor.shutdown(); // always shut down when done</pre><p>What’s different from raw Executor:</p><ul><li>You get a Future to track the task</li><li>You can wait (.get()), cancel, or check status</li><li>You control the thread pool size and reuse</li><li>You can handle errors and shut down cleanly</li></ul><p><strong>c. </strong><strong>ScheduledExecutorService — &quot;Run this later or repeatedly.&quot;</strong></p><p><strong><em>Scenario: Bank interest calculation or retry system</em></strong></p><p>Some tasks need to run based on time — not just “as soon as possible.”</p><pre>ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);<br><br>// One-time delay: retry a failed task after 10 seconds<br>scheduler.schedule(() -&gt;<br>    System.out.println(&quot;Retrying failed task...&quot;), 10, TimeUnit.SECONDS);<br><br>// Periodic: calculate interest every 24 hours<br>scheduler.scheduleAtFixedRate(() -&gt;<br>    System.out.println(&quot;Calculating daily interest...&quot;), 0, 24, TimeUnit.HOURS);<br><br>scheduler.shutdown();</pre><p><strong>Use cases: </strong>scheduled jobs (cron-style), retry mechanisms with backoff, periodic background tasks (cleanup, monitoring)</p><p><strong>d. </strong><strong>ThreadPoolExecutor — &quot;A custom-built workforce factory.&quot;</strong></p><p><strong><em>Scenario: High-traffic ticket booking system</em></strong></p><p>During peak load, thousands of requests arrive at once. You need precise control over how many threads run, how many tasks wait, and what happens when the system is overwhelmed.</p><pre>ThreadPoolExecutor executor = new ThreadPoolExecutor(<br>    5,                           // corePoolSize    — always-available workers<br>    10,                          // maximumPoolSize — max threads during peak load<br>    60,                          // keepAliveTime   — idle extra threads live this long<br>    TimeUnit.SECONDS,            // unit<br>    new LinkedBlockingQueue&lt;&gt;(100) // workQueue    — tasks wait here when all cores are busy<br>);<br><br>executor.execute(() -&gt; System.out.println(&quot;Booking ticket...&quot;));<br>executor.shutdown();</pre><p>Extra threads beyond corePoolSize are only created when the queue is full, and are retired after keepAliveTime if idle.</p><p><strong><em>e. ForkJoinPool — “Split big work into smaller pieces and conquer.”</em></strong></p><p><strong>e. </strong><strong>ForkJoinPool — &quot;Split big work into smaller pieces and conquer.&quot;</strong></p><p><strong><em>Scenario: Parallel sum of a large dataset</em></strong></p><p>Instead of one thread processing a million records from start to finish, it ForkJoinPool splits the work recursively, runs pieces in parallel, then combines the results.</p><pre>ForkJoinPool pool = new ForkJoinPool();<br><br>int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8};<br><br>int sum = pool.invoke(new RecursiveTask&lt;Integer&gt;() {<br>    protected Integer compute() {<br>        // split → solve in parallel → combine<br>        return Arrays.stream(numbers).parallel().sum();<br>    }<br>});<br><br>System.out.println(&quot;Sum: &quot; + sum);<br>pool.shutdown();</pre><p>Best suited for CPU-bound, divide-and-conquer problems — like sorting, searching, or processing large collections.</p><p><strong>Common Thread Pool Factories (</strong><strong>Executors Utility Class)</strong></p><ol><li><strong>newFixedThreadPool(n)</strong> → Fixed number of threads — excess tasks wait in queue.</li><li><strong>newCachedThreadPool() </strong>→ Creates new threads as needed, reuses idle threads.</li><li><strong>newSingleThreadExecutor()</strong> → Single worker thread — executes tasks sequentially.</li><li><strong>newScheduledThreadPool(n)</strong> → Supports scheduled and periodic tasks.</li><li><strong>newVirtualThreadPerTaskExecutor()</strong> (Java 21+)→ Creates lightweight virtual threads per task — massive concurrency.</li></ol><h3>Future and CompletableFuture</h3><h4>Future — “I’ll give you the result later, but you must keep checking.”</h4><p><strong>Scenario: Online food delivery tracking</strong></p><p>Imagine you order food from an app. The restaurant starts preparing it in the background, but you don’t receive it immediately. Instead, you get a <strong>tracking token</strong> — you can check whether it’s ready, or cancel it if needed. That tracking token is exactly what a Future represents in Java.</p><p>A Future represents the result of an asynchronous computation that will be available at some point in the future.</p><pre>ExecutorService executor = Executors.newFixedThreadPool(2);<br><br>Future&lt;Integer&gt; future = executor.submit(() -&gt; {<br>    return 10 + 20;<br>});<br><br>Integer result = future.get(); // Blocks until result is ready<br>System.out.println(result);   // 30<br><br>// Useful methods<br>future.isDone();        // Returns true if the task completed<br>future.isCancelled();   // Returns true if the task was cancelled<br>future.cancel(true);    // Attempts to cancel the task<br>future.get(5, TimeUnit.SECONDS); // Waits max 5 seconds, then throws TimeoutException</pre><p><strong>Limitations</strong></p><ul><li><strong>Blocking nature</strong> — future.get() blocks the calling thread until the task finishes. Your thread sits idle, doing nothing.</li><li><strong>No chaining</strong> — Imagine validating payment, updating inventory, and sending a confirmation email — each step depending on the previous. WithFuture, you must call .get() after each step and manually start the next one. The flow is sequential and blocking, not a smooth pipeline.</li><li><strong>No composition</strong> — You cannot combine multiple Future results together without blocking on each one individually.</li><li><strong>No timeout safety by default</strong> — If a task hangs, future.get() hangs indefinitely with it. You can pass a timeout with future.get(5, TimeUnit.SECONDS), but there&#39;s no built-in way to define a fallback if it expires.</li></ul><p>👉 All four of these limitations are exactly what CompletableFuture were designed to solve.</p><h4>CompletableFuture — “Don’t wait… just tell what to do next.”</h4><p><strong>Scenario: Order processing system (non-blocking flow)</strong></p><p>A user places an order. Your system needs to validate payment, update inventory, and send a confirmation email — each step depending on the previous one. But you don’t want threads sitting idle waiting for each step to finish.</p><p>CompletableFuture solves this. It represents a future result <em>and</em> lets you define what happens next — turning a blocking chain into a smooth, non-blocking pipeline.</p><p><strong>runAsync vs </strong><strong>supplyAsync</strong></p><p>runAsync — “Run task, no result.”</p><p>supplyAsync — “Run task and return result.”</p><pre>// runAsync — fire a task, no result needed<br>CompletableFuture.runAsync(() -&gt; sendAuditLog());<br><br>// supplyAsync — fire a task and return a result<br>CompletableFuture.supplyAsync(() -&gt; validatePayment());</pre><p><strong>Core Features</strong></p><ul><li><strong>Non-blocking pipelines</strong> — No .get() blocking; threads are free to do other work while waiting.</li><li><strong>Chaining</strong> — Steps execute automatically in sequence; each receives the previous result.</li><li><strong>Composition</strong> — Combine multiple independent async tasks and merge their results.</li><li><strong>Exception handling</strong> — Recover from failures mid-pipeline without crashing the chain.</li><li><strong>Parallel orchestration</strong> — Run independent tasks concurrently and coordinate their completion.</li></ul><pre>| Capability            | Future        | CompletableFuture |<br>| --------------------- | ------------- | ----------------- |<br>| Blocking              | Yes (`get()`) | No (non-blocking) |<br>| Chaining              | ❌             | ✅                 |<br>| Composition           | ❌             | ✅                 |<br>| Callbacks             | ❌             | ✅                 |<br>| Exception handling    | Poor          | Clean             |<br>| Parallel coordination | Manual        | Built-in          |</pre><p><strong>Advanced Features of CompletableFuture</strong></p><ol><li>thenApply— “Transform the result”: Takes result → transforms it → passes to next step.</li><li>thenCompose — “Chain dependent async tasks”: Use when the next step depends on the previous result.</li><li>thenCombine — “Combine two independent results”: Use when tasks are independent, but results must be merged.</li><li>allOf — “Wait for all tasks to complete”: Waits for ALL futures.</li><li>anyOf — “Proceed when ANY one completes”: Return the first completed result and ignore the slower ones.</li><li>thenAccept — “Consume result (no return)”: Uses the result but does not return anything</li><li>thenRun — “Run something after completion (no input, no output)”: Runs the next step, no data passed.</li><li>exceptionally — “Fallback on error.”</li><li>handle — “Always run (success or failure).”</li></ol><pre>// thenApply — Transform the result<br>CompletableFuture.supplyAsync(() -&gt; &quot;ram&quot;)<br>    .thenApply(name -&gt; name.toUpperCase());<br><br>// thenCompose — Chain dependent async tasks<br>// Use when the next step needs the previous result<br>CompletableFuture.supplyAsync(() -&gt; validatePayment())<br>    .thenCompose(paymentId -&gt;<br>        CompletableFuture.supplyAsync(() -&gt; updateInventory(paymentId))<br>    );<br><br>// thenCombine — Combine two independent results<br>CompletableFuture&lt;String&gt; userFuture  = CompletableFuture.supplyAsync(() -&gt; getUser());<br>CompletableFuture&lt;String&gt; orderFuture = CompletableFuture.supplyAsync(() -&gt; getOrders());<br><br>userFuture.thenCombine(orderFuture, (user, orders) -&gt; user + &quot; &quot; + orders);<br><br>// allOf — Wait until ALL futures complete<br>CompletableFuture&lt;Void&gt; all = CompletableFuture.allOf(future1, future2, future3);<br>all.thenRun(() -&gt; System.out.println(&quot;All services completed&quot;));<br><br>// anyOf — Proceed when the FIRST future completes<br>CompletableFuture&lt;Object&gt; fastest = CompletableFuture.anyOf(future1, future2, future3);<br>fastest.thenAccept(result -&gt; System.out.println(&quot;Fastest result: &quot; + result));<br><br>// thenAccept — Consume result, no return<br>CompletableFuture.supplyAsync(() -&gt; getUser())<br>    .thenAccept(user -&gt; sendEmail(user));<br><br>// thenRun — Run next step, no data passed<br>CompletableFuture.supplyAsync(() -&gt; processOrder())<br>    .thenRun(() -&gt; System.out.println(&quot;Order completed&quot;));<br><br>// exceptionally — Fallback on error<br>CompletableFuture.supplyAsync(() -&gt; processPayment())<br>    .exceptionally(ex -&gt; {<br>        System.out.println(&quot;Error: &quot; + ex.getMessage());<br>        return false;<br>    });<br><br>// handle — Always runs (success or failure)<br>CompletableFuture.supplyAsync(() -&gt; processPayment())<br>    .handle((result, ex) -&gt; {<br>        if (ex != null) return false;<br>        return result;<br>    });</pre><p><strong>Production tip:</strong> By default, it CompletableFuture uses the common ForkJoinPool. For real applications, always pass your own executor to control thread count and avoid resource contention</p><h3>Virtual Threads — “Millions of workers, almost for free.”</h3><p><strong><em>The Problem with Platform Threads</em></strong></p><p>Every traditional Java thread maps <strong>1-to-1 with an OS thread</strong>. OS threads are expensive:</p><ul><li>Each consumes <strong>~1MB of stack memory</strong></li><li>They’re slow to create and destroy</li><li>Most of the time, they’re just <strong>blocked on I/O</strong> — waiting for a DB query, an HTTP response, a file read — doing absolutely nothing useful</li></ul><p>A server handling 10,000 concurrent requests needs 10,000 OS threads. At 1MB each, that’s <strong>10GB of memory</strong> just for threads sitting idle.</p><p>This is the problem Virtual Threads solve.</p><p><strong><em>What Are Virtual Threads?</em></strong></p><p>Virtual Threads were introduced as part of <strong>Project Loom</strong>, becoming generally available in <strong>Java 21</strong>.</p><p>They are <strong>lightweight threads managed by the JVM</strong> — not the OS. The JVM runs them on top of a small pool of OS threads called <strong>carrier threads</strong>.</p><pre>| Feature                 | Platform Threads | Virtual Threads                             |<br>| ----------------------- | ---------------- | ------------------------------------------- |<br>| **Thread Type**         | OS-level threads | JVM-managed lightweight threads             |<br>| **Managed by**          | Operating System | JVM (Project Loom)                          |<br>| **Memory per thread**   | ~1 MB (stack)    | Few KB (grows/shrinks dynamically)          |<br>| **Max practical count** | Thousands        | Millions                                    |<br>| **Creation cost**       | Expensive        | Very cheap                                  |<br>| **Best for**            | CPU-bound work   | I/O-bound work                              |<br>| **Blocking behavior**   | OS thread blocks | Thread is *parked*, carrier thread is freed |</pre><p><strong><em>The Magic — Mounting and Unmounting</em></strong></p><p>This is the core mechanism that makes virtual threads powerful.</p><p>When a virtual thread <strong>blocks on I/O</strong>, it <em>unmounts</em> from its carrier thread. The carrier is immediately free to pick up another virtual thread. When the I/O completes, the virtual thread <em>mounts</em> back onto any available carrier and resumes.</p><pre>// Platform thread — OS thread is stuck the entire time<br>OS Thread → [working] → [blocked on DB... waiting... waiting...] → [resumes]<br>❌ Carrier is occupied. No other task can use it.<br><br>// Virtual thread — carrier is freed during the wait<br>Virtual Thread → [working] → [blocks on DB]<br>                                    ↓<br>                           unmounts from carrier<br>                                    ↓<br>                      carrier picks up another virtual thread<br>                                    ↓<br>                  DB responds → mounts back → resumes<br>✅ Carrier is never idle. Thousands of virtual threads share a few carriers.</pre><pre>// 1. Simple creation<br>Thread vt = Thread.ofVirtual().start(() -&gt; System.out.println(&quot;Hello from virtual thread&quot;));<br><br>// 2. Named — useful for debugging<br>Thread vt = Thread.ofVirtual()<br>                  .name(&quot;order-processor&quot;)<br>                  .start(() -&gt; processOrder());<br><br>// 3. Best for servers — one virtual thread per task, no pool sizing needed<br>ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor();<br><br>executor.submit(() -&gt; handleRequest()); // virtual thread 1<br>executor.submit(() -&gt; handleRequest()); // virtual thread 2<br>executor.submit(() -&gt; handleRequest()); // millions possible — no bottleneck<br><br>executor.shutdown();</pre><p>Notice what’s gone: <strong>no pool sizing</strong>. With platform threads, you’d agonize over newFixedThreadPool(50) vs newFixedThreadPool(200). With virtual threads, you just submit. The JVM handles everything.</p><p><strong><em>The Gotcha — Pinning</em></strong></p><p>A virtual thread gets <strong>pinned</strong> to its carrier when it cannot unmount. This happens in two situations:</p><ol><li>Inside a synchronized block</li><li>When calling native/foreign methods</li></ol><p>Pinning doesn’t break correctness — your code still works. But the carrier thread gets stuck, killing the performance benefit.</p><pre>// ❌ Pinned — virtual thread cannot unmount during dbQuery()<br>synchronized (lock) {<br>    dbQuery(); // carrier is stuck here<br>}<br><br>// ✅ Use ReentrantLock instead — virtual thread CAN unmount<br>ReentrantLock lock = new ReentrantLock();<br>lock.lock();<br>try {<br>    dbQuery(); // carrier is freed during the wait<br>} finally {<br>    lock.unlock();<br>}</pre><p>⚠️ <strong>Practical tip:</strong> Audit your code for synchronized blocks around I/O operations when adopting virtual threads. JDK 23+ is actively working to eliminate synchronized pinning entirely.</p><p><strong><em>When to Use Virtual Threads</em></strong></p><p>✅ <strong>Great fit — I/O-bound tasks:</strong></p><ul><li>REST API request handlers</li><li>Database queries</li><li>HTTP client calls (external APIs)</li><li>File reads and writes</li><li>Microservices talking to other services</li></ul><p>⚠️ <strong>Not the right tool — CPU-bound tasks:</strong></p><ul><li>Sorting, encryption, image processing, ML inference</li><li>Use ForkJoinPool or a fixed platform thread pool instead</li></ul><p><strong><em>Rule of thumb:</em></strong><em> If your thread spends most of its time </em>waiting<em>, virtual threads will help. If it spends most of its time </em>computing<em>, it won’t.</em></p><p><strong><em>Structured Concurrency — “Manage virtual threads like a team, not loose threads.”</em></strong></p><p><strong>Scenario:</strong> Processing an e-commerce order</p><p>When a user places an order, your system needs to run three independent tasks simultaneously:</p><ul><li>Validate payment</li><li>Reserve inventory</li><li>Notify the warehouse</li></ul><p>With traditional approaches, if one task fails, the others keep running — wasting resources and leaving the system in an inconsistent state. <strong>Structured Concurrency</strong>, introduced in <strong>Java 21</strong> via StructuredTaskScope, solves this.</p><p>The idea: <strong>a group of tasks lives and dies together</strong>. If one fails, the rest are automatically cancelled. No orphan threads, no resource leaks.</p><pre>import java.util.concurrent.StructuredTaskScope;<br><br>public String processOrder(String orderId) throws Exception {<br><br>    try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {<br><br>        // Fork three tasks — each runs on its own virtual thread<br>        StructuredTaskScope.Subtask&lt;String&gt; payment   =<br>                scope.fork(() -&gt; validatePayment(orderId));<br><br>        StructuredTaskScope.Subtask&lt;String&gt; inventory =<br>                scope.fork(() -&gt; reserveInventory(orderId));<br><br>        StructuredTaskScope.Subtask&lt;String&gt; warehouse =<br>                scope.fork(() -&gt; notifyWarehouse(orderId));<br><br>        scope.join();           // wait for all three<br>        scope.throwIfFailed();  // if any failed, throw — cancels the rest<br><br>        return payment.get() + &quot; | &quot; + inventory.get() + &quot; | &quot; + warehouse.get();<br>    }<br>}</pre><pre>| Behavior                            | What it means                                                                                 |<br>| ----------------------------------- | --------------------------------------------------------------------------------------------- |<br>| `scope.fork()`                      | Starts a new child task (typically as a virtual thread)                                       |<br>| `scope.join()`                      | Waits for all forked tasks to complete                                                        |<br>| **Shutdown on Failure**             | If any task fails → remaining tasks are cancelled                                             |<br>| **Shutdown on Success**             | Returns as soon as a successful result is obtained (in “race” style scopes)                   |<br>| **Auto-close (try-with-resources)** | Scope automatically closes → ensures all threads are completed or cancelled, preventing leaks |</pre><p>Virtual threads let you write simple, familiar, blocking-style code — and get the scalability of reactive/async programming without any of the complexity.</p><p><strong><em>Virtual Threads + CompletableFuture — Why It’s Not the Best Combination</em></strong></p><p>At first glance, combining them seems powerful. In practice, <strong>they solve the same problem in different ways</strong> — and mixing them creates unnecessary complexity.</p><p><strong>CompletableFuture was born out of scarcity.</strong> Threads were expensive, so it invented an elaborate pipeline — thenApply, thenCompose, allOf — to avoid leaving threads idle. The complexity was the price you paid for performance.</p><p><strong>Virtual threads were born out of abundance.</strong> Threads are now so cheap you can have millions. The original problem CompletableFuture was solving — threads are too expensive to block — simply doesn&#39;t exist anymore.</p><p><em>Analogy:</em> CompletableFuture is an elaborate ticket-passing system invented when a restaurant only had 5 waiters. Virtual threads give you unlimited waiters. You don&#39;t need the ticket system anymore — it&#39;s just overhead that confuses everyone.</p><pre>// ❌ Mixing both — looks right, behaves unexpectedly<br>CompletableFuture<br>    .supplyAsync(() -&gt; validatePayment(), virtualExecutor)  // ✅ virtual thread<br>    .thenApply(result -&gt; updateInventory(result))           // ⚠️ silently switches to ForkJoinPool<br>    .thenApply(result -&gt; sendEmail(result));                // ⚠️ still on ForkJoinPool<br><br>// ✅ Virtual threads alone — simple, readable, scales to millions<br>try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {<br>    executor.submit(() -&gt; {<br>        String payment   = validatePayment();<br>        String inventory = updateInventory(payment);<br>        String email     = sendEmail(inventory);<br>    });<br>}</pre><p>The result of mixing them: you get all the complexity of CompletableFuture pipelines with none of the simplicity that virtual threads promise. Stack traces become fragmented, error handling splits across two models, and your code is harder to read than if you&#39;d just picked one approach.</p><blockquote><em>💡 </em><strong><em>Rule of thumb:</em></strong><em> On Java 21+, write simple blocking code and let virtual threads handle the scaling. Keep </em><em>CompletableFuture for legacy codebases or older Java versions — but don&#39;t combine the two.</em></blockquote><blockquote><em>⚠️ The danger of mixing isn’t that it crashes — it’s that it </em><strong><em>silently doesn’t work the way you think it does.</em></strong><em> That’s the worst kind of bug.</em></blockquote><h3>Concurrent Collections — “Shared data, no chaos.”</h3><p><strong><em>Why Not Just Use Regular Collections?</em></strong></p><pre>// ❌ NOT thread-safe — two threads updating simultaneously = corrupted data<br>Map&lt;String, Integer&gt; stock = new HashMap&lt;&gt;();<br>stock.put(&quot;item-1&quot;, 100); // Thread 1<br>stock.put(&quot;item-1&quot;, 99);  // Thread 2 — may overwrite incorrectly</pre><p>Regular collections like HashMap, ArrayList, and LinkedList were never designed for concurrent access. Using them across threads without synchronization leads to data corruption, missed updates, and unpredictable results.</p><p>You could wrap them with synchronized — but that locks the <strong>entire collection</strong> for every operation, killing performance.</p><p>Concurrent collections solve this with <strong>fine-grained locking</strong> or <strong>lock-free algorithms</strong> — only the affected part of the collection is locked, not the whole thing.</p><h4>1. ConcurrentHashMap — &quot;Many readers, safe writers.&quot;</h4><p><em>Analogy:</em> A warehouse with 16 aisles. Multiple workers can update <strong>different aisles simultaneously</strong> — only the specific aisle being updated is briefly locked, not the whole warehouse.</p><pre>ConcurrentHashMap&lt;String, Integer&gt; stock = new ConcurrentHashMap&lt;&gt;();<br><br>// Multiple threads can read/write safely — no explicit synchronization needed<br>stock.put(&quot;item-1&quot;, 100);<br>stock.put(&quot;item-2&quot;, 50);<br><br>// Atomic check-then-act — safe without synchronized block<br>stock.putIfAbsent(&quot;item-3&quot;, 75);<br><br>// Atomic increment — no race condition<br>stock.merge(&quot;item-1&quot;, -1, Integer::sum);<br><br>System.out.println(stock.get(&quot;item-1&quot;)); // 99</pre><p><strong>Key behaviours:</strong></p><ul><li>Reads are <strong>non-blocking</strong> — multiple threads read simultaneously with no locking</li><li>Writes lock only the <strong>affected segment</strong>, not the whole map</li><li>putIfAbsent(), merge(), compute() are <strong>atomic</strong> — safe without extra synchronization</li><li>null Keys and values are <strong>not allowed</strong></li></ul><blockquote><em>⚠️ </em><em>size() is approximate under concurrent modification — don&#39;t rely on it for critical logic.</em></blockquote><h4>2. CopyOnWriteArrayList — &quot;Read freely, write carefully.&quot;</h4><p><em>Analogy:</em> A notice board in the warehouse. Workers can read it anytime without waiting. When a manager updates it, they <strong>print a fresh copy</strong> of the entire board, make the change, and swap it in. Readers always see a consistent snapshot.</p><pre>CopyOnWriteArrayList&lt;String&gt; orders = new CopyOnWriteArrayList&lt;&gt;();<br><br>orders.add(&quot;order-1&quot;);<br>orders.add(&quot;order-2&quot;);<br><br>// Safe to iterate while another thread adds — no ConcurrentModificationException<br>for (String order : orders) {<br>    System.out.println(order); // reads the snapshot, not the live list<br>}<br><br>orders.add(&quot;order-3&quot;); // creates a new internal copy — safe but expensive</pre><p><strong>Key behaviours:</strong></p><ul><li>Every <strong>write</strong> creates a full copy of the underlying array — expensive</li><li>Every <strong>read and iteration</strong> is completely lock-free</li><li>Best when reads are <strong>very frequent</strong>, writes are <strong>rare</strong></li></ul><blockquote><em>⚠️ Never use for write-heavy workloads — copying the entire array on every write is costly.</em></blockquote><h4>3. ConcurrentLinkedQueue — &quot;Lock-free, high-speed queue.&quot;</h4><p><em>Analogy:</em> A conveyor belt where workers can add items to the back and take items from the front simultaneously — no one ever waits for a gate to open.</p><pre>ConcurrentLinkedQueue&lt;String&gt; taskQueue = new ConcurrentLinkedQueue&lt;&gt;();<br><br>// Producer threads — add tasks<br>taskQueue.offer(&quot;task-1&quot;);<br>taskQueue.offer(&quot;task-2&quot;);<br><br>// Consumer threads — take tasks<br>String task = taskQueue.poll(); // returns null if empty — never blocks<br>System.out.println(&quot;Processing: &quot; + task);</pre><p><strong>Key behaviours:</strong></p><ul><li><strong>Non-blocking</strong> — offer() and poll() never wait</li><li>Uses a <strong>lock-free algorithm</strong> internally — extremely fast under high contention</li><li>poll() returns null If empty — always check before using</li></ul><h4>4. Blocking Queues — “Wait if empty, wait if full.”</h4><p>Blocking queues are the backbone of the <strong>Producer-Consumer pattern</strong>. Unlike ConcurrentLinkedQueue, They can <strong>pause a thread</strong> when the queue is empty (consumer waits) or full (producer waits) — instead of returning null or throwing an exception.</p><p><strong>LinkedBlockingQueue</strong> — optionally bounded, linked nodes</p><p><em>Analogy:</em> An order inbox with a maximum capacity. New orders wait outside if the inbox is full. Processors wait at the inbox if it’s empty.</p><pre>LinkedBlockingQueue&lt;String&gt; queue = new LinkedBlockingQueue&lt;&gt;(10); // max 10 tasks<br><br>// Producer — blocks if queue is full<br>queue.put(&quot;order-1&quot;); // waits if queue full<br><br>// Consumer — blocks if queue is empty<br>String order = queue.take(); // waits until something arrives<br>System.out.println(&quot;Processing: &quot; + order);</pre><p><strong>ArrayBlockingQueue</strong> — strictly bounded, array-backed</p><p><em>Analogy:</em> A fixed-size loading dock. Exactly N trucks can park at once — no exceptions.</p><pre>ArrayBlockingQueue&lt;String&gt; queue = new ArrayBlockingQueue&lt;&gt;(5); // strictly 5 slots<br><br>queue.put(&quot;shipment-1&quot;);   // blocks if all 5 slots are full<br>queue.offer(&quot;shipment-2&quot;); // returns false immediately if full — non-blocking alternative<br><br>String shipment = queue.take(); // blocks if empty</pre><p><strong>Key difference from</strong><strong>LinkedBlockingQueue:</strong> capacity is <strong>mandatory and fixed</strong> at creation. Better memory predictability.</p><p><strong>PriorityBlockingQueue</strong> — unbounded, priority-ordered</p><p><em>Analogy:</em> A hospital triage queue. Critical patients are always seen first, regardless of arrival order.</p><pre>PriorityBlockingQueue&lt;String&gt; queue = new PriorityBlockingQueue&lt;&gt;();<br><br>queue.put(&quot;LOW-priority-task&quot;);<br>queue.put(&quot;HIGH-priority-task&quot;);<br>queue.put(&quot;MEDIUM-priority-task&quot;);<br><br>System.out.println(queue.take()); // HIGH-priority-task — natural ordering</pre><p>⚠️ <strong>Unbounded</strong> — never blocks the producer. Only blocks the consumer when empty. Use with caution in high-throughput systems to avoid memory issues.</p><h4>5. Producer-Consumer Pattern</h4><p>The Producer-Consumer pattern is the most common use of blocking queues — producers generate work, consumers process it, and the queue buffers between them so neither side has to wait for the other directly.</p><p><em>Analogy:</em> A restaurant kitchen. Waiters (producers) place orders on a ticket rail. Chefs (consumers) take tickets and cook. The rail (queue) decouples them — waiters don’t wait at the kitchen, chefs don’t chase waiters for orders.</p><pre>LinkedBlockingQueue&lt;String&gt; orderQueue = new LinkedBlockingQueue&lt;&gt;(10);<br><br>// Producer — waiter taking orders<br>Runnable producer = () -&gt; {<br>    try {<br>        for (int i = 1; i &lt;= 5; i++) {<br>            String order = &quot;Order-&quot; + i;<br>            orderQueue.put(order);             // blocks if queue full<br>            System.out.println(&quot;Placed: &quot; + order);<br>        }<br>    } catch (InterruptedException e) {<br>        Thread.currentThread().interrupt();<br>    }<br>};<br><br>// Consumer — chef processing orders<br>Runnable consumer = () -&gt; {<br>    try {<br>        while (true) {<br>            String order = orderQueue.take();  // blocks if queue empty<br>            System.out.println(&quot;Cooking: &quot; + order);<br>        }<br>    } catch (InterruptedException e) {<br>        Thread.currentThread().interrupt();<br>    }<br>};<br><br>Thread producerThread = new Thread(producer);<br>Thread consumerThread = new Thread(consumer);<br><br>producerThread.start();<br>consumerThread.start();</pre><pre>| Collection                | Blocking? | Best For                                    | Avoid When                               |<br>| ------------------------- | --------- | ------------------------------------------- | ---------------------------------------- |<br>| **ConcurrentHashMap**     | ❌ No      | High-performance concurrent reads/writes    | You need `null` keys/values              |<br>| **CopyOnWriteArrayList**  | ❌ No      | Read-heavy workloads                        | Write-heavy workloads                    |<br>| **ConcurrentLinkedQueue** | ❌ No      | High-throughput, lock-free task passing     | You need backpressure / bounded capacity |<br>| **LinkedBlockingQueue**   | ✔ Yes     | Producer-consumer (flexible size)           | Unbounded usage → memory risk            |<br>| **ArrayBlockingQueue**    | ✔ Yes     | Fixed-capacity queues, backpressure control | You need dynamic resizing                |<br>| **PriorityBlockingQueue** | ✔ Yes*    | Priority-based task scheduling              | You need strict capacity limits          |</pre><p><strong>Rule of thumb:</strong> If threads only <strong>read</strong> shared data, a regular collection volatile may suffice. If threads <strong>read and write</strong>, always reach for a concurrent collection over a synchronized wrapper. The performance difference at scale is significant</p><h3>Conclusion</h3><p>We started with a restaurant and one waiter.</p><p>We ended with millions of virtual waiters — each so lightweight that spinning one up costs almost nothing, each smart enough to step aside the moment they’re waiting for the kitchen.</p><p><strong>Evolution of Java Concurrency — Refined Table</strong></p><pre>| Era     | Tool                   | What It Solved                                               | What It Left Behind                                             |<br>| ------- | ---------------------- | ------------------------------------------------------------ | --------------------------------------------------------------- |<br>| Java 1  | Thread                 | Basic concurrency, parallel execution                        | Heavyweight (OS threads), hard to manage manually               |<br>| Java 5  | ExecutorService        | Thread pooling, lifecycle management, task abstraction       | Still tied to OS threads, risk of misconfigured pools           |<br>| Java 5  | Future                 | Track async task result                                      | Blocking (`get()`), no composition, limited error handling      |<br>| Java 8  | CompletableFuture      | Non-blocking pipelines, chaining, async composition          | Complex APIs, harder debugging and readability                  |<br>| Java 5+ | Concurrent Collections | Thread-safe data structures without manual locking           | Doesn’t eliminate all synchronization needs                     |<br>| Java 21 | Virtual Threads        | Lightweight threads, massive scalability (millions of tasks) | Pinning risks with blocking synchronized/IO, requires awareness |<br>| Java 21 | StructuredTaskScope    | Structured concurrency, safe task grouping and cancellation  | Still evolving, not yet widely adopted                          |</pre><p>Each tool in this list wasn’t invented in isolation. Each one was a direct response to a limitation in the one before it. That’s what makes Java concurrency an <em>evolution</em> — not a collection of random APIs, but a continuous effort to make concurrent programming safer, simpler, and more scalable.</p><p><strong>What should you actually use today?</strong></p><ul><li><strong>New Java 21+ project, I/O-bound workload</strong> → Virtual Threads. Write blocking code and let the JVM handle the rest.</li><li><strong>Need to coordinate a group of tasks with lifecycle control</strong> → StructuredTaskScope.</li><li><strong>Legacy codebase on Java 8–17</strong> → CompletableFuture with a well-tuned ThreadPoolExecutor.</li><li><strong>Shared data across threads</strong> → Always reach for a concurrent collection over a synchronized wrapper.</li><li><strong>CPU-heavy parallel work</strong> → ForkJoinPool.</li></ul><p><strong>One last thing.</strong></p><p>The most common mistake developers make with concurrency isn’t picking the wrong tool. It’s reaching for complexity before they need it. Start with the simplest model that works. Virtual threads have made that simpler model — plain, blocking, sequential code — genuinely production-ready for the first time.</p><p>The restaurant now has unlimited waiters. You just have to remember not to handcuff them to the table.</p><p>If this article helped you, consider sharing it with someone who’s still manually sizing thread pools. They deserve to know about virtual threads, too.</p><p>Want to run all of this yourself? The full Spring Boot demo project is on GitHub: <a href="https://github.com/CodeCraftByRamcharan/springboot-java-concurrency-demo">springboot-java-concurrency-demo</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b33e7523dcc2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn React Hooks by Understanding How They Work]]></title>
            <link>https://medium.com/@yramcharanteja/learn-react-hooks-by-understanding-how-they-work-ae85432326f5?source=rss-e072c7cbc844------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae85432326f5</guid>
            <category><![CDATA[react-cusom-hooks]]></category>
            <category><![CDATA[react-hook-usereducer]]></category>
            <category><![CDATA[usestate-hook]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[react-usememo]]></category>
            <dc:creator><![CDATA[CodeCraft by Ramcharan]]></dc:creator>
            <pubDate>Wed, 08 Apr 2026 15:19:39 GMT</pubDate>
            <atom:updated>2026-04-08T15:19:39.177Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>What are Hooks?</strong></h4><p>Hooks are special built-in functions introduced in <strong>React 16.8</strong> that allow functional components to use React features like <strong>state</strong> and <strong>lifecycle behavior</strong>.</p><p>In simple terms, Hooks let you “hook into” React features without writing class components.</p><p>Before Hooks, functional components were limited — they couldn’t <strong>manage state or use lifecycle</strong> methods. With Hooks, these limitations were removed, making functional components more powerful and flexible.</p><h4><strong>Why Hooks?</strong></h4><p>Hooks were introduced to simplify React development and improve code reuse:</p><ul><li>✅ Use state and side effects without classes</li><li>✅ Write cleaner and more readable code</li><li>✅ Reuse logic easily using custom Hooks</li><li>✅ Reduce boilerplate compared to class components</li></ul><blockquote><em>⚠️</em><strong><em> Note:</em></strong><em> Hooks don’t exactly “replace” class components — they provide a simpler alternative. Class components are still supported but less commonly used in modern React.</em></blockquote><h4><strong>Rules of Hooks</strong></h4><p>To ensure Hooks work correctly, follow these two important rules:</p><ol><li><strong>Only call Hooks at the top level</strong><br> Don’t call Hooks inside loops, conditions, or nested functions.<br> This ensures React can track Hook calls consistently.</li><li><strong>Only call Hooks from React functions(</strong>Functional components or Custom Hooks).</li></ol><h4>Why Hooks Should Not Be Called in Loops, Conditions, or Nested Functions</h4><p><strong>Simple idea: </strong>React identifies Hooks <strong>by the order in which they are called</strong>, not by their name.</p><p>🔁 Hook Order Rule (in simple terms)</p><p>On every render, React expects Hooks to be called in the <strong>same order</strong>.</p><p>Example of correct usage:</p><pre>function MyComponent() {<br>  const [count, setCount] = useState(0);   // Hook 1<br>  const [name, setName] = useState(&quot;&quot;);    // Hook 2<br>  // same order every render ✅<br>}</pre><p><strong><em>❌ What goes wrong with conditions?</em></strong></p><pre>function MyComponent() {<br>  if (someCondition) {<br>    useState(0); // ❌ Hook inside condition<br>  }<br>  useState(&quot;&quot;); // Another hook<br>}</pre><p>Problem:</p><ul><li>First render → condition is trueHook order: [Hook1, Hook2]</li><li>Next render → condition is falseHook order: [Hook2]</li></ul><p>Now React gets confused because:</p><ul><li>It expects Hook1 at position 1</li><li>But Hook2 moved into position 1</li></ul><p><strong><em>Why does this break things?</em> </strong>React stores Hook data internally like this:</p><pre>Render 1 → [countState, nameState]<br>Render 2 → [???, nameState]</pre><p>Since React matches Hooks <strong>by position</strong>, not name:</p><ul><li>State values get mixed up</li><li>You may see bugs or errors like:</li></ul><blockquote><em>“Hooks must be called in the same order on every render”</em></blockquote><h4>Types of Hooks</h4><p>Hooks in React can be broadly categorized into:</p><ul><li><strong>Built-in Hooks</strong> (provided by React)</li><li><strong>Custom Hooks</strong> (created by developers)</li></ul><p><strong>Built-in Hooks:</strong> React provides several built-in Hooks for different use cases. For better understanding, we can group them as follows:</p><p><strong><em>🔹 Basic Hooks (Most commonly used): </em></strong>These are the Hooks you’ll use in almost every React application: <strong>useState, useEffect,</strong> and <strong>useContext</strong></p><p><strong><em>🔹 Additional Hooks: </em></strong>Used for more specific optimizations and advanced state handling: <strong>useReducer, useRef, useMemo, </strong>and <strong>useCallback</strong></p><p><strong><em>🔹 Advanced / Modern Hooks: </em></strong>These Hooks are used in more advanced scenarios, especially with <strong>concurrent features and modern React (18+)</strong>:</p><ul><li><strong>useTransition</strong> — Handle non-urgent UI updates</li><li><strong>useDeferredValue</strong> — Defer updating a value for performance</li><li><strong>useId</strong> — Generate unique IDs (useful for accessibility)</li><li><strong>useSyncExternalStore</strong> — Subscribe to external stores</li></ul><p><strong>Newer React Hooks (React 18/19+ and modern frameworks):</strong></p><ul><li><strong>useInsertionEffect</strong> — For CSS-in-JS libraries</li><li><strong>useActionState</strong> — Manage form actions (React 19)</li><li><strong>useOptimistic</strong> — Optimistic UI updates</li><li><strong>useFormStatus</strong> — Track form submission status</li></ul><p><strong><em>Custom Hooks: </em></strong>User-defined<strong> Hooks</strong> that allow you to reuse logic across components.</p><p>A custom Hook:</p><ul><li>It&#39;s just a JavaScript function</li><li>Must start with <strong>use</strong></li><li>Can call other Hooks inside it</li></ul><h4>useState Hook</h4><p>It is a Hook that allows functional components to <strong>store and manage state</strong>.</p><pre>  //Syntax<br>  const [state, setState] = useState(initialValue);    <br><br>  const[count, setCount] = useState(0);<br>  const[name, setName] = useState(&quot;David&quot;);<br>  const [time, setTime] = useState(new Date().toLocaleTimeString());</pre><ul><li><strong>state</strong> → current value</li><li><strong>setState</strong> → function used to update the value</li><li><strong>initialValue</strong> → the value used only during the first render</li></ul><h4>useEffect Hook</h4><p>useEffect allows you to perform <strong>side effects</strong> in functional components.</p><p>Side effects include: <strong>API calls</strong>, <strong>Subscriptions</strong>, <strong>Timers </strong>(setTimeout, setInterval), and <strong>DOM </strong>updates</p><p>In <strong>class components</strong>, side effects were handled using: componentDidMount, componentDidUpdate, componentWillUnmount</p><p>It runs <strong>after the component renders</strong>.</p><p>Think of it as, <em>“Run this code after render, and clean it up if needed.”</em></p><p><strong>Dependency Array: </strong>It<strong> </strong>is the <strong>second argument</strong> of useEffect. It controls <strong>when the effect runs</strong>.</p><pre>//No dependency<br>useEffect(() =&gt; {<br>  // runs every time<br>});<br><br>//Empty array []<br>useEffect(() =&gt; {<br>  // runs once<br>}, []);<br><br>//With dependencies [count, name]<br>useEffect(() =&gt; {<br>  // runs when count or name changes<br>}, [count, name]);<br><br>//Example<br>useEffect(() =&gt; {<br>  const interval = setInterval(() =&gt; {<br>    console.log(&quot;Running...&quot;);<br>  }, 1000);<br><br>  return () =&gt; clearInterval(interval); // cleanup<br>}, []);</pre><p><strong>Execution Order of useEffect</strong></p><ul><li><strong>Effects run:</strong> top → bottom (in the order they are written)</li><li><strong>Cleanup runs:</strong> bottom → top (reverse order)</li></ul><h4>useContext Hook</h4><p>useContext is a Hook that allows you to <strong>access data from a Context directly</strong> inside a functional component.</p><p>It helps to avoid <strong>prop drilling</strong> (passing data through multiple components unnecessarily).</p><pre>import React from &quot;react&quot;;<br>import { useContext, createContext } from &quot;react&quot;;<br><br><br>// create the context<br>const UserContext = createContext();<br><br><br>export default function Dashbord({user}){<br>    &lt;UserContext.Provider value={user}&gt;<br>        &lt;Sidebar/&gt;<br>    &lt;/UserContext.Provider&gt;<br>}<br><br><br>export function Sidebar(){<br>    return &lt;Profile/&gt;;<br>}<br><br><br>export function Profile(){<br>    const user = useContext(UserContext);<br>    return &lt;h1&gt;Hello, {user.name}&lt;/h1&gt;<br>}</pre><h4>useRef Hook</h4><p>useRef is a Hook that lets you <strong>store a mutable value</strong> that persists across re-renders <strong>without causing a re-render when it changes</strong>.</p><p><strong>Simple Understanding: </strong><em>“Store a value that stays the same between renders, but doesn’t trigger re-render when updated.”</em></p><pre>//Example 1<br>import { useRef, useEffect } from &quot;react&quot;;<br><br>export default function LoginForm() {<br>  const inputRef = useRef(null);<br><br>  useEffect(() =&gt; {<br>    inputRef.current.focus(); // focus input on mount<br>  }, []);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;input ref={inputRef} placeholder=&quot;Enter username&quot; /&gt;<br>      &lt;button&gt;Login&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>//Example 2<br>import { useState, useRef, useEffect } from &quot;react&quot;;<br><br>export default function SearchBox() {<br>  const [query, setQuery] = useState(&quot;&quot;);<br>  const prevQuery = useRef(&quot;&quot;);<br><br>  useEffect(() =&gt; {<br>    if (prevQuery.current !== query) {<br>      console.log(&quot;Search changed from&quot;, prevQuery.current, &quot;to&quot;, query);<br>      prevQuery.current = query; // manually update ref<br>    }<br>  }, [query]);<br><br>  return (<br>    &lt;input<br>      value={query}<br>      onChange={(e) =&gt; setQuery(e.target.value)}<br>    /&gt;<br>  );<br>}</pre><pre>| Feature            | useRef                 | useState |<br>| ------------------ | ---------------------- | -------- |<br>| Triggers re-render | ❌ No                   | ✅ Yes    |<br>| Stores value       | ✅ Yes (`.current`)     | ✅ Yes    |<br>| Use case           | DOM, persistent values | UI state |</pre><h4>useReducer Hook</h4><p>useReducer is a React Hook used to manage <strong>complex state logic</strong> in functional components.</p><p>It is an alternative to useState, especially when:</p><ul><li>State updates depend on the previous state</li><li>State logic is complex</li><li>Multiple state values are related</li></ul><pre>const [state, dispatch] = useReducer(reducer, initialState);</pre><p>Parameters:</p><ul><li><strong>reducer</strong> → A function that defines how state changes based on an action</li><li><strong>initialState</strong> → The starting state</li></ul><p>Returns:</p><ul><li><strong>state</strong> → Current state value</li><li><strong>dispatch</strong> → Function to send an action to update the state</li></ul><pre>import { useReducer } from &quot;react&quot;;<br><br>function counterReducer(state, action) {<br>  switch (action.type) {<br>    case &quot;increment&quot;:<br>      return { count: state.count + 1 };<br><br>    case &quot;decrement&quot;:<br>      return { count: state.count - 1 };<br><br>    default:<br>      return state;<br>  }<br>}<br><br>export default function Counter() {<br>  const [state, dispatch] = useReducer(counterReducer, { count: 0 });<br><br>  return (<br>    &lt;&gt;<br>      &lt;p&gt;Count: {state.count}&lt;/p&gt;<br>      &lt;button onClick={() =&gt; dispatch({ type: &quot;increment&quot; })}&gt;<br>        +<br>      &lt;/button&gt;<br>      &lt;button onClick={() =&gt; dispatch({ type: &quot;decrement&quot; })}&gt;<br>        -<br>      &lt;/button&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><pre>| Feature     | useState       | useReducer                     |<br>| ----------- | -------------- | ------------------------------ |<br>| Complexity  | Simple state   | Complex state logic            |<br>| Logic       | Inline         | Centralized (reducer function) |<br>| Scalability | Limited        | Better for large apps          |<br>| Pattern     | Direct updates | Action-based (Redux-like)      |</pre><p>Key Concepts</p><ol><li>Reducer Function: A pure function that decides how the state changes</li></ol><p>2. Dispatch: A function used to send actions</p><p>3. Action: An object that describes <strong>what happened</strong></p><h4>useCallback Hook</h4><p>useCallback is a Hook used to <strong>memoize a function</strong> so that the same function reference is preserved between renders.</p><p>Why is useCallback needed?</p><p>In React:</p><ul><li>Every time a component re-renders, <strong>functions inside it are recreated</strong></li><li>This means they get a <strong>new reference</strong> every time</li></ul><p>The Problem</p><p>When you pass a function as a prop:</p><ul><li>React.memo prevents re-rendering if props don’t change</li><li>But functions are <strong>new on every render</strong>, even if the logic is the same</li></ul><p>So React thinks:</p><blockquote><em>“Props changed → re-render child”</em></blockquote><p>This leads to <strong>unnecessary re-renders</strong>, especially if the child is heavy.</p><pre>//Problem Example<br>import React, { useState } from &quot;react&quot;;<br>import FunctionalComponentWithoutuseCallbackChild from &quot;./FunctionalComponentWithoutuseCallbackChild&quot;;<br><br>export default function FunctionalComponentWithoutuseCallbackParent() {<br>  const [count, setCount] = useState(0);<br>  const [text, setText] = useState(&quot;&quot;);<br><br>  // Function defined inside component<br>  const handleClick = () =&gt; {<br>    setCount(count + 1);<br>  };<br><br>  console.log(&quot;Parent rendered&quot;);<br><br>  return (<br>    &lt;div style={{ border: &quot;2px solid blue&quot;, padding: &quot;10px&quot; }}&gt;<br>      &lt;h2&gt;Count: {count}&lt;/h2&gt;<br>      &lt;input<br>        type=&quot;text&quot;<br>        placeholder=&quot;Type something...&quot;<br>        value={text}<br>        onChange={(e) =&gt; setText(e.target.value)}<br>      /&gt;<br>      &lt;FunctionalComponentWithoutuseCallbackChild onClick={handleClick} /&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>import React from &quot;react&quot;;<br><br>function FunctionalComponentWithoutuseCallbackChild({ onClick }) {<br>  console.log(&quot;Child rendered&quot;);<br>  return (<br>    &lt;button onClick={onClick} style={{ marginTop: &quot;10px&quot; }}&gt;<br>      Increment from Child<br>    &lt;/button&gt;<br>  );<br>}<br><br>//Solution<br>import React, { useState } from &quot;react&quot;;<br>import FunctionalComponentWithoutuseCallbackChild from &quot;./FunctionalComponentWithoutuseCallbackChild&quot;;<br><br>export default function FunctionalComponentWithoutuseCallbackParent() {<br>  const [count, setCount] = useState(0);<br>  const [text, setText] = useState(&quot;&quot;);<br><br>  // With callback Hooks<br>    const handleClick = useCallback(() =&gt; {<br>    setCount(count + 1);<br>  }, []);<br><br>  console.log(&quot;Parent rendered&quot;);<br><br>  return (<br>    &lt;div style={{ border: &quot;2px solid blue&quot;, padding: &quot;10px&quot; }}&gt;<br>      &lt;h2&gt;Count: {count}&lt;/h2&gt;<br>      &lt;input<br>        type=&quot;text&quot;<br>        placeholder=&quot;Type something...&quot;<br>        value={text}<br>        onChange={(e) =&gt; setText(e.target.value)}<br>      /&gt;<br>      &lt;FunctionalComponentWithoutuseCallbackChild onClick={handleClick} /&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>import React from &quot;react&quot;;<br><br>function FunctionalComponentWithoutuseCallbackChild({ onClick }) {<br>  console.log(&quot;Child rendered&quot;);<br>  return (<br>    &lt;button onClick={onClick} style={{ marginTop: &quot;10px&quot; }}&gt;<br>      Increment from Child<br>    &lt;/button&gt;<br>  );<br>}<br><br><br>export default React.memo(FunctionalComponentWithoutuseCallbackChild); // memoized child</pre><p>Dependency Array</p><ul><li><strong>[] (empty)</strong><br> → Function is created <strong>once</strong> and reused forever</li><li><strong>[a, b]</strong><br> → Function is recreated when <strong>a or b changes</strong></li><li><strong>No dependency array</strong> ❌<br> → Function is recreated on every render (no memoization)</li></ul><h4>useMemo Hook</h4><p>useMemo is a Hook used to <strong>memoize the result of a computation</strong>.</p><p>It ensures that a value is only recalculated when its <strong>dependencies change</strong>, helping improve performance in expensive operations.</p><p>Without useMemo:</p><ul><li>Any calculation inside a component runs <strong>on every render</strong></li><li>Even if the inputs haven’t changed</li><li>This can slow down the app for <strong>expensive calculations</strong></li></ul><pre>//Problem<br>import React, { useState } from &quot;react&quot;;<br><br>export default function FunctionalComponentuseMemo() {<br>  const [count, setCount] = useState(0);<br>  const [text, setText] = useState(&quot;&quot;);<br><br>  // Expensive calculation every render<br>  const expensiveValue = (() =&gt; {<br>    console.log(&quot;Calculating...&quot;);<br>    let total = 0;<br>    for (let i = 0; i &lt; 1e7; i++) {<br>      total += i;<br>    }<br>    return total + count;<br>  })();<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Expensive value: {expensiveValue}&lt;/p&gt;<br>      &lt;button onClick={() =&gt; setCount(c =&gt; c + 1)}&gt;Increment&lt;/button&gt;<br>      &lt;input value={text} onChange={e =&gt; setText(e.target.value)} /&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>//Solution<br>import React, { useState } from &quot;react&quot;;<br><br>export default function FunctionalComponentuseMemo() {<br>  const [count, setCount] = useState(0);<br>  const [text, setText] = useState(&quot;&quot;);<br><br>// using useMemo Hooks<br>   const expensiveValue = useMemo(() =&gt; {<br>    console.log(&quot;Calculating...&quot;);<br>    let total = 0;<br>    for (let i = 0; i &lt; 1e7; i++) {<br>      total += i;<br>    }<br>    return total + count;<br>  }, [count]); // only recalculates when count changes<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Expensive value: {expensiveValue}&lt;/p&gt;<br>      &lt;button onClick={() =&gt; setCount(c =&gt; c + 1)}&gt;Increment&lt;/button&gt;<br>      &lt;input value={text} onChange={e =&gt; setText(e.target.value)} /&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Dependency Array</p><ul><li><strong>[] (empty)</strong><br> → Runs <strong>only once</strong> (on mount), Never recalculates again</li><li><strong>[a]</strong><br> → Recalculates only when <strong>a changes</strong></li><li><strong>No dependency array</strong> ❌<br> → Recalculates on <strong>every render</strong></li></ul><pre>| Hook        | What it memoizes             |<br>| ----------- | ---------------------------- |<br>| useMemo     | Value (result of a function) |<br>| useCallback | Function reference           |</pre><h4>Custom Hooks</h4><p>Use Custom Hooks when:</p><ul><li>You see <strong>duplicate logic</strong> in multiple components</li><li>Your component is getting <strong>too complex</strong></li><li>You want to <strong>separate logic from UI</strong></li><li>You need reusable behavior like API calls, forms, authentication, and event handling</li></ul><p>Custom Hooks <strong>don’t share state automatically</strong>. They only share <strong>logic</strong>, not data. 👉 Each component using a custom Hook gets its <strong>own independent state</strong>.</p><pre>//WIthout using cutom Hook for fetch <br>import { useState, useEffect } from &quot;react&quot;;<br><br>export default function Users() {<br>  const [data, setData] = useState(null);<br>  const [loading, setLoading] = useState(false);<br>  const [error, setError] = useState(null);<br><br>  useEffect(() =&gt; {<br>    setLoading(true);<br>    setError(null);<br><br>    fetch(&quot;https://jsonplaceholder.typicode.com/users&quot;)<br>      .then((res) =&gt; {<br>        if (!res.ok) throw new Error(&quot;Error fetching data&quot;);<br>        return res.json();<br>      })<br>      .then((data) =&gt; setData(data))<br>      .catch((err) =&gt; setError(err.message))<br>      .finally(() =&gt; setLoading(false));<br>  }, []);<br><br>  if (loading) return &lt;p&gt;Loading...&lt;/p&gt;;<br>  if (error) return &lt;p&gt;Error: {error}&lt;/p&gt;;<br><br>  return (<br>    &lt;ul&gt;<br>      {data.map((user) =&gt; (<br>        &lt;li key={user.id}&gt;{user.name}&lt;/li&gt;<br>      ))}<br>    &lt;/ul&gt;<br>  );<br>}<br><br>//Using Custom Hook<br>export default function Users() {<br>  const { data, loading, error } = useFetch(<br>    &quot;https://jsonplaceholder.typicode.com/users&quot;<br>  );<br><br>  if (loading) return &lt;p&gt;Loading...&lt;/p&gt;;<br>  if (error) return &lt;p&gt;Error: {error}&lt;/p&gt;;<br><br>  return (<br>    &lt;ul&gt;<br>      {data.map((user) =&gt; (<br>        &lt;li key={user.id}&gt;{user.name}&lt;/li&gt;<br>      ))}<br>    &lt;/ul&gt;<br>  );<br>}<br><br>//Custom Hook<br>import { useState, useEffect } from &quot;react&quot;;<br><br>function useFetch(url) {<br>  const [data, setData] = useState(null);<br>  const [loading, setLoading] = useState(false);<br>  const [error, setError] = useState(null);<br><br>  useEffect(() =&gt; {<br>    if (!url) return;<br><br>    const fetchData = async () =&gt; {<br>      try {<br>        setLoading(true);<br>        setError(null);<br><br>        const res = await fetch(url);<br>        if (!res.ok) throw new Error(&quot;Error fetching data&quot;);<br><br>        const result = await res.json();<br>        setData(result);<br>      } catch (err) {<br>        setError(err.message);<br>      } finally {<br>        setLoading(false);<br>      }<br>    };<br><br>    fetchData();<br>  }, [url]);<br><br>  return { data, loading, error };<br>}</pre><pre>| Feature       | Custom Hook    | Component        |<br>| ------------- | -------------- | ---------------- |<br>| Purpose       | Reuse logic    | Render UI        |<br>| Returns       | Data/functions | JSX              |<br>| State sharing | Independent    | Shared via props |</pre><p>Real-World React Scenarios</p><ol><li><strong>API Calls</strong></li><li><strong>Forms</strong>(Typing username/password, Validating inputs, and Submitting data)</li><li><strong>Authentication</strong>(Store user info, Check if logged in, and Logout)</li><li><strong>Theme</strong>: User switches between light and dark mode.</li><li><strong>Local Storage</strong>: You refresh the page, but the data stays</li><li><strong>Debounce</strong>: Wait until the user stops typing → then call the API(Faster + efficient)</li><li><strong>Window Size</strong>: Website adjusts based on screen size</li></ol><h3>Conclusion</h3><p>React Hooks have fundamentally changed the way we build React applications. What once required class components, complex lifecycle methods, and repetitive patterns can now be handled with simple, reusable functions.</p><p>By understanding core Hooks like useState, useEffect, and useContext.You can manage state and side effects with ease. As your applications grow, Hooks like useReducer, useRef, useMemo, and useCallback help you handle complex logic and optimize performance effectively.</p><p>However, mastering Hooks isn’t just about knowing what they do — it’s about understanding <strong>when and why to use them</strong>. Following the Rules of Hooks, avoiding common pitfalls (like unnecessary memoization or incorrect dependencies), and writing clean, predictable logic are what truly make your code scalable and maintainable.</p><p>Custom Hooks take this a step further by allowing you to extract and reuse logic, making your components cleaner and more focused on UI.</p><p>In modern React development, Hooks are not just a feature — they are the <strong>standard way</strong> to build applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae85432326f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React State Management Made Easy: Context API, Classic Redux & Redux Toolkit]]></title>
            <link>https://medium.com/@yramcharanteja/react-state-management-made-easy-context-api-classic-redux-redux-toolkit-ece84d492f72?source=rss-e072c7cbc844------2</link>
            <guid isPermaLink="false">https://medium.com/p/ece84d492f72</guid>
            <category><![CDATA[react-context-api]]></category>
            <category><![CDATA[react-state-management]]></category>
            <category><![CDATA[redux-toolkit]]></category>
            <category><![CDATA[react-redux-toolkit]]></category>
            <category><![CDATA[react-redux]]></category>
            <dc:creator><![CDATA[CodeCraft by Ramcharan]]></dc:creator>
            <pubDate>Sun, 15 Mar 2026 22:58:40 GMT</pubDate>
            <atom:updated>2026-03-15T22:58:40.359Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Context API:</strong> Good for small apps, but doesn’t scale well.<br><strong>Classic Redux:</strong> Centralized state, more boilerplate.<br><strong>Redux Toolkit: </strong>Modern Redux, less boilerplate, safer, and easier to use.</p><h3>Why Redux Was Introduced (When We Already Have Context API)</h3><p>When building small React applications, <strong>state management is simple</strong>. You can manage the state using: useState, useReducer, useContext</p><p>However, as the application grows, the <strong>state becomes harder to manage</strong>, especially when multiple components need access to the same data.</p><p><strong>The Problem: Prop Drilling</strong></p><p>Example:</p><pre>App<br> └── Dashboard<br>      └── Sidebar<br>           └── UserProfile</pre><p>If UserProfile needs the user data from App, You must pass props through every component.</p><pre>&lt;App user={user} /&gt;<br>&lt;Dashboard user={user} /&gt;<br>&lt;Sidebar user={user} /&gt;<br>&lt;UserProfile user={user} /&gt;</pre><p>This is called <strong>Prop Drilling</strong>.</p><p>Problems:</p><ul><li>Components pass props they don’t need</li><li>Hard to maintain large apps</li><li>Difficult debugging</li></ul><h3>Solution 1: Context API</h3><ol><li>Create a Context</li></ol><pre>import { createContext } from &quot;react&quot;;<br>//createContext() creates a context object that will store the global data shared between components.<br>export const ThemeContext = createContext();</pre><p>2. Wrap Components with Context Provider so child components can access the data</p><pre>import React, { useState } from &quot;react&quot;;<br>import { ThemeContext } from &quot;./ThemeContext&quot;;<br>import Navbar from &quot;./Navbar&quot;;<br><br>function App() {<br>  const [theme, setTheme] = useState(&quot;light&quot;);<br><br>  const toggleTheme = () =&gt; {<br>    setTheme(theme === &quot;light&quot; ? &quot;dark&quot; : &quot;light&quot;);<br>  };<br><br>  return (<br>    &lt;ThemeContext.Provider value={{ theme, toggleTheme }}&gt;<br>      &lt;Navbar /&gt;<br>    &lt;/ThemeContext.Provider&gt;<br>  );<br>}<br><br>export default App;</pre><p>3. Child components can access the context using the useContext hook.</p><pre>import React, { useContext } from &quot;react&quot;;<br>import { ThemeContext } from &quot;./ThemeContext&quot;;<br><br>function ThemeButton() {<br>  const { theme, toggleTheme } = useContext(ThemeContext);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Current Theme: {theme}&lt;/p&gt;<br>      &lt;button onClick={toggleTheme}&gt;Toggle Theme&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default ThemeButton;</pre><p>Limitation of Context API</p><ol><li><strong>Performance issues:</strong> When context value changes, all components re-render.</li><li><strong>Complex state logic:</strong> Context Api is not designed for complex state transitions.</li><li><strong>No centralized debugging: </strong>No built-in tools like Redux DevTools.</li><li><strong>Harder to Scale: </strong>Large applications need predictable state management.</li></ol><h3>Solution 2: Redux</h3><p>Redux addresses all the limitations of Context API.</p><p>Three Core Principles of Redux</p><ol><li><strong>Single source of truth</strong> → Application state lives in one store</li><li><strong>State is read-only </strong>→ State cannot be modified directly. Instead, you dispatch an action that describes what should change.</li><li><strong>Changes are made with pure functions </strong>→ Redux uses reducers, which are pure functions that take the current state and an action, then return a new state.</li></ol><h4>Redux with createStore</h4><p>Before Redux Toolkit existed, Redux used <strong>createStore</strong>. Although it is now <strong>deprecated</strong>, it is important to understand for interviews.</p><p>Step 1: npm install redux react-redux</p><p>Step 2: Create Reducer</p><pre>//Initial State<br>const initialState = {<br>  count: 0<br>};<br><br>/*<br>*Reducer Function<br>*Receives current state<br>*Receives action<br>*Return new State<br>*/<br>function counterReducer(state = initialState, action) {<br><br>  switch(action.type) {<br><br>    case &quot;INCREMENT&quot;:<br>      return { ...state, count: state.count + 1 };<br><br>    case &quot;DECREMENT&quot;:<br>      return { ...state, count: state.count - 1 };<br><br>    case &quot;RESET&quot;:<br>      return { ...state, count: 0 };<br><br>    default:<br>      return state;<br>  }<br>}<br><br>export default counterReducer;</pre><p>Step 3: Create Store</p><pre>import { createStore } from &quot;redux&quot;;<br>import counterReducer from &quot;./reducer&quot;;<br><br>//Create Redux Store<br>const store = createStore(counterReducer);<br><br>export default store;</pre><p>The store holds the application state, dispatches actions, and notifies subscribers.</p><p>Step 4: Connect Redux to React</p><pre>import React from &quot;react&quot;;<br>import ReactDOM from &quot;react-dom/client&quot;;<br>import { Provider } from &quot;react-redux&quot;;<br>import App from &quot;./App&quot;;<br>import store from &quot;./store&quot;;<br><br>const root = ReactDOM.createRoot(document.getElementById(&quot;root&quot;));<br><br>root.render(<br>  &lt;Provider store={store}&gt;<br>    &lt;App /&gt;<br>  &lt;/Provider&gt;<br>);</pre><p>Step 5: Use Redux in the Component</p><pre>import React from &quot;react&quot;;<br>import { useSelector, useDispatch } from &quot;react-redux&quot;;<br><br>function Counter() {<br><br>  //Reads Data from Redux Store<br>  const count = useSelector((state) =&gt; state.count);<br><br>  // Dispatches Actions<br>  const dispatch = useDispatch();<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;{count}&lt;/h1&gt;<br><br>      //Send Action to reducer<br>      &lt;button onClick={() =&gt; dispatch({ type: &quot;INCREMENT&quot; })}&gt;<br>        Increment<br>      &lt;/button&gt;<br><br>      &lt;button onClick={() =&gt; dispatch({ type: &quot;DECREMENT&quot; })}&gt;<br>        Decrement<br>      &lt;/button&gt;<br><br>      &lt;button onClick={() =&gt; dispatch({ type: &quot;RESET&quot; })}&gt;<br>        Reset<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default Counter;</pre><h4>Modern Redux with Redux Toolkit (configureStore)</h4><p>Redux Toolkit is now the <strong>recommended way to use Redux</strong>.</p><p>Advantages:</p><ul><li>Less boilerplate</li><li>Built-in best practices</li><li>Includes middleware</li><li>Simpler reducers</li></ul><p><strong>Step 1:</strong> <em>npm install @reduxjs/toolkit react-redux</em></p><p><strong>Step 2: </strong>Create a Slice</p><pre>import { createSlice } from &quot;@reduxjs/toolkit&quot;;<br><br>// Step 1: Define a slice<br>export const counterSlice = createSlice({<br>  name: &quot;counter&quot;,      // Name of the slice<br>  initialState: {       // Initial state of the slice<br>    value: 0<br>  },<br>  reducers: {           // Reducers define how state changes<br>    increment: (state) =&gt; {<br>      state.value += 1; // Redux Toolkit uses Immer, so we can &quot;mutate&quot; state safely<br>    },<br>    decrement: (state) =&gt; {<br>      state.value -= 1;<br>    },<br>    reset: (state) =&gt; {<br>      state.value = 0;<br>    }<br>  }<br>});<br><br>// Step 2: Export actions<br>export const { increment, decrement, reset } = counterSlice.actions;<br><br>// Step 3: Export reducer<br>export default counterSlice.reducer;</pre><p><strong>Explanation:</strong></p><ul><li>createSlice() replaces <strong>separate action + reducer code</strong> in classic Redux. createSlice <strong>automatically creates action types and action creators</strong> for each reducer.</li><li>state.value += 1 Looks like a mutation, but Redux Toolkit handles it safely using <strong>Immer</strong>.</li><li>actions are automatically generated (increment, decrement, reset).</li></ul><p><strong>Step 3: </strong>Configure the Store</p><pre>import { configureStore } from &quot;@reduxjs/toolkit&quot;;<br>import counterReducer from &quot;./counterSlice&quot;;<br><br>// Step 1: Create the store<br>export const store = configureStore({<br>  reducer: {<br>    counter: counterReducer // Add our slice reducer<br>  }<br>});</pre><p><strong>Explanation:</strong></p><ul><li>configureStore replaces createStore and sets up <strong>Redux DevTools</strong> automatically.</li><li>reducer key can have <strong>multiple slices</strong> for larger apps.</li></ul><p><strong>Step 4: </strong>Wrap App with Provider</p><pre>import React from &quot;react&quot;;<br>import ReactDOM from &quot;react-dom/client&quot;;<br>import { Provider } from &quot;react-redux&quot;;<br>import { store } from &quot;./store&quot;;<br>import App from &quot;./App&quot;;<br><br>ReactDOM.createRoot(document.getElementById(&quot;root&quot;)).render(<br>  &lt;Provider store={store}&gt;<br>    &lt;App /&gt;<br>  &lt;/Provider&gt;<br>);</pre><p><strong>Step 5: </strong>Use Redux State in Component</p><pre>import React from &quot;react&quot;;<br>import { useSelector, useDispatch } from &quot;react-redux&quot;;<br>import { increment, decrement, reset } from &quot;./counterSlice&quot;;<br><br>function App() {<br>  const count = useSelector((state) =&gt; state.counter.value); // Access state<br>  const dispatch = useDispatch(); // Dispatch actions<br><br>  return (<br>    &lt;div style={{ textAlign: &quot;center&quot;, marginTop: &quot;50px&quot; }}&gt;<br>      &lt;h1&gt;Redux Toolkit Counter&lt;/h1&gt;<br>      &lt;h2&gt;{count}&lt;/h2&gt;<br>      &lt;button onClick={() =&gt; dispatch(increment())}&gt;Increment&lt;/button&gt;<br>      &lt;button onClick={() =&gt; dispatch(decrement())}&gt;Decrement&lt;/button&gt;<br>      &lt;button onClick={() =&gt; dispatch(reset())}&gt;Reset&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><p><strong>Explanation:</strong></p><ul><li>useSelector reads the Redux state (state.counter.value).</li><li>useDispatch sends actions to update the state.</li><li>Clicking buttons updates the state <strong>without prop drilling</strong>.</li></ul><h3>Conclusion</h3><p>State management is a key part of building scalable React applications. While <strong>Context API</strong> works well for small apps and simple state sharing, it has limitations in performance, complex logic, and debugging.</p><p><strong>Redux</strong>, especially with <strong>Redux Toolkit</strong>, provides a <strong>centralized, predictable, and scalable state management solution</strong>. With createSlice and configureStoreRedux becomes easier to implement with <strong>less boilerplate</strong>, <strong>built-in best practices</strong>, and <strong>automatic DevTools integration</strong>.</p><p>For beginners and interview preparation, understanding <strong>the Context API, classic Redux, and modern Redux Toolkit</strong> provides a strong foundation for managing state efficiently in real-world React applications.</p><h3>GitHub References</h3><ul><li><strong>Context API Implementation:</strong> <a href="https://github.com/CodeCraftByRamcharan/react-context-api">https://github.com/CodeCraftByRamcharan/react-context-api</a></li><li><strong>React Redux Implementation:</strong> <a href="https://github.com/CodeCraftByRamcharan/react-redux-movie-app">https://github.com/CodeCraftByRamcharan/react-redux-movie-app</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ece84d492f72" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>