<?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 Pallavi Shankar Sutar on Medium]]></title>
        <description><![CDATA[Stories by Pallavi Shankar Sutar on Medium]]></description>
        <link>https://medium.com/@techblogsbypallavi?source=rss-17c7e41052a9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*7vswrw36ypWWHcI3</url>
            <title>Stories by Pallavi Shankar Sutar on Medium</title>
            <link>https://medium.com/@techblogsbypallavi?source=rss-17c7e41052a9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 10:11:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@techblogsbypallavi/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[Blue-Green Deployment Explained: Achieving Zero-Downtime Releases with Kubernetes]]></title>
            <link>https://techblogsbypallavi.medium.com/blue-green-deployment-explained-achieving-zero-downtime-releases-with-kubernetes-e953221ab2f3?source=rss-17c7e41052a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/e953221ab2f3</guid>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[blue-green-deployment]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Pallavi Shankar Sutar]]></dc:creator>
            <pubDate>Fri, 16 Oct 2026 15:54:22 GMT</pubDate>
            <atom:updated>2026-10-16T15:54:22.976Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sORP6lIfg6TWSwmId_oZQw.png" /><figcaption>Blue-Green Deployment</figcaption></figure><p><em>Understanding how modern applications deploy new versions without disrupting users, with a practical Spring Boot and Kubernetes example.</em></p><h3>Introduction</h3><p>Imagine you’re shopping on an e-commerce platform during a major festive sale.</p><p>Thousands of customers are browsing products, adding items to their carts, and completing payments.</p><p>Meanwhile, the development team has prepared a new version of the application with bug fixes and improved functionality.</p><p>The team needs to deploy these changes to production.</p><p>But here’s the challenge:</p><p><strong>How can we deploy a new application version without interrupting customers who are actively using the platform?</strong></p><p>Stopping the existing application, deploying the new version, and restarting the service may introduce downtime.</p><p>Even a few minutes of unavailability during peak shopping hours can affect customer experience and business operations.</p><p>This is where <strong>Blue-Green Deployment</strong> becomes useful.</p><p>In this article, we’ll explore what Blue-Green Deployment is, how it works, and how to implement it using Spring Boot and Kubernetes.</p><h3>1. What Is Blue-Green Deployment?</h3><p>Blue-Green Deployment is a software release strategy that maintains two separate application environments.</p><p>These environments are commonly referred to as:</p><p>🔵 <strong>Blue Environment:</strong> The current production version serving customer requests.</p><p>🟢 <strong>Green Environment:</strong> The new application version deployed and validated before receiving production traffic.</p><p>Only one environment initially serves regular production requests.</p><p>Once the new version is validated, incoming traffic is redirected from Blue to Green.</p><p>The previous version can remain available temporarily as a rollback option.</p><h3>Example</h3><p>Consider an e-commerce Order Management Service.</p><p>Currently, the application is running version 1.0.</p><p>The development team introduces new functionality in version 2.0.</p><p>Instead of replacing version 1.0 immediately, both versions are deployed separately.</p><p>Blue continues serving production traffic while Green undergoes validation.</p><p>After successful testing, production traffic is redirected to Green.</p><p>This approach helps minimise downtime and release-related risks.</p><h3>2. How Does Blue-Green Deployment Work?</h3><p>Let’s understand the deployment lifecycle.</p><h3>Phase 1: Blue Is Active</h3><p>Initially, all customer requests are routed to the Blue environment.</p><pre>             Customer Requests<br>                     |<br>                     v<br>               Load Balancer<br>                     |<br>                     v<br>              BLUE Environment<br>               Spring Boot v1<br>                  ACTIVE<br><br>  `          GREEN Environment<br>                 STANDBY<br></pre><p>At this stage:</p><ul><li>Blue handles production traffic.</li><li>Green is not serving customer requests.</li><li>The existing application continues operating normally.</li></ul><h3>Phase 2: Deploy the New Version</h3><p>The team deploys Spring Boot version 2.0 into the Green environment.</p><pre>      Customer Requests <br>              | <br>              v <br>          Load Balancer <br>              | <br>              v <br>        BLUE Environment <br>        Spring Boot v1 <br>            ACTIVE <br><br>        GREEN Environment <br>        Spring Boot v2 <br>        UNDER VALIDATION</pre><p>Both versions now exist.</p><p>However, production traffic continues flowing to Blue.</p><p>The team performs health checks, smoke tests, and application validation on Green.</p><h3>Phase 3: Switch Production Traffic</h3><p>Once Green passes all required checks, traffic is redirected.</p><pre>      Customer Requests <br>              | <br>              v <br>        Load Balancer <br>              | <br>              v <br>      GREEN Environment <br>        Spring Boot v2 <br>            ACTIVE <br>    <br>      BLUE Environment <br>      Spring Boot v1 <br>          STANDBY</pre><p>Green becomes the active production version.</p><p>Blue remains available temporarily in case rollback is required.</p><p><strong>Important:</strong> Blue-Green Deployment can minimize downtime, but zero downtime is not automatic. Application readiness, connection draining, infrastructure routing, and backward compatibility must be handled correctly.</p><h3>3. Implementing Blue-Green Deployment Using Kubernetes</h3><p>Let’s implement this strategy for an e-commerce Order Management microservice.</p><p>Our technology stack includes:</p><ul><li>Java</li><li>Spring Boot</li><li>Docker</li><li>Kubernetes</li><li>Spring Boot Actuator</li></ul><p>We’ll use two Kubernetes Deployments and one Kubernetes Service.</p><h3>Step 1: Create the Blue Deployment</h3><p>The Blue environment runs application version 1.0.</p><p>Create a file named blue-deployment.yaml.</p><pre>apiVersion: apps/v1 <br>kind: Deployment <br>metadata: <br>  name: order-service-blue <br>spec: <br>  replicas: 3 <br>  selector: <br>    matchLabels: <br>      app: order-service <br>      version: blue <br>  template: <br>    metadata: <br>      labels: <br>        app: order-service <br>        version: blue <br>    spec: <br>      containers: <br>        - name: order-service <br>        image: myregistry/order-service:1.0 <br>        ports: <br>          - containerPort: 8080 <br>        readinessProbe: <br>          httpGet: <br>            path: /actuator/health/readiness <br>            port: 8080 <br>        initialDelaySeconds: 10 <br>         periodSeconds: 5</pre><p>This configuration creates three Pods running version 1.0.</p><p>The readiness probe helps Kubernetes determine whether each application Pod is ready to receive traffic.</p><p>The Spring Boot Actuator readiness endpoint must be enabled and configured appropriately.</p><h3>Step 2: Create the Kubernetes Service</h3><p>Next, create order-service.yaml.</p><pre>apiVersion: v1 <br>kind: Service <br>metadata: <br>  name: order-service <br>spec: <br>  selector:  <br>    app: order-service <br>    version: blue <br>  ports: <br>    - protocol: TCP <br>      port: 80 <br>      targetPort: 8080</pre><p>Notice the Service selector:</p><pre>selector: <br>  app: order-service <br>  version: blue</pre><p>This tells Kubernetes to route traffic to Pods labelled version: blue.</p><p>The Service provides a stable endpoint while the underlying application Pods can change.</p><h3>Step 3: Deploy the Green Environment</h3><p>Now create green-deployment.yaml.</p><pre>apiVersion: apps/v1 <br>kind: Deployment <br>metadata: <br>  name: order-service-green <br>spec: <br>  replicas: 3 <br>  selector: <br>    matchLabels: <br>      app: order-service <br>      version: green <br>  template: <br>    metadata: <br>      labels: <br>        app: order-service <br>        version: green <br>    spec: <br>      containers: <br>        - name: order-service <br>        image: myregistry/order-service:2.0 <br>        ports: <br>          - containerPort: 8080 <br>        readinessProbe: <br>          httpGet: <br>            path: /actuator/health/readiness <br>            port: 8080 <br>          initialDelaySeconds: 10 <br>          periodSeconds: 5</pre><p>Apply the configuration:</p><pre>kubectl apply -f green-deployment.yaml</pre><p>Verify the rollout:</p><pre>kubectl rollout status deployment/order-service-green</pre><p>At this point, both Blue and Green are running.</p><p>But the Kubernetes Service still selects Blue Pods.</p><p>Therefore, Green does not receive regular production traffic through that Service.</p><p>Before switching, Green should be tested through a separate internal endpoint or another controlled validation mechanism.</p><h3>4. Switching Traffic from Blue to Green</h3><p>Once the Green environment is validated, we can update the Kubernetes Service selector.</p><p>Execute:</p><pre>kubectl patch service order-service \<br>  -p &#39;{&quot;spec&quot;:{&quot;selector&quot;:{&quot;app&quot;:&quot;order-service&quot;,&quot;version&quot;:&quot;green&quot;}}}&#39;</pre><p>What happens here?</p><p>Previously, the Service selected:</p><pre>version: blue</pre><p>Now it selects:</p><pre>version: green</pre><p>Kubernetes updates the Service’s backend endpoints to reflect the new selector.</p><p>New requests can then be routed to the Green environment as the changes propagate.</p><p>The application has been upgraded without intentionally shutting down the currently serving environment.</p><p>However, the traffic transition is not a perfectly atomic switch. Existing connections and endpoint-update propagation require consideration.</p><h3>5. What Happens If the New Version Fails?</h3><p>Imagine version 2.0 introduces an unexpected issue.</p><p>Customers begin experiencing errors while placing orders.</p><p>Because the Blue environment is still running, the team can redirect traffic back to it.</p><p>Execute:</p><pre>kubectl patch service order-service \<br>  -p &#39;{&quot;spec&quot;:{&quot;selector&quot;:{&quot;app&quot;:&quot;order-service&quot;,&quot;version&quot;:&quot;blue&quot;}}}&#39;</pre><p>The Service again selects the Blue Pods.</p><p>This provides a relatively straightforward application rollback.</p><p>However, rollback safety depends on more than retaining old Pods.</p><p>For example, if version 2.0 modified the database in a way that version 1.0 cannot understand, switching back may not restore correct functionality.</p><p>This leads us to another important production consideration.</p><h3>6. Managing Database Changes During Blue-Green Deployment</h3><p>Suppose Blue and Green connect to the same database.</p><p>Version 1.0 uses the following columns:</p><pre>ORDERS<br>------<br>ORDER_ID<br>CUSTOMER_ID<br>TOTAL_AMOUNT<br>STATUS</pre><p>Version 2.0 introduces a new attribute:</p><pre>DISCOUNT_AMOUNT</pre><p>Adding a nullable column is generally backwards-compatible, provided the existing application does not depend on a fixed column structure</p><p>But what happens if version 2.0 renames or removes a column used by version 1.0?</p><p>The old application may fail after rollback.</p><p>A safer approach is the <strong>Expand-and-Contract Pattern</strong>.</p><h3>Expand</h3><p>Introduce backwards-compatible database changes.</p><p>For example:</p><pre>ALTER TABLE ORDERS<br>ADD DISCOUNT_AMOUNT NUMBER(10,2);</pre><p>Both application versions should continue functioning.</p><h3>Migrate</h3><p>Deploy version 2.0 and begin using the new column.</p><p>Where necessary, migrate existing data and temporarily support both old and new representations.</p><h3>Contract</h3><p>Once version 1.0 is no longer required, remove obsolete database structures in a later release.</p><p>This reduces compatibility risks during deployment and rollback.</p><h3>7. Blue-Green vs. Rolling Deployment</h3><p>Blue-Green and Rolling Deployment are two widely used release strategies.</p><p><strong>Blue-Green Deployment</strong></p><p>Maintains two environments and redirects traffic after validating the new release.</p><p><strong>Rolling Deployment</strong></p><p>Gradually replaces old application instances with new instances.</p><p>Both approaches can minimise downtime, but they differ in resource requirements, traffic management, and release behaviour.</p><p>Blue-Green Deployment is useful when the team wants to validate an entire new environment before switching traffic.</p><p>Rolling Deployment may be preferable when gradual replacement and efficient resource utilisation are priorities.</p><h3>8. Important Production Considerations</h3><p>Successfully deploying an application involves more than updating a Kubernetes Service.</p><h3>Readiness and Health Checks</h3><p>Ensure the new application is ready before allowing production traffic.</p><p>A running Pod is not necessarily a ready Pod.</p><h3>Graceful Shutdown</h3><p>When an old Pod is terminated, Kubernetes normally provides a grace period for the application to shut down.</p><p>Spring Boot should be configured to handle in-flight requests appropriately.</p><p>For example:</p><pre>server:<br>  shutdown: graceful</pre><pre>spring:<br>  lifecycle:<br>    timeout-per-shutdown-phase: 30s</pre><p>The Kubernetes termination grace period must also be sufficient for the application’s shutdown requirements.</p><h3>Monitoring</h3><p>Monitor critical metrics during and after the cutover:</p><ul><li>HTTP error rates</li><li>Request latency</li><li>Application CPU and memory usage</li><li>Database connection usage</li><li>Business transaction failures</li></ul><h3>Database Compatibility</h3><p>Ensure both application versions can safely operate against the database schema during the transition.</p><h3>Background Jobs</h3><p>If the application includes scheduled jobs, remember that Blue and Green may execute background tasks simultaneously.</p><p>Switching HTTP traffic does not automatically disable scheduled jobs in the inactive environment.</p><p>Distributed coordination or dedicated batch workers may be necessary.</p><h3>9. Real-World E-commerce Example</h3><p>Consider a shopping platform preparing for a major sale.</p><p>The existing Order Management Service is running version 1.0.</p><p>The development team introduces version 2.0 with:</p><ul><li>Improved order validation</li><li>Additional discount calculations</li><li>Performance improvements</li><li>Bug fixes</li></ul><p>Using Blue-Green Deployment, the team can:</p><ol><li>Continue serving customers through version 1.0.</li><li>Deploy version 2.0 to an independent environment.</li><li>Validate version 2.0 using controlled test traffic.</li><li>Switch production traffic to version 2.0.</li><li>Monitor application and business metrics.</li><li>Roll back to version 1.0 if necessary and compatible.</li></ol><p>This approach makes the production release process more controlled and reduces the need for planned application downtime.</p><h3>Conclusion</h3><p>Blue-Green Deployment is an effective strategy for releasing new application versions while minimising service interruption.</p><p>By maintaining two environments, teams can validate a new release before redirecting production traffic.</p><p>However, achieving reliable deployments requires careful attention to readiness checks, network traffic, database compatibility, application shutdown, and rollback planning.</p><p>For Spring Boot microservices deployed on Kubernetes, understanding these concepts is an important step toward building reliable production systems.</p><p><strong>A successful production deployment is not just about releasing new code. It’s about introducing change without compromising application availability and reliability.</strong></p><p>Happy coding! ☕</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e953221ab2f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Batch Explained: A Practical Guide Using E-commerce Order Processing]]></title>
            <link>https://techblogsbypallavi.medium.com/spring-batch-explained-a-practical-guide-using-e-commerce-order-processing-5803ea544de8?source=rss-17c7e41052a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/5803ea544de8</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring-batch]]></category>
            <category><![CDATA[spring-batch-processing]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Pallavi Shankar Sutar]]></dc:creator>
            <pubDate>Fri, 16 Oct 2026 14:20:22 GMT</pubDate>
            <atom:updated>2026-10-16T14:20:22.415Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C4Uv4usvZJ_L_8F__I03wA.png" /><figcaption>Spring Batch</figcaption></figure><p>Understanding Spring Batch architecture, chunk-oriented processing, and its core components with a real-world example.</p><h3>Introduction</h3><p>Imagine you’re working on an e-commerce application that receives thousands of orders every day.</p><p>Some orders need payment verification, others require discount calculations, and many need their processing statuses updated.</p><p>Now imagine handling 100,000 orders daily.</p><p>Would you create a separate REST API call for every order? Would you load all the records into memory and process them at once?</p><p>Neither approach is necessarily suitable for large-scale background processing.</p><p>This is where <strong>Spring Batch</strong> comes into the picture.</p><p>Spring Batch provides a structured and reliable way to process large volumes of data while supporting transaction management, error handling, and restartability.</p><p>In this article, we’ll explore how Spring Batch works and understand its architecture through a practical e-commerce order-processing example.</p><h3>1. What Is Spring Batch?</h3><p>Spring Batch is a framework designed to simplify the development of robust batch-processing applications.</p><p>Batch processing refers to executing operations on a collection of records, usually without requiring continuous user interaction.</p><p>Unlike traditional REST APIs, which typically handle individual requests, batch applications can process large datasets through a controlled workflow.</p><h3>Where is Spring Batch used?</h3><p>Spring Batch can be useful for:</p><ul><li>E-commerce order processing</li><li>Inventory updates</li><li>Sales report generation</li><li>Customer billing</li><li>Data migration</li><li>Payroll processing</li><li>Bulk data validation</li></ul><p>Consider an e-commerce platform with thousands of orders waiting to be processed.</p><p>Instead of processing each order through a separate external request, we can create a Spring Batch Job that reads pending orders, performs calculations, and updates their statuses.</p><h3>2. Understanding Spring Batch Architecture</h3><p>Spring Batch revolves around five important components:</p><p><strong>Job, Step, ItemReader, ItemProcessor, and ItemWriter.</strong></p><p>Let’s understand each component using our e-commerce application.</p><h3>Job</h3><p>A Job represents the complete batch-processing workflow.</p><p>For example:</p><pre>orderProcessingJob</pre><p>Our Job is responsible for processing pending customer orders.</p><h3>Step</h3><p>A Step represents one phase of a Job.</p><p>A Job can contain multiple Steps.</p><p>For our example, we’ll create a single chunk-oriented Step that reads, processes, and writes orders.</p><h3>ItemReader</h3><p>The ItemReader retrieves records from the data source.</p><p>In our e-commerce application, it fetches orders with the status PENDING.</p><p>Example SQL:</p><pre>SELECT ID, CUSTOMER_ID, TOTAL_AMOUNT, STATUS <br>FROM ORDERS WHERE STATUS = &#39;PENDING&#39; ORDER BY ID;</pre><p>The reader fetches the records to be processed.</p><p>For large production workloads, the reader should be configured with an appropriate cursor or paging strategy.</p><h3>ItemProcessor</h3><p>The ItemProcessor applies business logic to each record.</p><p>For example, our application may apply a 10% discount to orders above ₹5,000.</p><pre>@Component public class OrderProcessor implements ItemProcessor&lt;Order, Order&gt; {<br>   @Override public Order process(Order order) { <br>      if (order.getTotalAmount() .compareTo(new BigDecimal(&quot;5000&quot;)) &gt; 0) { <br>          BigDecimal discount = order.getTotalAmount() .multiply(new BigDecimal(&quot;0.10&quot;)); <br>          order.setTotalAmount( order.getTotalAmount().subtract(discount) ); <br>      } <br>      order.setStatus(&quot;PROCESSED&quot;); <br>      return order; } <br>}</pre><p>Here, we are applying a discount and changing the order status.</p><p>The processor transforms the data, but it doesn’t persist the changes.</p><p>That responsibility belongs to the writer.</p><p><em>In a production e-commerce system, discounts should be calculated according to actual pricing rules and should not be reapplied to already processed orders.</em></p><h3>ItemWriter</h3><p>The ItemWriter saves processed data to the destination.</p><p>In our example, it updates the order amount and status in the database.</p><p>A JdbcBatchItemWriter can execute the required database update for each chunk.</p><p>Example SQL:</p><pre>UPDATE ORDERS SET TOTAL_AMOUNT = :totalAmount, <br>STATUS = :status WHERE ID = :id;</pre><h3>3. Understanding Chunk-Oriented Processing</h3><p>Chunk-oriented processing is one of the most important concepts in Spring Batch.</p><p>Instead of processing all records in a single transaction, Spring Batch divides the data into smaller groups called <strong>chunks</strong>.</p><p>Suppose we have 10,000 pending orders.</p><p>We configure:</p><pre>.&lt;Order, Order&gt;chunk(100, transactionManager)</pre><p>This means Spring Batch will typically:</p><ol><li>Read 100 orders.</li><li>Process each order.</li><li>Write the processed orders.</li><li>Commit the transaction.</li><li>Continue with the next 100 orders.</li></ol><p>If all 10,000 orders are processed successfully, this results in approximately 100 chunks.</p><h3>Why is chunk processing useful?</h3><p><strong>Transaction management</strong></p><p>Each chunk operates within a transaction boundary.</p><p>If a database write fails, the transaction can roll back.</p><p><strong>Memory efficiency</strong></p><p>Chunk processing avoids the need to hold the entire dataset in memory.</p><p><strong>Failure handling</strong></p><p>Spring Batch supports configurable retry and skip mechanisms.</p><p><strong>Performance tuning</strong></p><p>Developers can adjust chunk size based on workload and database performance.</p><p>However, increasing chunk size does not automatically improve performance. Larger chunks may also increase transaction duration and resource consumption.</p><h3>4. Configuring a Spring Batch Job</h3><p>Let’s create a Spring Batch configuration using Spring Boot 3 and Spring Batch 5.</p><pre>@Configuration public class OrderBatchConfig { <br>  @Bean public Step orderProcessingStep( JobRepository jobRepository, <br>      PlatformTransactionManager transactionManager, <br>      ItemReader&lt;Order&gt; orderReader, ItemProcessor&lt;Order, Order&gt; orderProcessor, <br>      ItemWriter&lt;Order&gt; orderWriter) { <br>    return new StepBuilder( &quot;orderProcessingStep&quot;, jobRepository) <br>          .&lt;Order, Order&gt;chunk( 100, transactionManager) <br>          .reader(orderReader) .processor(orderProcessor) <br>          .writer(orderWriter)  <br>          .build(); <br>    }<br><br>    @Bean public Job orderProcessingJob( JobRepository jobRepository, <br>      Step orderProcessingStep) { <br>      return new JobBuilder( &quot;orderProcessingJob&quot;, jobRepository) <br>            .start(orderProcessingStep) .build(); <br>    } <br>}</pre><h3>Understanding the configuration</h3><p><strong>JobRepository:</strong> Stores metadata about Job and Step executions.</p><p><strong>TransactionManager:</strong> Manages transactions during batch processing.</p><p><strong>ItemReader:</strong> Fetches pending orders.</p><p><strong>ItemProcessor:</strong> Applies discount calculations and updates the status in memory.</p><p><strong>ItemWriter:</strong> Persists processed orders.</p><p>The code above demonstrates Job and Step configuration. A complete runnable application also requires the Order model, database configuration, and implementations of the reader and writer.</p><h3>5. Handling Failures in Spring Batch</h3><p>Imagine processing 10,000 orders, but some records contain invalid information.</p><p>Should the entire Job fail because of a few invalid records?</p><p>Not necessarily.</p><p>Spring Batch provides mechanisms such as skip and retry.</p><h3>Skip invalid records</h3><pre>.faultTolerant() <br>.skip(InvalidOrderException.class) <br>.skipLimit(10)</pre><p>This configuration allows eligible invalid orders to be skipped, up to the configured limit.</p><h3>Retry temporary failures</h3><pre>.faultTolerant() <br>.retry(TransientDataAccessException.class) <br>.retryLimit(3)</pre><p>This configuration allows additional attempts for eligible transient database failures.</p><p>Skip and retry behaviour must be designed carefully.</p><p>For example, an invalid order might be skipped and recorded for manual review, while a temporary database failure might be retried.</p><h3>6. Spring Batch vs. Spring Scheduler</h3><p>Many developers confuse Spring Batch with Spring Scheduler.</p><p>However, they solve different problems.</p><p><strong>1. Primary Purpose</strong></p><p><strong>Spring Batch:</strong> Handles large-scale data processing.</p><p><strong>Spring Scheduler:</strong> Triggers tasks at scheduled times.</p><p><strong>2. Execution Management</strong></p><p><strong>Spring Batch:</strong> Provides Job and Step execution management.</p><p><strong>Spring Scheduler:</strong> Provides time-based task execution.</p><p><strong>3. Chunk Processing</strong></p><p><strong>Spring Batch:</strong> Supports chunk-oriented processing for efficient data handling.</p><p><strong>Spring Scheduler:</strong> Does not provide built-in chunk processing.</p><p><strong>4. Restartability</strong></p><p><strong>Spring Batch:</strong> Supports job restartability and recovery.</p><p><strong>Spring Scheduler:</strong> Does not provide built-in batch restartability.</p><p><strong>5. Error Handling</strong></p><p><strong>Spring Batch:</strong> Provides configurable skip and retry mechanisms.</p><p><strong>Spring Scheduler:</strong> Requires separate error-handling and retry logic.</p><p><strong>6. Execution Metadata</strong></p><p><strong>Spring Batch:</strong> Maintains job execution metadata through JobRepository.</p><p><strong>Spring Scheduler:</strong> Does not maintain detailed job execution metadata by default.</p><p><strong>7. Real-World Example</strong></p><p><strong>Spring Batch:</strong> Processes 10,000 pending e-commerce orders.</p><p><strong>Spring Scheduler:</strong> Triggers the order-processing job every night at midnight.</p><p>For example, an e-commerce application may need to process pending orders every night.</p><p>Spring Scheduler can trigger the processing at midnight.</p><p>Spring Batch can then read, process, and update the orders.</p><p>Both frameworks can work together to automate the workflow.</p><h3>7. Real-World E-commerce Workflow</h3><p>Our complete processing flow looks like this:</p><pre>E-commerce Application<br>                     |<br>                     v<br>              Orders Database<br>                     |<br>                     v<br>              Spring Batch Job<br>                     |<br>                     v<br>                ItemReader<br>             Fetch PENDING Orders<br>                     |<br>                     v<br>               ItemProcessor<br>              Validate Orders<br>             Calculate Discount<br>             Set PROCESSED Status<br>                     |<br>                     v<br>                 ItemWriter<br>              Update Database<br>                     |<br>                     v<br>              Job Completion</pre><p>For more complex applications, the workflow could be extended to include inventory reconciliation, report generation, or integration with external systems.</p><p>External side effects, such as sending customer notifications, require careful handling to avoid duplicate actions when jobs are retried or restarted.</p><h3>8. Spring Batch Best Practices</h3><p>When implementing Spring Batch in production applications, consider the following practices:</p><p><strong>Choose an appropriate chunk size:</strong> Experiment with different values and measure throughput, memory usage, and transaction duration.</p><p><strong>Use efficient database queries:</strong> Retrieve only the required columns and implement suitable indexing.</p><p><strong>Implement proper exception handling:</strong> Distinguish between temporary failures and permanent data errors.</p><p><strong>Design for restartability:</strong> Ensure jobs can safely resume after failures.</p><p><strong>Use idempotent processing:</strong> Prevent duplicate updates when a job is restarted.</p><p><strong>Monitor Job executions:</strong> Track execution status, failures, and processing duration.</p><p><strong>Avoid unnecessary concurrency:</strong> Introduce parallel processing only when the workload justifies the additional complexity.</p><h3>Conclusion</h3><p>Spring Batch provides a powerful foundation for building reliable and scalable data-processing applications.</p><p>Its architecture revolves around five core components:</p><p><strong>Job → Step → ItemReader → ItemProcessor → ItemWriter</strong></p><p>By understanding these components and chunk-oriented processing, developers can implement efficient batch workflows across a wide range of industries.</p><p>Whether you’re processing e-commerce orders, generating reports, or migrating large datasets, Spring Batch helps organize complex processing into manageable and maintainable workflows.</p><p>The real value of Spring Batch is not simply processing thousands of records.</p><p>It is processing them reliably while managing transactions, handling failures, and supporting recovery.</p><p>Happy coding! ☕</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5803ea544de8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JWTs in Microservices: How to Rotate Keys and Invalidate Sessions Cleanly]]></title>
            <link>https://techblogsbypallavi.medium.com/jwts-in-microservices-how-to-rotate-keys-and-invalidate-sessions-cleanly-db30c1110fd7?source=rss-17c7e41052a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/db30c1110fd7</guid>
            <category><![CDATA[jwt-token]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Pallavi Shankar Sutar]]></dc:creator>
            <pubDate>Fri, 05 Sep 2025 10:57:46 GMT</pubDate>
            <atom:updated>2025-09-05T10:57:46.484Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N4Im4TzwGnnQ-1KuZkk4Jw.png" /></figure><p>In a microservices architecture, securing communication between services and authenticating users across distributed systems is non-trivial. JSON Web Tokens (JWTs) have emerged as the de facto standard for stateless authentication due to their lightweight structure and self-contained nature. However, with power comes responsibility — especially when it comes to <strong>key rotation</strong> and <strong>session invalidation</strong>. Let’s explore how to manage these critical aspects cleanly and securely in your microservices environment.</p><p><strong>Why JWTs Are Popular in Microservices</strong></p><p>JWTs are compact, URL-safe tokens that carry claims about a user or entity. Each token is cryptographically signed, ensuring data integrity and authenticity without the need for server-side session storage. This makes them a perfect match for microservices, where:</p><ul><li>Services can validate tokens independently.</li><li>There’s no need for centralized session stores.</li><li>System performance improves with fewer database hits.</li></ul><p>But JWTs are not without challenges — especially when tokens need to be invalidated or signing keys rotated.</p><p><strong>Understanding JWT Key Rotation</strong></p><p><strong>Key rotation</strong> refers to the practice of periodically updating the cryptographic keys used to sign JWTs. This is vital for:</p><ul><li>Mitigating the risk of key leaks.</li><li>Enforcing strong security compliance (e.g., PCI, HIPAA).</li><li>Reducing the blast radius of compromised tokens.</li></ul><p>JWTs can be signed using symmetric (HMAC) or asymmetric (RSA, ECDSA) keys. In microservices, <strong>asymmetric keys</strong> are preferred as they allow token verification without exposing the private key across services.</p><p><strong>Best Practices for JWT Key Rotation</strong></p><p>Rotating keys in a live production environment requires careful planning to avoid breaking authentication. Here’s how to do it cleanly:</p><p><strong>1. Use Key IDs (kid)</strong></p><p>Include a kid (Key ID) in the JWT header to identify which key was used to sign the token. This allows services to choose the correct key during verification.</p><pre>{<br>&quot;alg&quot;: &quot;RS256&quot;,<br>&quot;typ&quot;: &quot;JWT&quot;,<br>&quot;kid&quot;: &quot;key-2025–08&quot;<br>}</pre><p><strong>2. Maintain a Key Registry</strong></p><p>Store active and expired keys in a key registry or keystore. Services should look up the appropriate key using the kid from the JWT.</p><p><strong>3. Expose a JWKS Endpoint</strong></p><p>Publish your public keys via a JWKS (JSON Web Key Set) endpoint. Services can periodically fetch the latest keys to validate tokens.</p><p><strong>4. Support Graceful Rotation</strong></p><p>During rotation, keep both the old and new keys in your registry. Continue accepting tokens signed by the old key for a limited grace period.</p><p><strong>5. Automate Rotation</strong></p><p>Use secret management tools like <strong>HashiCorp Vault</strong>, <strong>AWS KMS</strong>, or <strong>Azure Key Vault</strong> to automate key generation, storage, and expiration.</p><p><strong>Handling Session Invalidation in JWTs</strong></p><p>JWTs are <strong>stateless</strong> — once issued, they’re valid until expiration. This means you can’t directly “kill” a token unless you add your own mechanisms. Here are strategies to make session invalidation work:</p><p><strong>1. Short-Lived Access Tokens</strong></p><p>Issue short-lived access tokens (e.g., 5–15 mins) and use refresh tokens to obtain new ones. This limits the window for abuse if a token is compromised.</p><p><strong>2. Refresh Tokens with Rotation</strong></p><p>Store refresh tokens securely (e.g., HTTP-only cookies) and rotate them on every use. Keep a list of valid refresh tokens per user/device in your database.</p><p><strong>3. Token Revocation Lists (Blacklists)</strong></p><p>Maintain a blacklist of revoked tokens (or jti values) in Redis or a fast-access store. On token validation, check if the jti is revoked.</p><p><strong>Token Versioning Strategy</strong></p><p>A simple yet effective way to invalidate sessions is by tying tokens to a <strong>version number</strong> stored in your database.</p><p><strong>How it works:</strong></p><ul><li>Embed token_version in the JWT payload.</li><li>On logout or password change, increment the version in the user record.</li><li>During validation, compare the version in the token against the DB value. If mismatched, reject the token.</li></ul><p>This approach works well without needing a full token blacklist.</p><p><strong>Real-World Implementation Tips</strong></p><p>To implement secure and maintainable JWT-based auth across microservices, consider these:</p><p><strong>1. Centralized Authentication Service</strong></p><p>Issue tokens from a centralized auth service. Other microservices should only <strong>verify</strong>, not <strong>issue</strong> JWTs.</p><p><strong>2. JWKS Caching and Fallback</strong></p><p>Cache JWKS responses locally and implement fallback logic in case of endpoint downtime.</p><p><strong>3. Critical Token Invalidation</strong></p><p>For high-risk actions (e.g., account deletion), use a Redis-based token blacklist with a TTL that matches the token’s remaining life.</p><p><strong>4. Use Robust Libraries</strong></p><p>Leverage libraries like:</p><ul><li><strong>jose</strong> or <strong>jsonwebtoken</strong> (Node.js)</li><li><strong>Auth0 JWT SDKs</strong></li><li><strong>Go-Jose</strong> for Go</li><li><strong>Nimbus JOSE + JWT</strong> for Java</li></ul><p><strong>Conclusion</strong></p><p>JWTs bring simplicity and scalability to microservices — but with that comes the need for deliberate planning around <strong>key rotation</strong> and <strong>session invalidation</strong>. By implementing structured key rotation with kid headers and JWKS, and by using refresh tokens, token versioning, or blacklists, you can maintain both security and flexibility.</p><p>Never treat JWTs as fire-and-forget. With automated tooling, versioning strategies, and short-lived tokens, your microservices can be both secure and stateless.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db30c1110fd7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Choosing the Right NoSQL DB for Your Java Backend]]></title>
            <link>https://techblogsbypallavi.medium.com/choosing-the-right-nosql-db-for-your-java-backend-750d8c078b79?source=rss-17c7e41052a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/750d8c078b79</guid>
            <category><![CDATA[nosql]]></category>
            <category><![CDATA[cassandra]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[mongodb]]></category>
            <dc:creator><![CDATA[Pallavi Shankar Sutar]]></dc:creator>
            <pubDate>Tue, 02 Sep 2025 13:19:26 GMT</pubDate>
            <atom:updated>2025-09-02T13:19:26.992Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ovs0l4oZLNIRjLlBh8YOyQ.png" /></figure><p>In today’s data-driven backend systems, <strong>NoSQL databases</strong> are essential for building fast, scalable, and flexible applications. While traditional relational databases (like MySQL or PostgreSQL) are still valuable, NoSQL offers performance and schema freedom that fits many modern Java use cases.</p><p>But with options like <strong>MongoDB</strong>, <strong>Cassandra</strong>, <strong>Redis</strong>, <strong>Couchbase</strong>, and <strong>Elasticsearch</strong>, how do you choose the right one for your Java backend?</p><p>Let’s break it down.</p><p><strong>🔹 What is NoSQL?</strong></p><p><strong>NoSQL</strong> stands for “Not Only SQL” — a family of databases that handle:</p><ul><li>Unstructured or semi-structured data</li><li>High scalability</li><li>Flexible schema design</li><li>Horizontal distribution</li></ul><p>Types of NoSQL databases:</p><ul><li><strong>Document-based</strong> (e.g., MongoDB)</li><li><strong>Key-value</strong> (e.g., Redis)</li><li><strong>Column-family</strong> (e.g., Cassandra)</li><li><strong>Graph-based</strong> (e.g., Neo4j)</li></ul><p>Each is suited to different backend needs.</p><p><strong>🔸 Factors to Consider for Java Backends</strong></p><p>When selecting a NoSQL DB for a Java backend, consider:</p><ol><li><strong>Data Model &amp; Query Needs</strong></li></ol><ul><li>Hierarchical or nested data? → MongoDB</li><li>High-speed lookups? → Redis</li><li>Time-series or logs? → Cassandra or Elasticsearch</li></ul><ol><li><strong>Consistency vs Availability (CAP Theorem)</strong></li></ol><ul><li>Do you need strong consistency or eventual consistency?</li></ul><ol><li><strong>Scalability Requirements</strong></li></ol><ul><li>Do you expect massive data volume or high concurrent reads/writes?</li></ul><ol><li><strong>Java Ecosystem Support</strong></li></ol><ul><li>Does the DB offer mature Java drivers or Spring Data integration?</li></ul><p><strong>🔸 Top NoSQL Databases for Java Projects</strong></p><p><strong>✅ 1. MongoDB — Best for Flexible Documents</strong></p><p><strong>Type:</strong> Document store<br> <strong>Use Cases:</strong> Product catalogs, user profiles, content management</p><ul><li>Stores data as JSON-like documents (BSON)</li><li>Ideal for nested, semi-structured data</li><li>Native support with Spring Data MongoDB</li></ul><p><strong>Example Integration:</strong></p><pre>@Document<br>public class User {<br>  @Id<br>  private String id;<br>  private String name;<br>  private List&lt;String&gt; roles;<br>}</pre><p>📌 <strong>Best for</strong>: Apps needing flexible schemas and rich querying.</p><p><strong>✅ 2. Redis — Best for In-Memory Speed</strong></p><p><strong>Type:</strong> Key-value store<br> <strong>Use Cases:</strong> Caching, session storage, rate limiting</p><ul><li>Blazing-fast in-memory access</li><li>Supports TTL, pub/sub, and persistence</li><li>Great for microservices and caching layers</li></ul><p><strong>Example Use Case:</strong></p><pre>@Cacheable(value = &quot;users&quot;, key = &quot;#userId&quot;)</pre><p>public User getUserById(String userId) { … }</p><p>📌 <strong>Best for</strong>: Real-time performance and lightweight data.</p><p><strong>✅ 3. Cassandra — Best for High-Volume Writes</strong></p><p><strong>Type:</strong> Wide-column store<br> <strong>Use Cases:</strong> Time-series data, IoT, analytics</p><ul><li>Linear scalability with no single point of failure</li><li>Tunable consistency levels</li><li>Designed for high write throughput</li></ul><p><strong>Java Integration:</strong></p><ul><li>Use DataStax Java Driver</li><li>Spring Data Cassandra support available</li></ul><p>📌 <strong>Best for</strong>: Write-heavy, geo-distributed systems.</p><p><strong>✅ 4. Couchbase — Document DB + Cache</strong></p><p><strong>Type:</strong> Document store with key-value capabilities<br> <strong>Use Cases:</strong> Mobile data sync, session stores</p><ul><li>Combines document model + key-value performance</li><li>Built-in caching and SQL-like query language (N1QL)</li><li>Java SDK and Spring Data support</li></ul><p>📌 <strong>Best for</strong>: Offline-first apps and high availability scenarios.</p><p><strong>✅ 5. Elasticsearch — Best for Search &amp; Logs</strong></p><p><strong>Type:</strong> Search engine / Document store<br> <strong>Use Cases:</strong> Full-text search, log analytics</p><ul><li>Schema-less JSON document storage</li><li>Powerful querying and aggregations</li><li>Java REST client and Spring Data Elasticsearch</li></ul><p>📌 <strong>Best for</strong>: Search-heavy apps and analytics dashboards.</p><p><strong>🔸 Comparison Table</strong></p><p><strong>Database</strong></p><p><strong>Type</strong></p><p><strong>Java Support</strong></p><p><strong>Use Case</strong></p><p>MongoDB</p><p>Document</p><p>✅ Spring Data</p><p>Flexible data models</p><p>Redis</p><p>Key-Value</p><p>✅ Spring Cache</p><p>High-speed caching</p><p>Cassandra</p><p>Column-Family</p><p>✅ DataStax Driver</p><p>High-throughput, large data</p><p>Couchbase</p><p>Document/KV</p><p>✅ Spring Data</p><p>Mobile sync, hybrid performance</p><p>Elasticsearch</p><p>Search/Doc</p><p>✅ Spring Data</p><p>Logging, search, analytics</p><p><strong>🔸 Final Decision Guide</strong></p><p><strong>Need</strong></p><p><strong>Recommended NoSQL DB</strong></p><p>Caching or sessions</p><p>Redis</p><p>Nested, dynamic data</p><p>MongoDB</p><p>Time-series / high writes</p><p>Cassandra</p><p>Search / full-text</p><p>Elasticsearch</p><p>Offline-ready + cache</p><p>Couchbase</p><p><strong>🔹 Conclusion</strong></p><p>There’s no one-size-fits-all NoSQL database. The right choice for your Java backend depends on your data patterns, scale, and performance needs.</p><p>The good news? Every major NoSQL solution offers strong Java SDKs or Spring Data integration, making it easier than ever to plug them into your architecture.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=750d8c078b79" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dockerizing Spring Boot Apps the Right Way]]></title>
            <link>https://techblogsbypallavi.medium.com/dockerizing-spring-boot-apps-the-right-way-0b906d760fdd?source=rss-17c7e41052a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/0b906d760fdd</guid>
            <category><![CDATA[dockerfiles]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[dockerizing]]></category>
            <dc:creator><![CDATA[Pallavi Shankar Sutar]]></dc:creator>
            <pubDate>Tue, 02 Sep 2025 10:13:25 GMT</pubDate>
            <atom:updated>2025-09-02T10:13:25.578Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8QH3WOdkxV5Iz958Si43cw.png" /></figure><p>Containerization has become a core practice in modern backend development. For Java developers, Docker offers a streamlined way to package and deploy Spring Boot applications across different environments with consistent behaviour.</p><p>In this blog, we’ll walk through how to Dockerize a Spring Boot app effectively, with real examples and best practices — including Docker Compose integration for managing multi-container environments.</p><p><strong>🔹 Preparing Your Spring Boot Application</strong></p><p>Before Dockerizing your Spring Boot app, ensure it’s set up to build a self-contained executable JAR. You can do this using either Maven or Gradle.</p><p><strong>✅ Maven Setup</strong></p><p>Ensure your pom.xml includes:</p><pre>&lt;build&gt;<br>&lt;plugins&gt;<br>&lt;plugin&gt;<br>&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>&lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;<br>&lt;/plugin&gt;<br>&lt;/plugins&gt;<br>&lt;/build&gt;</pre><p>Then, build the app with:</p><pre>./mvnw clean package</pre><p>This will create a fat JAR in the /target directory — perfect for Docker.</p><p><strong>🔸 Creating an Optimized Dockerfile</strong></p><p>Here’s a <strong>Docker Spring Boot example</strong> using a basic Dockerfile:</p><pre>FROM openjdk:17-jdk-slim<br>VOLUME /tmp<br>ARG JAR_FILE=target/*.jar<br>COPY ${JAR_FILE} app.jar<br>ENTRYPOINT [&quot;java&quot;,&quot;-jar&quot;,&quot;/app.jar&quot;]</pre><p><strong>🔍 Explanation:</strong></p><ul><li><strong>Base image</strong>: Uses a minimal JDK image to reduce size.</li><li><strong>COPY</strong>: Transfers the JAR to the container.</li><li><strong>ENTRYPOINT</strong>: Runs the application when the container starts.</li></ul><p><strong>🔸 Building and Running the Docker Image</strong></p><p><strong>🧱 Build the Docker image:</strong></p><pre>docker build -t my-spring-app .</pre><p><strong>🚀 Run the container:</strong></p><pre>docker run -p 8080:8080 my-spring-app</pre><p>Your Spring Boot app should now be available at <a href="http://localhost:8080.">http://localhost:8080.</a></p><p><strong>🔸 Adding Docker Compose for Multi-Container Setup</strong></p><p>If your application connects to a database or other services, Docker Compose can simplify orchestration.</p><p><strong>✅ Example: Spring Boot + PostgreSQL</strong></p><p>Create a docker-compose.yml:</p><pre>version: &#39;3.8&#39;<br>services:<br>app:<br>build: .<br>ports:<br>- &quot;8080:8080&quot;<br>depends_on:<br>- db<br>environment:<br>SPRING_DATASOURCE_URL: jdbc:postgresql://db:5432/mydb<br>SPRING_DATASOURCE_USERNAME: user<br>SPRING_DATASOURCE_PASSWORD: password<br>db:<br>image: postgres:13<br>environment:<br>POSTGRES_DB: mydb<br>POSTGRES_USER: user<br>POSTGRES_PASSWORD: password<br>ports:<br>- &quot;5432:5432&quot;</pre><p><strong>🌐 Run both services:</strong></p><pre>docker-compose up - build</pre><p>This spins up both your Spring Boot app and PostgreSQL database, fully wired via environment variables.</p><p><strong>🔸 Best Practices for Dockerizing Spring Boot Apps</strong></p><p><strong>✅ 1. Use Lightweight Base Images</strong></p><p>Instead of openjdk, consider eclipse-temurin or distroless for production:</p><pre>FROM eclipse-temurin:17-jre-alpine</pre><p><strong>✅ 2. Externalize Configuration</strong></p><p>Avoid hardcoding sensitive values. Use environment variables or bind-mount external config files.</p><pre>docker run -e SPRING_PROFILES_ACTIVE=prod -p 8080:8080 my-spring-app</pre><p><strong>✅ 3. Use .dockerignore</strong></p><p>Prevent unnecessary files from bloating the image:</p><p>target/</p><p>.git/</p><p>*.md</p><p><strong>✅ 4. Add Health Checks in Compose</strong></p><p>healthcheck:</p><p>test: [“CMD”, “curl”, “-f”, “http://localhost:8080/actuator/health&quot;]</p><p>interval: 30s</p><p>timeout: 10s</p><p>retries: 5</p><p><strong>✅ 5. Use Multi-Stage Builds (Optional)</strong></p><p>For cleaner builds with Maven inside Docker:</p><p># Build Stage</p><pre>FROM maven:3.8.5-openjdk-17 AS build<br>COPY . /app<br>WORKDIR /app<br>RUN mvn clean package</pre><p># Run Stage</p><pre>FROM openjdk:17-jdk-slim<br>COPY - from=build /app/target/*.jar app.jar<br>ENTRYPOINT [&quot;java&quot;, &quot;-jar&quot;, &quot;/app.jar&quot;]</pre><p><strong>🔹 Conclusion</strong></p><p>Dockerizing Spring Boot apps isn’t just about running your app in a container — it’s about doing it in a way that supports scalability, environment consistency, and collaboration. With a clean Dockerfile, efficient image layering, and Docker Compose for multi-service setups, you can prepare your backend for real-world deployment pipelines.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0b906d760fdd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating Redis for Caching in Java Applications]]></title>
            <link>https://techblogsbypallavi.medium.com/integrating-redis-for-caching-in-java-applications-04c7a14a0202?source=rss-17c7e41052a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/04c7a14a0202</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[redis-cache]]></category>
            <dc:creator><![CDATA[Pallavi Shankar Sutar]]></dc:creator>
            <pubDate>Thu, 21 Aug 2025 07:30:30 GMT</pubDate>
            <atom:updated>2025-08-21T07:30:30.659Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xmTgQOf8fBZfGv-PBvmj1Q.png" /></figure><p><strong>🔹 Introduction</strong></p><p>In high-performance Java applications, database calls and external API requests can become bottlenecks. That’s where caching comes in — and <strong>Redis</strong> is one of the most popular solutions for ultra-fast, in-memory caching.</p><p>In this post, we’ll explore how to integrate Redis into Java applications using Spring Boot, complete with examples and best practices.</p><p><strong>🔸 Why Use Redis for Caching?</strong></p><p>Redis (Remote Dictionary Server) is a blazing-fast, in-memory key-value store. It supports:</p><ul><li>Microsecond latency</li><li>Persistence (optional)</li><li>Data structures like hashes, lists, sets</li><li>Pub/Sub messaging</li><li>Built-in replication and clustering</li></ul><p>For Java apps, Redis helps reduce:</p><ul><li>Repeated database hits</li><li>Expensive computations</li><li>External API latency</li></ul><p><strong>🔸 Use Cases of Redis Caching in Java Apps</strong></p><ol><li><strong>Database Query Caching</strong><br> Cache expensive SELECT queries for faster access.</li><li><strong>Session Management</strong><br> Store and retrieve user sessions in distributed apps.</li><li><strong>Rate Limiting / Throttling</strong><br> Control request frequency using Redis counters.</li><li><strong>Configuration or Metadata Caching</strong><br> Frequently used data that changes rarely.</li></ol><p><strong>🔸 Redis Integration with Spring Boot</strong></p><p>Spring Boot makes Redis integration seamless using spring-boot-starter-data-redis.</p><p><strong>✅ Step 1: Add Dependencies</strong></p><p>For Maven:</p><pre>&lt;dependency&gt;<br>&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>&lt;artifactId&gt;spring-boot-starter-data-redis&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p>For Gradle:</p><pre>dependencies {<br>    implementation &#39;org.springframework.boot:spring-boot-starter-data-redis&#39;<br>}</pre><p><strong>✅ Step 2: Configure Redis in application.properties</strong></p><pre>spring.cache.type=redis<br>spring.redis.host=localhost<br>spring.redis.port=6379</pre><p>Make sure Redis is installed and running locally, or use Docker:</p><pre>docker run - name redis -p 6379:6379 redis</pre><p><strong>✅ Step 3: Enable Caching</strong></p><p>Add the @EnableCaching annotation to your main class:</p><pre>@SpringBootApplication<br>@EnableCaching<br>public class MyApp { … }</pre><p><strong>✅ Step 4: Use @Cacheable in Service Methods</strong></p><pre>@Cacheable(value = &quot;users&quot;, key = &quot;#userId&quot;)<br>public User getUserById(String userId) {<br>simulateSlowService(); // Simulate DB call<br>return userRepository.findById(userId).orElse(null);<br>}</pre><p>The first call fetches from DB; subsequent calls return from Redis.</p><p><strong>✅ Other Caching Annotations:</strong></p><ul><li>@CachePut — updates the cache</li><li>@CacheEvict — removes from cache</li></ul><p><strong>🔸 Example: Caching Product Data</strong></p><pre>@Service<br>public class ProductService {<br>  @Cacheable(value = &quot;products&quot;, key = &quot;#id&quot;)<br>  public Product getProductById(String id) {<br>    return productRepository.findById(id).orElseThrow();<br>  }<br><br>  @CacheEvict(value = &quot;products&quot;, key = &quot;#id&quot;)<br>  public void deleteProduct(String id) {<br>    productRepository.deleteById(id);<br>  }<br>}</pre><p>This setup keeps your product cache fresh and responsive.</p><p><strong>🔸 Best Practices for Using Redis in Java</strong></p><p><strong>✅ Set TTL (Time To Live)</strong></p><p>Prevent stale cache and memory bloat:</p><pre>@Bean<br>public RedisCacheManager cacheManager(RedisConnectionFactory factory) {<br>RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()<br>.entryTtl(Duration.ofMinutes(10));<br>return RedisCacheManager.builder(factory).cacheDefaults(config).build();<br>}</pre><p><strong>✅ Avoid Caching Null Values</strong></p><p>Update config to ignore nulls:</p><p>config.disableCachingNullValues();</p><p><strong>✅ Use Meaningful Keys</strong></p><p>Combine value + ID (user::123) to avoid key collision.</p><p><strong>✅ Monitor Redis Usage</strong></p><p>Use Redis CLI, Prometheus, or RedisInsight for monitoring.</p><p><strong>🔸 Redis Serialization Options</strong></p><p>Spring Redis uses <strong>JDK serialization</strong> by default. For better readability and performance, switch to JSON:</p><pre>@Bean<br>public RedisTemplate&lt;String, Object&gt; redisTemplate(RedisConnectionFactory factory) {<br>  RedisTemplate&lt;String, Object&gt; template = new RedisTemplate&lt;&gt;();<br>  template.setConnectionFactory(factory);<br>  template.setValueSerializer(new GenericJackson2JsonRedisSerializer());<br>  return template;<br>}</pre><p><strong>🔹 Conclusion</strong></p><p>Integrating Redis for caching in Java applications can significantly boost performance, reduce latency, and offload pressure from databases. With Spring Boot’s easy annotations and configuration, you can implement Redis caching in minutes.</p><p>Whether you’re optimizing API response times, handling high traffic, or managing session state, Redis proves to be a scalable and reliable choice for backend Java developers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=04c7a14a0202" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Event-Driven Architecture with Kafka in Java Projects]]></title>
            <link>https://techblogsbypallavi.medium.com/event-driven-architecture-with-kafka-in-java-projects-71a461d4e8f7?source=rss-17c7e41052a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/71a461d4e8f7</guid>
            <category><![CDATA[kafka-consumer]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[apache-kafka]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Pallavi Shankar Sutar]]></dc:creator>
            <pubDate>Wed, 20 Aug 2025 05:54:02 GMT</pubDate>
            <atom:updated>2025-08-20T05:54:02.226Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K7rIwo7z71i_fCwjY-z5CQ.png" /></figure><p>Modern backend systems need to be fast, scalable, and loosely coupled. Traditional monolithic designs often fall short when data needs to flow in real-time across distributed components. That’s where <strong>Event-Driven Architecture (EDA)</strong> steps in — and <strong>Apache Kafka</strong> is one of its most powerful enablers.</p><p>This guide explores how Java developers can use Kafka to build event-driven systems that are resilient, modular, and production-ready.</p><p><strong>🔹 What is Event-Driven Architecture?</strong></p><p>In event-driven architecture, components communicate through <strong>events</strong> — significant changes in state. Instead of direct API calls or tight coupling, services <strong>emit</strong> and <strong>react</strong> to events asynchronously.</p><p>This model enables:</p><ul><li><strong>Loose coupling</strong> of components</li><li><strong>Real-time processing</strong></li><li>Better <strong>horizontal scalability</strong></li></ul><p><strong>🔸 Kafka’s Role in Event-Driven Java Systems</strong></p><p><strong>Apache Kafka</strong> is a distributed streaming platform purpose-built for EDA. It acts as a high-throughput event log where producers write data and consumers subscribe to it.</p><p><strong>Key Concepts:</strong></p><ul><li><strong>Topics</strong>: Logical channels for events (e.g., user.registered)</li><li><strong>Partitions</strong>: Scalable logs inside each topic</li><li><strong>Producers</strong>: Java services that publish events</li><li><strong>Consumers</strong>: Services that subscribe to events</li><li><strong>Brokers</strong>: Kafka servers storing and serving events</li></ul><p>Kafka helps Java microservices communicate asynchronously while staying decoupled.</p><p><strong>🔸 When to Use Kafka in Java Projects</strong></p><p>Kafka shines in scenarios like:</p><ul><li><strong>Microservices Communication</strong>: Services interact through published events.</li><li><strong>Audit Logging</strong>: Record actions without blocking main flows.</li><li><strong>Real-Time Data Flow</strong>: Stream orders, clicks, or metrics instantly.</li><li><strong>Command and Event Separation</strong>: Better fault tolerance and reactivity.</li></ul><p><strong>🔸 Kafka Integration with Spring Boot</strong></p><p>Spring Boot makes Kafka integration seamless via spring-kafka.</p><p><strong>Step 1: Add Maven Dependency</strong></p><pre>&lt;dependency&gt;<br>&lt;groupId&gt;org.springframework.kafka&lt;/groupId&gt;<br>&lt;artifactId&gt;spring-kafka&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p><strong>Step 2: Kafka Producer Configuration</strong></p><pre>@Bean<br>public KafkaTemplate&lt;String, String&gt; kafkaTemplate(ProducerFactory&lt;String, String&gt; pf) {<br>return new KafkaTemplate&lt;&gt;(pf);<br>}</pre><p><strong>Step 3: Send an Event</strong></p><pre>@Autowired<br>private KafkaTemplate&lt;String, String&gt; kafkaTemplate;<br>public void publishUserCreatedEvent(String userJson) {<br>kafkaTemplate.send(&quot;user.registered&quot;, userJson);<br>}</pre><p><strong>Step 4: Kafka Consumer Example</strong></p><pre>@KafkaListener(topics = &quot;user.registered&quot;, groupId = &quot;user-service&quot;)<br>public void consume(String message) {<br>System.out.println(&quot;Consumed event: &quot; + message);<br>}</pre><p>You can scale consumers by adding more instances to the same consumer group.</p><p><strong>🔸 Designing an Event-Driven Flow: A Real Example</strong></p><p>Let’s say you’re building a user registration system.</p><ol><li>UserService creates a new user and publishes a user.registered event.</li><li>EmailService listens to this event and sends a welcome email.</li><li>AnalyticsService logs the registration for tracking.</li></ol><p>None of these services call each other directly — they only interact through Kafka.</p><p><strong>✅ Schema Design</strong></p><p>Choose a consistent event schema format:</p><ul><li><strong>JSON</strong> (flexible, widely supported)</li><li><strong>Avro</strong> (compact, schema evolution support)</li></ul><p>Example JSON payload:</p><pre>{<br>&quot;userId&quot;: &quot;123&quot;,<br>&quot;email&quot;: &quot;test@example.com&quot;,<br>&quot;timestamp&quot;: &quot;2025–08–17T10:00:00Z&quot;<br>}</pre><p><strong>🔸 Best Practices for Kafka in Java</strong></p><p><strong>✅ Use Idempotent Producers</strong></p><p>Avoid sending duplicate events on retries using enable.idempotence=true.</p><p><strong>✅ Proper Topic Naming</strong></p><p>Use consistent naming like entity.action (e.g., order.placed, payment.failed).</p><p><strong>✅ Partitioning Strategy</strong></p><p>Partition by user ID or order ID to preserve event order per entity.</p><p><strong>✅ Handle Failures Gracefully</strong></p><p>Use Dead Letter Topics and logging for failed message processing.</p><p><strong>✅ Secure Your Kafka Cluster</strong></p><p>Enable SSL, authentication (SASL), and proper ACLs.</p><p><strong>🔹 Conclusion</strong></p><p>Event-driven architecture enables scalable, loosely coupled systems and Apache Kafka is the backbone for implementing it effectively in Java.</p><p>With tools like Spring Boot and spring-kafka, you can set up producers and consumers quickly, handle millions of messages efficiently, and design systems that react to changes in real time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71a461d4e8f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling Concurrency in Java: Executors, CompletableFuture & Beyond]]></title>
            <link>https://techblogsbypallavi.medium.com/handling-concurrency-in-java-executors-completablefuture-beyond-f42c76ee1e98?source=rss-17c7e41052a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/f42c76ee1e98</guid>
            <category><![CDATA[completablefuture-in-java]]></category>
            <category><![CDATA[java8]]></category>
            <category><![CDATA[java-8-feature]]></category>
            <category><![CDATA[completablefuture]]></category>
            <dc:creator><![CDATA[Pallavi Shankar Sutar]]></dc:creator>
            <pubDate>Tue, 19 Aug 2025 08:26:14 GMT</pubDate>
            <atom:updated>2025-08-19T08:26:14.422Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k84oChJH4B3odafAus7GQA.png" /></figure><p>Concurrency is a critical concept in modern Java backend development. As systems scale and demand high performance, writing thread-safe and non-blocking code becomes essential. Java offers robust concurrency tools, but knowing <em>when and how to use them</em> can make or break your application’s efficiency.</p><p>In this blog, we’ll explore the evolution of concurrency in Java — from classic threads to modern tools like ExecutorService and CompletableFuture. Let’s dive in.</p><p><strong>🔹 Understanding Java Concurrency Basics</strong></p><p>Before Java 5, concurrency was primarily handled using Thread and Runnable. Here’s a basic example:</p><pre>Thread thread = new Thread(() -&gt; {<br>System.out.println(&quot;Running in a separate thread&quot;);<br>});<br>thread.start();</pre><p>While simple, this approach lacks control over thread pooling, error handling, and scalability. Manually managing threads is error-prone and should be avoided in real-world systems.</p><p><strong>🔹 Using Executors for Thread Management</strong></p><p>The ExecutorService interface, introduced in Java 5, abstracts away manual thread creation. It provides better control, reusability, and thread pooling.</p><p><strong>✅ Example: Using Fixed Thread Pool</strong></p><pre>ExecutorService executor = Executors.newFixedThreadPool(3);<br>executor.submit(() -&gt; {<br>System.out.println(&quot;Task executed by: &quot; + Thread.currentThread().getName());<br>});<br>executor.shutdown();</pre><p>This is ideal when you need to run multiple short-lived tasks without overloading the system.</p><p><strong>✅ Key Features:</strong></p><ul><li>Controlled number of threads</li><li>Task scheduling</li><li>Graceful shutdown with shutdown() and awaitTermination()</li></ul><p><strong>🔹 CompletableFuture: The Modern Asynchronous API</strong></p><p>Java 8 introduced CompletableFuture — a powerful API that makes async programming more readable and composable.</p><p>It improves upon Future by allowing:</p><ul><li>Non-blocking async calls</li><li>Chaining of dependent tasks</li><li>Better exception handling</li></ul><p><strong>🔍 CompletableFuture Example: Basic Async Task</strong></p><pre>CompletableFuture&lt;Void&gt; future = CompletableFuture.runAsync(() -&gt;<br>System.out.println(&quot;Running async task in: &quot; + Thread.currentThread().getName())<br>);</pre><p><strong>🔗 Chaining with thenApply() and thenCompose()</strong></p><pre>CompletableFuture&lt;String&gt; greeting = CompletableFuture.supplyAsync(() -&gt; &quot;Hello&quot;)<br>.thenApply(str -&gt; str + &quot; World&quot;);<br>System.out.println(greeting.get()); <br><br>//output Hello World</pre><p><strong>🚨 Exception Handling</strong></p><pre>CompletableFuture&lt;String&gt; task = CompletableFuture.supplyAsync(() -&gt; {<br>if (true) throw new RuntimeException(&quot;Failed!&quot;);<br>return &quot;Success&quot;;<br>}).exceptionally(ex -&gt; &quot;Recovered: &quot; + ex.getMessage());<br>System.out.println(task.get());</pre><p><strong>🔹 Advanced Techniques &amp; Real-World Use Cases</strong></p><p><strong>🔗 Combining Multiple Async Tasks</strong></p><pre>CompletableFuture&lt;String&gt; task1 = CompletableFuture.supplyAsync(() -&gt; &quot;API-1&quot;);<br>CompletableFuture&lt;String&gt; task2 = CompletableFuture.supplyAsync(() -&gt; &quot;API-2&quot;);<br>CompletableFuture&lt;Void&gt; all = CompletableFuture.allOf(task1, task2);<br>all.thenRun(() -&gt; {<br>try {<br>System.out.println(task1.get() + &quot; &amp; &quot; + task2.get());<br>} catch (Exception e) { e.printStackTrace(); }<br>});</pre><p>This is useful for parallel API calls, DB queries, or file processing — especially in microservices.</p><p><strong>🤝 Integration with Spring Boot</strong></p><pre>@Async<br>public CompletableFuture&lt;String&gt; asyncMethod() {<br>return CompletableFuture.completedFuture(&quot;Async result&quot;);<br>}</pre><p>To enable, annotate your config class with @EnableAsync.</p><p><strong>🔹 Best Practices for Java Concurrency</strong></p><ul><li><strong>Don’t over-thread</strong>: Too many threads cause CPU contention.</li><li><strong>Use proper thread pools</strong>: Fixed or cached depending on workload.</li><li><strong>Prefer CompletableFuture</strong> for readability and async chaining.</li><li><strong>Debug concurrency issues</strong> with tools like:</li><li>JVisualVM</li><li>Java Flight Recorder (JFR)</li><li>Thread dumps during high CPU loads</li></ul><p><strong>✅ Conclusion</strong></p><p>Java provides a rich set of tools to handle concurrency, from ExecutorService for structured thread management to CompletableFuture for elegant asynchronous workflows. Mastering these will make your backend code more efficient, responsive, and scalable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f42c76ee1e98" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Introduction to Spring Reactive Programming]]></title>
            <link>https://techblogsbypallavi.medium.com/an-introduction-to-spring-reactive-programming-6d86464b7ebe?source=rss-17c7e41052a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d86464b7ebe</guid>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[webflux]]></category>
            <category><![CDATA[spring-reactive]]></category>
            <category><![CDATA[mono]]></category>
            <dc:creator><![CDATA[Pallavi Shankar Sutar]]></dc:creator>
            <pubDate>Tue, 14 Jan 2025 14:42:08 GMT</pubDate>
            <atom:updated>2025-01-14T14:42:08.218Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s3sVblssZVxrX2dVIWIdLA.png" /></figure><p>In the ever-evolving world of software development, building responsive and scalable applications is becoming increasingly critical. Reactive programming, an asynchronous programming paradigm, has emerged as a powerful solution to these demands. In this blog, we’ll explore how Spring Framework leverages reactive programming to provide developers with a robust and efficient toolkit for modern applications.</p><p><strong>What is Reactive Programming?</strong></p><p>Reactive programming is a declarative programming paradigm centred around asynchronous data streams. In essence, it allows developers to register callbacks and react to data changes or events as they occur. This approach makes it well-suited for systems that handle large volumes of data, need low latency, or require high concurrency.</p><p>Key characteristics of reactive programming include:</p><ul><li><strong>Asynchronous</strong>: Non-blocking operations allow tasks to be executed concurrently without waiting for others to complete.</li><li><strong>Event-driven</strong>: Actions are triggered in response to events or data changes.</li><li><strong>Backpressure</strong>: A mechanism to control the data flow and prevent overwhelming the consumer.</li></ul><p>Reactive programming aligns closely with the Reactive Streams specification, which defines the standard for asynchronous stream processing with non-blocking backpressure.</p><p><strong>Core Components of Spring Reactive Programming:</strong></p><ol><li><strong>Reactor Library</strong>:<br> At the heart of Spring’s reactive programming is <strong>Project Reactor</strong>, which provides two main types:</li></ol><ul><li><strong>Mono</strong>: Represents a single value or no value (like Optional).</li><li><strong>Flux</strong>: Represents a stream of zero or more values.</li></ul><ol><li><strong>Spring WebFlux</strong>:<br> A reactive web framework built on top of Project Reactor, supporting non-blocking HTTP request processing.</li><li><strong>Reactive Repositories</strong>:<br> Part of Spring Data, it allows reactive access to databases.</li></ol><p><strong>Benefits of Spring Reactive Programming</strong></p><ol><li><strong>High Scalability</strong>: Non-blocking I/O enables applications to handle thousands of concurrent requests with minimal resource usage.</li><li><strong>Better Resource Utilization</strong>: By avoiding thread-blocking operations, reactive programming makes efficient use of system resources.</li><li><strong>Responsive Applications</strong>: Applications built with reactive programming are inherently more responsive, as they can process data as it arrives without waiting for entire datasets.</li><li><strong>Seamless Integration</strong>: Spring’s reactive modules integrate seamlessly with other Spring projects, such as Spring Data and Spring Security.</li></ol><p>Here’s a basic example of a reactive REST API built using Spring WebFlux.</p><pre>import org.springframework.web.bind.annotation.GetMapping;<br>import org.springframework.web.bind.annotation.RestController;<br>import reactor.core.publisher.Flux;<br><br>@RestController<br>public class ReactiveController {<br><br>    @GetMapping(&quot;/numbers&quot;)<br>    public Flux&lt;Integer&gt; streamNumbers() {<br>        return Flux.range(1, 10); // Stream numbers 1 through 10<br>    }<br>}</pre><p><strong>Explanation</strong></p><ul><li><strong>Flux.range(1, 10)</strong>: Creates a stream of integers from 1 to 10.</li><li>The /numbers endpoint returns the numbers as a reactive stream. Each number is sent to the client as it’s generated.</li></ul><p><strong>When to Use Spring WebFlux</strong></p><p>While Spring WebFlux offers numerous advantages, it isn’t always the right choice. Consider using WebFlux if:</p><ul><li>Your application requires high concurrency and low latency.</li><li>You’re building microservices that rely heavily on non-blocking I/O.</li><li>You need to process data streams or events in real-time.</li></ul><p>For applications with simpler requirements or where blocking I/O is predominant, the traditional Spring MVC model may be a better fit.</p><p><strong>Conclusion</strong></p><p>Spring Reactive Programming, with its foundation in Spring WebFlux and Project Reactor, empowers developers to build responsive, resilient, and scalable applications. By embracing the reactive paradigm, organizations can better meet the demands of modern software systems. Whether you’re building microservices, real-time applications, or handling large-scale data streams, Spring’s reactive stack is a tool worth exploring.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d86464b7ebe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Microservices Service Discovery with Eureka]]></title>
            <link>https://techblogsbypallavi.medium.com/microservices-service-discovery-with-eureka-84649bf5b665?source=rss-17c7e41052a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/84649bf5b665</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[service-discovery]]></category>
            <category><![CDATA[spring-cloud]]></category>
            <category><![CDATA[eureka]]></category>
            <dc:creator><![CDATA[Pallavi Shankar Sutar]]></dc:creator>
            <pubDate>Fri, 22 Nov 2024 15:14:50 GMT</pubDate>
            <atom:updated>2024-11-22T15:14:50.235Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dd3Bzzym9GpqchVgNnAGzg.png" /></figure><p>Microservices architecture has revolutionized the way we design and deploy applications by breaking them into smaller, loosely coupled, independently deployable services. However, with this approach comes the challenge of enabling seamless communication between these services. Service discovery is a critical component in microservices architecture, ensuring that services can dynamically locate and interact with each other without hardcoding dependencies. Eureka, a service discovery tool developed by Netflix, is widely adopted in this domain.</p><p>In this blog, we’ll explore Eureka, its components, how it works, and the steps to integrate it into a microservices ecosystem.</p><p><strong>What is Eureka?</strong></p><p>Eureka is a REST-based service registry that enables services to register themselves and discover other services. It plays a key role in dynamic scaling, load balancing, and fault tolerance. Eureka is part of the Netflix OSS (Open-Source Software) suite and is particularly known for its integration with Spring Cloud.</p><p><strong>Why Service Discovery?</strong></p><p>In microservices, services often run on dynamic infrastructure like containers or virtual machines. Their locations (IP addresses and ports) change frequently due to scaling, failure, or redeployment. Manually tracking these changes is infeasible. Service discovery automates this process by maintaining a registry of all services and their instances.</p><p><strong>Key Components of Eureka:</strong></p><ol><li><strong>Eureka Server:</strong></li></ol><p>It acts as the service registry, maintaining a registry of all available services and their instances. It also provides an API for registration, renewal (heartbeat), and deregistration.</p><p><strong>2. Eureka Client:</strong></p><p>It is a library embedded in microservices to interact with the Eureka Server. It registers the service instance with the Eureka server and periodically sends heartbeats to renew its registration.</p><p><strong>3. Service Registry:</strong></p><p>It is a database maintained by the Eureka Server to store information about service instances. It includes metadata like service name, IP address, port, status, and instance ID.</p><p><strong>How Eureka Works:</strong></p><p><strong>1. Service Registration:</strong> When a service instance starts, it registers itself with the Eureka Server by providing its metadata.</p><p><strong>2. Service Renewal:</strong> To ensure that the instance is still healthy, it sends periodic heartbeat signals to the server. If a heartbeat is missed for a configured period, the instance is marked as unavailable.</p><p><strong>3. Service Discovery:</strong> A service querying the Eureka Server receives a list of available instances for a given service. The client-side load balancer (e.g., Ribbon) can use this information to route requests to the appropriate instance.</p><p><strong>4. Instance Removal:</strong> When an instance shuts down or fails, it is removed from the registry either through explicit deregistration or by the server marking it as unavailable after a timeout.</p><p><strong>Setting Up Eureka in a Microservices Ecosystem:</strong></p><ol><li><strong>Eureka Server Setup: </strong>Add the below dependencies to your Spring Boot application</li></ol><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-cloud-starter-netflix-eureka-server&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p>Under dependency management add spring cloud dependency:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-cloud-dependencies&lt;/artifactId&gt;<br>    &lt;version&gt;2023.0.3&lt;/version&gt;<br>    &lt;type&gt;pom&lt;/type&gt;<br>    &lt;scope&gt;import&lt;/scope&gt;<br>&lt;/dependency&gt;</pre><p>Enable Eureka Server in your main application class:</p><pre>@SpringBootApplication<br>@EnableEurekaServer<br>public class EurekaApplication {<br>    public static void main(String[] args) {<br>      SpringApplication.run(EurekaApplication.class, args);<br>     }<br>}</pre><p>Configure application.properties:</p><pre>server.port=8761<br>eureka.instance.hostname=localhost<br>eureka.client.registerWithEureka=false<br>eureka.client.fetchRegistry=false<br>eureka.client.serviceUrl.defaultZone=http://${eureka.instance.hostname}:${server.port}/eureka</pre><p><strong>2. Eureka Client Setup</strong>: Add dependencies to your service</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-cloud-starter-netflix-eureka-client&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p>Under dependency management add spring cloud dependency:</p><pre>&lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-cloud-dependencies&lt;/artifactId&gt;<br>   &lt;version&gt;2023.0.3&lt;/version&gt;<br>   &lt;type&gt;pom&lt;/type&gt;<br>   &lt;scope&gt;import&lt;/scope&gt;<br>&lt;/dependency&gt;</pre><p>Enable Eureka Client in your main application class:</p><pre>@SpringBootApplication<br>@EnableDiscoveryClient<br>public class EurekaClientApplication {<br>   public static void main(String[] args) {<br>      SpringApplication.run(CustomerServiceApplication.class, args);<br>  }<br>}</pre><p>Configure application.properties:</p><pre>server.port=8090<br>eureka.instance.preferIpAddress = true <br>eureka.client.registerWithEureka = true<br>eureka.client.fetchRegistry = true<br>eureka.client.serviceUrl.defaultZone = http://localhost:8761/eureka</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O7mKQu44elbc0L0VhP9McQ.png" /></figure><p><strong>Advantages of Eureka:</strong></p><blockquote>Dynamic Service Management: No need to manually manage service instances.</blockquote><blockquote>Scalability: Can handle a large number of service instances in distributed systems.</blockquote><blockquote>Integration: Seamlessly integrates with other Spring Cloud components like Ribbon, Hystrix and Zuul.</blockquote><p><strong>Conclusion</strong></p><p>Eureka simplifies service discovery in microservices by providing a dynamic, centralized registry. Its seamless integration with Spring Cloud makes it a go-to choice for Java-based microservices. Integrating Eureka into your microservices ecosystem unlocks numerous possibilities for automation and scalability. With proper configuration and understanding, it becomes a cornerstone for effective microservices communication.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84649bf5b665" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>