<?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 Puspalata Sahoo on Medium]]></title>
        <description><![CDATA[Stories by Puspalata Sahoo on Medium]]></description>
        <link>https://medium.com/@puspas99?source=rss-730bca56049c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*e-6UGPO25Eu5YUap.</url>
            <title>Stories by Puspalata Sahoo on Medium</title>
            <link>https://medium.com/@puspas99?source=rss-730bca56049c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 25 Nov 2026 02:51:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@puspas99/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[Event Sourcing vs. Event-Driven Architecture: A Clear-Cut Guide for Modern Systems]]></title>
            <link>https://medium.com/@puspas99/event-sourcing-vs-event-driven-architecture-a-clear-cut-guide-for-modern-systems-a49acc66c619?source=rss-730bca56049c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a49acc66c619</guid>
            <dc:creator><![CDATA[Puspalata Sahoo]]></dc:creator>
            <pubDate>Sat, 12 Jul 2025 06:17:45 GMT</pubDate>
            <atom:updated>2025-07-12T06:17:45.795Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s fast-moving software landscape, two architectural paradigms — <strong>event sourcing</strong> and <strong>event-driven architecture</strong> — are gaining widespread adoption. While they sound similar, they serve different purposes and can be used independently or together.</p><p>Let’s break them down and look at how and when to use each one effectively.</p><h3>What Is Event Sourcing?</h3><p><strong>Event sourcing</strong> is a data modeling pattern where every state change is recorded as a discrete event, rather than just storing the final state.</p><p>Instead of storing the latest balance of an account, we store every transaction that led to it.</p><p>🧾 Example:<br> Instead of updating a customer’s balance from $100 to $150, you record an event like:</p><p>CustomerDeposited($50)</p><h3>Event Sourcing Model</h3><ol><li>User action (e.g., “Deposit $50”)</li><li>Event created → CustomerDeposited($50)</li><li>Event stored in an event log</li><li>State rehydrated by replaying events</li></ol><h3>Benefits:</h3><ul><li><strong>Complete audit trail</strong></li><li><strong>Time-travel debugging</strong>: You can reconstruct past states</li><li><strong>Flexible projections</strong>: Build multiple read models from the same event stream</li></ul><h3>Challenges:</h3><ul><li>Complex event versioning</li><li>Querying current state requires projections</li><li>Not always intuitive for CRUD-centric teams</li></ul><h3>What Is Event-Driven Architecture?</h3><p><strong>Event-driven architecture (EDA)</strong> is a system design pattern where services communicate by producing and consuming <strong>events</strong>.</p><p>Each service listens for events it cares about and reacts to them independently.</p><pre>⚙️ Example:<br> A PaymentService emits a PaymentCompleted event.<br> The ShippingService listens for this event and triggers the shipment workflow.</pre><h3>Event-Driven System</h3><p><strong>Description</strong>: A microservices diagram:</p><ul><li>OrderService → emits OrderPlaced</li><li>InventoryService and NotificationService → consume that event</li><li>Arrows represent async event flow via a message broker (Kafka, RabbitMQ, etc.)</li></ul><h3>Benefits:</h3><ul><li><strong>Loose coupling</strong> between services</li><li><strong>Asynchronous and scalable</strong></li><li><strong>Resilient to failure</strong> — services can retry on failure</li></ul><h3>Challenges:</h3><ul><li>Event tracing across systems is complex</li><li>Requires robust tooling for event delivery, retries, and monitoring</li></ul><h3>How They Work Together</h3><p>You don’t have to choose between them.</p><ul><li><strong>Event sourcing</strong> is <em>how</em> you store state.</li><li><strong>Event-driven</strong> is <em>how</em> your services communicate.</li></ul><p>A service using event sourcing can naturally <strong>emit events</strong> to the outside world, powering an event-driven architecture.</p><pre>🎯 Think of event sourcing as the internal story,<br>and event-driven architecture as the external conversation.</pre><h3>Event Sourcing + EDA Combined</h3><ol><li>A service stores domain events internally using event sourcing.</li><li>Certain events are published to an event bus.</li><li>External services consume these events.</li></ol><h3>When to Use Each:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nWnCNKeVcYpwRWGf" /></figure><h3>Final Thoughts</h3><p>Both <strong>event sourcing</strong> and <strong>event-driven architecture</strong> are valuable tools for building modern, resilient systems — but they solve different problems.</p><ul><li>Use <strong>event sourcing</strong> to model state changes and keep a complete, replayable history.</li><li>Use <strong>event-driven architecture</strong> to enable loose coupling and responsive system behavior.</li></ul><p>These patterns are not competitors. In fact, when used together, they form the foundation of highly scalable and maintainable distributed systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a49acc66c619" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ How to Create Custom Annotations in Java (Step-by-Step)]]></title>
            <link>https://medium.com/@puspas99/how-to-create-custom-annotations-in-java-step-by-step-94d8fecd4b75?source=rss-730bca56049c------2</link>
            <guid isPermaLink="false">https://medium.com/p/94d8fecd4b75</guid>
            <dc:creator><![CDATA[Puspalata Sahoo]]></dc:creator>
            <pubDate>Tue, 01 Jul 2025 05:42:30 GMT</pubDate>
            <atom:updated>2025-07-01T05:42:30.431Z</atom:updated>
            <content:encoded><![CDATA[<p>Java annotations are one of those features that look simple but can do incredibly powerful things behind the scenes — frameworks like Spring, Hibernate, and JUnit depend on them heavily. But did you know you can <strong>create your own custom annotations</strong>?</p><p>In this post, I’ll walk you through how to create, apply, and process a custom annotation in Java.</p><h3>🔍 What Is an Annotation in Java?</h3><p>Annotations are metadata that provide information to the compiler or runtime environment. They don’t directly affect the execution of your code, but they can trigger behavior when combined with tools like <strong>Reflection</strong>, <strong>Annotation Processors</strong>, or frameworks.</p><p>You’ve probably used built-in annotations like:</p><pre>@Override<br>@Deprecated<br>@SuppressWarnings(&quot;unchecked&quot;)</pre><p>But you can also define your own!</p><h3>🛠️ Step 1: Define a Custom Annotation</h3><p>To define a custom annotation, use the @interface keyword. You can define elements (like parameters) inside it.</p><p>Here&#39;s a basic example:</p><pre>import java.lang.annotation.ElementType;<br>import java.lang.annotation.Retention;<br>import java.lang.annotation.RetentionPolicy;<br>import java.lang.annotation.Target;<br><br>// Define where the annotation can be used<br>@Target({ElementType.TYPE, ElementType.METHOD})<br><br>// Define when the annotation is available (e.g., runtime)<br>@Retention(RetentionPolicy.RUNTIME)<br>public @interface MyAnnotation {<br>    String value();           // Required parameter<br>    int count() default 1;    // Optional parameter with default<br>}</pre><h3>🔍 Explanation:</h3><ul><li>@Target: Specifies where your annotation can be applied (e.g., class, method, field).</li><li>@Retention: Controls how long the annotation is retained. Use RUNTIME to make it accessible via reflection.</li><li>@interface: Declares a custom annotation type.</li></ul><h3>✍️ Step 2: Apply the Annotation</h3><p>Now that we have @MyAnnotation, let’s apply it to a class and a method:</p><pre>@MyAnnotation(value = &quot;This is a class&quot;, count = 3)<br>public class MyClass {<br><br>    @MyAnnotation(&quot;This is a method&quot;)<br>    public void doSomething() {<br>        // Your business logic here<br>    }<br>}</pre><p>You can pass values to annotation elements just like method parameters. If an element has a default value, it’s optional to include.</p><h3>🔎 Step 3: Read the Annotation Using Reflection</h3><p>To make annotations meaningful, you often want to <strong>process them at runtime</strong>. Here’s how:</p><pre>import java.lang.reflect.Method;<br><br>public class AnnotationProcessor {<br>    public static void main(String[] args) throws Exception {<br>        Class&lt;MyClass&gt; clazz = MyClass.class;<br><br>        // Check annotation on class<br>        if (clazz.isAnnotationPresent(MyAnnotation.class)) {<br>            MyAnnotation annotation = clazz.getAnnotation(MyAnnotation.class);<br>            System.out.println(&quot;Class Annotation -&gt; value: &quot; + annotation.value() + &quot;, count: &quot; + annotation.count());<br>        }<br><br>        // Check annotation on methods<br>        for (Method method : clazz.getDeclaredMethods()) {<br>            if (method.isAnnotationPresent(MyAnnotation.class)) {<br>                MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);<br>                System.out.println(&quot;Method &quot; + method.getName() + &quot; -&gt; value: &quot; + annotation.value());<br>            }<br>        }<br>    }<br>}</pre><h3>⚙️ Real-World Use Cases</h3><p>Custom annotations can be used for:</p><ul><li>✅ Logging (@LogExecutionTime)</li><li>✅ Validation (@NotEmpty, @Range)</li><li>✅ Dependency injection (@Inject, @Autowired)</li><li>✅ Configuration (@ConfigValue)</li><li>✅ Documentation or code generation</li></ul><p>They’re especially powerful when paired with annotation processors or aspect-oriented programming (AOP).</p><h3>✏️ Notes</h3><ul><li>Use @Retention(RetentionPolicy.SOURCE) if it&#39;s only needed at compile time (e.g., for tools or warnings).</li><li>Use @Retention(RetentionPolicy.CLASS) if it needs to be in the bytecode but not at runtime.</li><li>Combine annotations with tools like <strong>Annotation Processors</strong> or <strong>AOP frameworks</strong> (like Spring AOP) for advanced use.</li></ul><h3>🧠 Final Thoughts</h3><p>Annotations are a clean and powerful way to add metadata to your code. With custom annotations, you can build more expressive, readable, and framework-friendly Java applications.</p><p>So next time you’re writing repetitive boilerplate or want to mark special behavior, consider writing your own annotation — you’ll be surprised how elegant it can be.</p><h3>💬 Let’s Connect</h3><p>If you found this helpful, consider clapping 👏 or leaving a comment!<br> Have you used custom annotations in a real project? Share your story!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94d8fecd4b75" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond Optional: Modern Java Error Handling with Sealed Classes and Pattern Matching]]></title>
            <link>https://medium.com/@puspas99/beyond-optional-modern-java-error-handling-with-sealed-classes-and-pattern-matching-9aca03c8e15a?source=rss-730bca56049c------2</link>
            <guid isPermaLink="false">https://medium.com/p/9aca03c8e15a</guid>
            <dc:creator><![CDATA[Puspalata Sahoo]]></dc:creator>
            <pubDate>Sat, 28 Jun 2025 12:51:40 GMT</pubDate>
            <atom:updated>2025-06-28T12:51:40.218Z</atom:updated>
            <content:encoded><![CDATA[<p>Java developers have long relied on Optional and checked exceptions to handle errors, but modern Java offers cleaner, more expressive error handling using <strong>pattern matching</strong> and <strong>sealed classes</strong>.</p><p>With <strong>sealed classes</strong> (introduced in Java 17), you can define a closed hierarchy for your error types:</p><pre>sealed interface Result&lt;T&gt; permits Success, Failure {}<br><br>record Success&lt;T&gt;(T value) implements Result&lt;T&gt; {}<br>record Failure&lt;T&gt;(String message) implements Result&lt;T&gt; {}</pre><p>We can even seal the Failure type for more granularity!</p><pre> sealed interface Failure extends Result permits InsufficientFunds,GatewayTimeout {<br><br>        String reason(); // Common method for all failures<br>}<br> record InsufficientFunds(double shortfall) implements Failure {<br>            @Override<br>            public String reason() {<br>                return &quot;Insufficient funds. You are short by $&quot; + shortfall;<br>            }<br>        }<br><br> record GatewayTimeout(boolean canRetry) implements Failure {<br>            @Override<br>            public String reason() {<br>                return &quot;Payment gateway timed out.&quot;;<br>            }<br>        }</pre><p>This enables <strong>exhaustive pattern matching</strong> (Java 21+) when handling results, ensuring you never forget to handle a failure case:</p><pre>Result&lt;String&gt; result = service.processPayment();<br><br>switch (result) {<br>    case Success(var value) -&gt; System.out.println(&quot;Success: &quot; + value);<br>    case Failure(var message) -&gt; System.err.println(&quot;Error: &quot; + message);<br>}</pre><pre>// The beautiful, clean, and safe calling code<br>PaymentResult result = service.processPayment(100.0);<br><br>String userMessage = switch (result) {<br>    // Pattern matching deconstructs the record for us!<br>    case PaymentResult.Success s -&gt;<br>        &quot;Payment of $&quot; + s.amount() + &quot; was successful! Transaction ID: &quot; + s.transactionId();<br><br>    // We can handle specific failure types<br>    case PaymentResult.Failure.InsufficientFunds f -&gt;<br>        &quot;Could not process payment. &quot; + f.reason();<br><br>    // We can even add logic with `when` clauses<br>    case PaymentResult.Failure.GatewayTimeout t when t.canRetry() -&gt;<br>        &quot;A temporary network error occurred. Please try again in a few moments.&quot;;<br><br>    case PaymentResult.Failure.GatewayTimeout t -&gt;<br>        &quot;A permanent network error occurred. Please contact support.&quot;;<br>};<br><br>System.out.println(userMessage);</pre><p>The above snippet is the more granular way to handle the Failure types.</p><p>This pattern moves your error handling <strong>from runtime surprises to compile-time guarantees</strong>:<br> ✅ No hidden null or unwrapped Optional.<br> ✅ No scattered try-catch unless truly exceptional.<br> ✅ Clear, readable handling of success and failure paths.<br> ✅ Safer refactoring with sealed hierarchies enforcing exhaustive handling.</p><p>Let’s break down why this is a massive improvement:</p><p>✅<strong>Compiler Exhaustiveness Checking:</strong> This is the killer feature. If you add a new failure type (e.g., CardExpired) to the Failure interface but forget to add a case for it in the switch, <strong>your code will not compile</strong>. This eliminates an entire class of runtime bugs. No default case is needed because the compiler guarantees you&#39;ve covered all possibilities.</p><p>✅<strong>Incredible Readability:</strong> The code reads like a list of business requirements. There’s no “instanceof” checking, no casting, and no verbose if-else if chain. The case Success s -&gt; syntax both checks the type and declares a perfectly-scoped, correctly-typed variable s for you to use.</p><p>✅<strong>Data-Driven Logic:</strong> Pattern matching lets you deconstruct the data within your types. We can directly access s.transactionId() or f.shortfall() without any extra work, making the code clean and focused on the logic.</p><p>So, is <strong>Optional </strong>Dead?</p><p>Absolutely not. It remains the perfect tool for its original purpose: <strong>representing the potential absence of a single value.</strong></p><ul><li><strong>Use </strong><strong>Optional&lt;T&gt; when:</strong> The only alternative outcome is &quot;nothing.&quot; A classic example is userRepository.findById(id). You either get a User or you get empty. There are no other failure reasons to communicate.</li><li><strong>Use a </strong><strong>sealed hierarchy when:</strong> An operation can result in success or one of several distinct, meaningful failure states. Think &quot;Create Order,&quot; &quot;Process Payment,&quot; or &quot;Validate Input.&quot;</li></ul><h3>🧠 Final Thoughts</h3><p>By embracing sealed types and pattern matching, you can write Java code that is more declarative, less error-prone, and far more pleasant to read and maintain. It bridges the gap between object-oriented and functional paradigms, allowing you to model your domain’s states and outcomes with precision and safety.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9aca03c8e15a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Happens When You Type a URL? A Deep Dive into the Internet]]></title>
            <link>https://medium.com/@puspas99/what-happens-when-you-type-a-url-a-deep-dive-into-the-internet-fa4b988e4ce1?source=rss-730bca56049c------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa4b988e4ce1</guid>
            <dc:creator><![CDATA[Puspalata Sahoo]]></dc:creator>
            <pubDate>Thu, 22 May 2025 10:16:57 GMT</pubDate>
            <atom:updated>2025-05-22T10:16:57.417Z</atom:updated>
            <content:encoded><![CDATA[<p>🌐 What Happens When You Type a URL?</p><h3>A Deep Dive into the Internet</h3><p>We do it every day — type a web address into a browser and hit Enter. Within seconds, a fully loaded webpage appears. But have you ever wondered what <em>really</em> happens in that tiny window of time?</p><p>Let’s take a simplified yet insightful journey through the key steps involved when you type a URL like www.google.com into your browser.</p><p>🧩 1. <strong>URL Parsing</strong></p><p>The browser first breaks down the URL into parts:</p><ul><li><strong>Protocol</strong>: https</li><li><strong>Domain</strong>: <a href="http://www.google.com/">www.google.com</a></li><li><strong>Path</strong>: / (if omitted, the root is assumed)</li></ul><p>It uses this to understand what kind of request to make and where to send it.</p><p>🌍 2. <strong>DNS(Domain Name System) Resolution</strong></p><p>Your computer needs to find the <strong>IP address</strong> of the domain:</p><ul><li>It checks browser and OS caches.</li><li>If not found, it asks a <strong>DNS server</strong> to translate www.google.com into an IP address like 142.250.190.4.</li><li>This IP points to Google’s web server.</li></ul><h3>🔌 3. TCP(Transmission Control Protocol) Connection</h3><p>With the IP address ready, your browser initiates a <strong>TCP 3-way handshake</strong> with the server:</p><ol><li><strong>SYN</strong> → Client requests connection</li><li><strong>SYN-ACK</strong> → Server acknowledges</li><li><strong>ACK</strong> → Client confirms</li></ol><p>This sets up a reliable connection on port <strong>443</strong> (used for HTTPS).</p><h3>🔒 4. TLS(<strong>Transport Layer Security</strong>) Handshake (For HTTPS)</h3><p>The browser and server establish a <strong>secure connection</strong> using TLS:</p><ul><li>They exchange encryption keys.</li><li>The server proves its identity using a digital certificate(contains public key and identity).</li><li>A secure channel is established.</li></ul><h3>📡 5. HTTP Request Sent</h3><p>Now the browser sends an <strong>HTTP GET request</strong>:</p><pre>GET / HTTP/1.1  <br>Host: www.google.com</pre><p>This tells the server: “Give me the homepage content.”</p><h3>🖥️ 6. Server Processes Request</h3><p>The server:</p><ul><li>Receives the request</li><li>Locates the resource (e.g., HTML file)</li><li>May trigger backend logic or database queries</li><li>Sends back an HTTP response</li></ul><h3>📄 7. HTTP Response Received</h3><p>The server responds with:</p><ul><li>Status code (e.g., 200 OK)</li><li>The webpage HTML</li><li>References to images, CSS, JS files</li></ul><h3>🎨 8. Browser Renders the Page</h3><p>The browser:</p><ul><li>Parses the HTML</li><li>Downloads additional resources (CSS, JS, images)</li><li>Builds the DOM and renders the visual layout</li><li>Executes scripts and shows you the final page</li></ul><h3>✅ 9. Webpage Loaded!</h3><p>In under a second, all this happens and you see the webpage appear.</p><h3>🧠 Final Thoughts</h3><p>Typing a URL seems simple — but under the hood, it triggers a complex series of events involving DNS, TCP/IP, HTTPS, and browser engines. Understanding this process is a great first step into the world of networking and web technologies.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa4b988e4ce1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Behind the Scenes of the Internet: Understanding the TCP 3-Way Handshake]]></title>
            <link>https://medium.com/@puspas99/behind-the-scenes-of-the-internet-understanding-the-tcp-3-way-handshake-87f72fa7446a?source=rss-730bca56049c------2</link>
            <guid isPermaLink="false">https://medium.com/p/87f72fa7446a</guid>
            <dc:creator><![CDATA[Puspalata Sahoo]]></dc:creator>
            <pubDate>Thu, 22 May 2025 08:01:58 GMT</pubDate>
            <atom:updated>2025-05-22T08:20:45.049Z</atom:updated>
            <content:encoded><![CDATA[<p>Every time you visit a website, stream a video, or send a message online, a lot happens behind the scenes to ensure your data gets to the right place — securely and in order. One of the most fundamental processes enabling this seamless communication is the <strong>TCP 3-Way Handshake</strong>.</p><p>But what exactly is it, and why is it so important?</p><p>Let’s break it down.</p><p>🌐<strong> What Is TCP?</strong></p><p><strong>TCP (Transmission Control Protocol)</strong> is one of the core protocols of the internet. It ensures <strong>reliable</strong>, <strong>ordered</strong>, and <strong>error-checked</strong> delivery of data between devices.</p><p>Unlike its cousin <strong>UDP</strong>, which just sends data without much care, TCP works like a polite conversation — both parties introduce themselves, agree on how to talk, and then start the actual exchange.</p><p>This “polite conversation” begins with a ritual called the <strong>3-Way Handshake.</strong></p><p>🤝 <strong>What Is the TCP 3-Way Handshake?</strong></p><p>The <strong>TCP 3-Way Handshake</strong> is the process used to <strong>establish a reliable connection</strong> between two devices (usually a client and a server) before data can be exchanged.</p><h3>It has 3 steps:</h3><ol><li><strong>SYN</strong> (Synchronize)</li><li><strong>SYN-ACK</strong> (Synchronize-Acknowledge)</li><li><strong>ACK</strong> (Acknowledge)</li></ol><p>This handshake ensures that both the client and server:</p><ul><li>Are ready to communicate</li><li>Agree on starting points for the data exchange</li><li>Can trust the connection is set up correctly</li></ul><p>📶 <strong>Step-by-Step Breakdown</strong></p><p>Let’s say you type www.google.com into your browser.</p><p>🔹<strong> 1. Client Sends SYN</strong></p><p>The browser (client) wants to initiate a connection, so it sends a <strong>SYN</strong> packet to Google’s server.</p><ul><li><strong>Client → Server</strong></li><li>The client sends a TCP packet with the <strong>SYN flag</strong> set.</li><li>This packet includes an <strong>initial sequence number (ISN)</strong>, a random number used to begin tracking the byte order of the communication.</li><li>Purpose: “I want to start a connection and here’s my ISN.”</li></ul><pre>Client → Server: SYN, Seq = 1000</pre><p><strong>🔹 2. Server Replies with SYN-ACK</strong></p><p>The server receives the SYN request and replies with two things in one packet:</p><ul><li><strong>Server → Client</strong></li><li>The server receives the SYN, reserves resources, and responds with a packet that:</li><li>Has both <strong>SYN and ACK flags</strong> set.</li><li>Acknowledges the client’s SYN by setting <strong>ACK = Client ISN + 1</strong>.</li><li>Sends its own <strong>SYN</strong> with its own sequence number.</li></ul><p>This is like saying: “Got it! Here’s my number, and I received yours.”</p><pre>Server → Client: SYN, Seq = 2000 | ACK = 1001</pre><p><strong>🔹 3. Client Sends Final ACK</strong></p><p>The client receives the SYN-ACK and sends back a final <strong>ACK</strong> to the server:</p><ul><li><strong>Client → Server</strong></li></ul><p>The client sends a final ACK:</p><ul><li>ACK = Server ISN + 1</li><li>No payload or data is sent; this just completes the handshake and simply seals the deal</li></ul><pre>Client → Server: ACK = 2001</pre><p>✅ Connection Established!</p><p>At this point, both the client and the server are synchronized and ready to exchange data. The TCP connection is now <strong>fully established</strong>, and your browser can securely start the <strong>HTTPS</strong> handshake (TLS/SSL) next.</p><p>🧠<strong> Why Is This Important?</strong></p><p>The TCP 3-Way Handshake ensures:</p><ul><li><strong>Reliable communication</strong>: No data is sent until both sides agree the connection is open.</li><li><strong>Order and tracking</strong>: Sequence numbers make sure that packets are delivered in order and duplicates are detected.</li><li><strong>Security groundwork</strong>: For secure (HTTPS) connections, TLS negotiation begins <strong>after</strong> the TCP connection is established.</li></ul><p>Without this handshake, your web experience would be far less stable and secure.</p><p>🔐 <strong>Fun Fact: Why Port 443?</strong></p><p>When you connect to https://www.google.com, your browser connects over <strong>TCP port 443</strong>, which is the standard for <strong>HTTPS</strong>. After the TCP connection is set up using the 3-way handshake, the browser and server initiate a <strong>TLS handshake</strong> to encrypt all future communication.</p><pre>Client                        Server<br>  | ------- SYN -----------&gt;   |   (Hello, can we talk?)<br>  | &lt;----- SYN-ACK ---------   |   (Yes, and here’s my info)<br>  | ------- ACK -----------&gt;   |   (Got it. Let’s start!)<br>  | ----- Secure, reliable connection established -----&gt;</pre><p><strong>🚀 Final Thoughts</strong></p><p>The next time you open a website, remember that this tiny, invisible <strong>3-step handshake</strong> is what made it all possible. It may last just a few milliseconds, but without it, the internet as we know it wouldn’t exist.</p><p>Whether you’re a developer, a network enthusiast, or just a curious mind — understanding the <strong>TCP 3-Way Handshake</strong> is a powerful insight into how the internet really works.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87f72fa7446a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OAuth 2.0 vs OpenID Connect vs SSO: Understanding the Key Differences]]></title>
            <link>https://medium.com/@puspas99/oauth-2-0-vs-openid-connect-vs-sso-understanding-the-key-differences-cd154da0041b?source=rss-730bca56049c------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd154da0041b</guid>
            <dc:creator><![CDATA[Puspalata Sahoo]]></dc:creator>
            <pubDate>Tue, 20 May 2025 09:45:16 GMT</pubDate>
            <atom:updated>2025-05-21T12:46:43.873Z</atom:updated>
            <content:encoded><![CDATA[<p>When it comes to authentication and authorization in modern web applications, terms like <strong>OAuth 2.0</strong>, <strong>OpenID Connect</strong>, and <strong>Single Sign-On (SSO)</strong> are often thrown around — sometimes interchangeably. But they’re not the same thing.</p><p>In this post, we’ll break down what each of these technologies is, how they differ, and how they work together.</p><p>🔐 <strong>What is OAuth 2.0?</strong></p><p><strong>OAuth 2.0</strong> is an <em>authorization</em> framework. Its main purpose is to allow an application to access resources on behalf of a user — without needing the user’s password.</p><p>For example:</p><p>When you log into a new app using your Google or Facebook account and the app requests permission to access your profile or contacts, that’s OAuth 2.0 in action.</p><p><strong>Key Points:</strong></p><ul><li>OAuth 2.0 does <em>not</em> authenticate the user.</li><li>It delegates access between services using access tokens.</li><li>Useful for APIs, third-party integrations, and delegated permissions.</li></ul><h3>🙋 What is OpenID Connect?</h3><p><strong>OpenID Connect (OIDC)</strong> is a layer built on top of OAuth 2.0. While OAuth is about authorization, OIDC adds <em>authentication</em> — verifying who the user is.</p><p>So, if OAuth is the valet key to access your car, OIDC checks the ID of the person using that key.</p><p><strong>Key Points:</strong></p><ul><li>OIDC provides a standardized way to authenticate users.</li><li>It issues an ID token (usually a JWT) that apps can use to verify identity.</li><li>Commonly used in web and mobile apps that support social logins (Google, Microsoft, etc.).</li></ul><h3>🙋What is SSO (Single Sign-On)?</h3><p><strong>Single Sign-On (SSO)</strong> is a <em>user experience</em> pattern. It allows users to log in once and gain access to multiple applications without needing to log in again for each.</p><p>SSO can be implemented using OAuth, OpenID Connect, SAML, or other protocols.</p><p><strong>Key Points:</strong></p><ul><li>SSO is about <em>session continuity</em> across apps.</li><li>It improves UX and reduces password fatigue.</li><li>It often leverages OAuth or OIDC behind the scenes.</li></ul><p>⚖️ Quick Comparison</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2-c6H5wmvph_g3SP" /></figure><h3>🧠 How They Work Together</h3><ul><li><strong>SSO</strong> often uses <strong>OpenID Connect</strong> to authenticate users across applications.</li><li><strong>OpenID Connect</strong> is built on <strong>OAuth 2.0</strong>, so the authentication process leverages OAuth flows.</li><li><strong>OpenID Connect</strong> is built on <strong>OAuth 2.0</strong>, so the authentication process leverages OAuth flows.</li><li><strong>OAuth 2.0</strong> is the foundation; <strong>OIDC</strong> adds identity; <strong>SSO</strong> ties it all together for a seamless login experience.</li></ul><h3>✅ Summary</h3><ul><li>Use <strong>OAuth 2.0</strong> when you want to let an app access user data from another service.</li><li>Use <strong>OpenID Connect</strong> when you want to authenticate users and get identity information.</li><li>Use <strong>SSO</strong> to create a unified login experience across multiple apps.</li></ul><p>They’re not rivals — they’re teammates.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd154da0041b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[gRPC vs. REST: Which One Should You Choose?]]></title>
            <link>https://medium.com/@puspas99/grpc-vs-rest-which-one-should-you-choose-12fc82614daf?source=rss-730bca56049c------2</link>
            <guid isPermaLink="false">https://medium.com/p/12fc82614daf</guid>
            <dc:creator><![CDATA[Puspalata Sahoo]]></dc:creator>
            <pubDate>Wed, 19 Mar 2025 10:19:36 GMT</pubDate>
            <atom:updated>2025-03-19T10:19:36.179Z</atom:updated>
            <content:encoded><![CDATA[<p>When building APIs, choosing the right communication method is crucial for performance, scalability, and developer experience. Two popular approaches are <strong>gRPC</strong> and <strong>REST</strong>. While REST has been the dominant API style for years, gRPC has gained traction due to its speed and efficiency. But which one is right for your project?</p><p>Let’s break down the key differences and help you decide.</p><h3>🚀 What is REST?</h3><p><strong>REST (Representational State Transfer)</strong> is an architectural style that allows systems to communicate over HTTP using standard methods like GET, POST, PUT, and DELETE. REST APIs typically use JSON for data exchange.</p><h3>Pros of REST:</h3><p>✅ <strong>Human-Readable</strong> — Uses JSON, which is easy to read and debug.<br> ✅ <strong>Broad Adoption</strong> — Works with almost every programming language.<br> ✅ <strong>Simple and Stateless</strong> — No need to maintain client session state.</p><h3>Cons of REST:</h3><p>❌ <strong>Performance Overhead</strong> — JSON serialization/deserialization can be slow.<br> ❌ <strong>Lack of Strong Typing</strong> — No strict contract between client and server.<br> ❌ <strong>Higher Latency</strong> — Multiple API calls may be needed for complex data retrieval.</p><h3>⚡ What is gRPC?</h3><p><strong>gRPC (gRPC Remote Procedure Call)</strong> is a high-performance, open-source framework developed by Google. It uses <strong>Protocol Buffers (protobufs)</strong> instead of JSON, enabling faster communication. gRPC also supports bidirectional streaming, making it ideal for real-time applications.</p><h3>Pros of gRPC:</h3><p>✅ <strong>High Performance</strong> — Binary serialization (protobufs) is much faster than JSON.<br> ✅ <strong>Strong Typing</strong> — Uses .proto contracts, ensuring consistency between client and server.<br> ✅ <strong>Bidirectional Streaming</strong> — Supports full-duplex communication for real-time data transfer.<br> ✅ <strong>Built-in Authentication &amp; Load Balancing</strong> — Includes advanced features out of the box.</p><h3>Cons of gRPC:</h3><p>❌ <strong>Not Human-Readable</strong> — Binary data makes debugging harder compared to JSON.<br> ❌ <strong>Limited Browser Support</strong> — gRPC doesn’t work well with standard web browsers.<br> ❌ <strong>Steeper Learning Curve</strong> — Developers need to learn protobufs and new tools.</p><p>🆚 gRPC vs. REST: A Feature Comparison</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/0*htzp5tGOn-fyeMLk" /></figure><h3>🔥 When to Use gRPC vs. REST</h3><h3>Use REST if:</h3><p>✔ You’re building a public API that needs wide adoption.<br> ✔ Your application interacts mainly with web browsers.<br> ✔ Human-readable responses (JSON) are a priority.</p><h3>Use gRPC if:</h3><p>✔ You need <strong>high-performance</strong> and <strong>low-latency</strong> communication.<br> ✔ You’re working on <strong>microservices</strong> that require efficient internal communication.<br> ✔ Your system involves <strong>real-time data streaming</strong>.</p><h3>🎯 Final Thoughts</h3><p>Both REST and gRPC have their strengths. REST remains the go-to choice for general web applications, while gRPC is perfect for high-performance, microservices-based architectures. If your project demands speed, efficiency, and strong typing, gRPC is worth considering. Otherwise, REST’s simplicity and flexibility might be the better fit.</p><p>Which one do you prefer for your projects? Let me know in the comments!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12fc82614daf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Round Robin Distribution for Fair Task Assignment in Java]]></title>
            <link>https://medium.com/@puspas99/round-robin-distribution-for-fair-task-assignment-in-java-7ce5fb16bbf1?source=rss-730bca56049c------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ce5fb16bbf1</guid>
            <dc:creator><![CDATA[Puspalata Sahoo]]></dc:creator>
            <pubDate>Thu, 13 Mar 2025 19:09:40 GMT</pubDate>
            <atom:updated>2025-03-13T19:09:40.571Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In modern software systems, <strong>fair task assignment</strong> is crucial for balancing workloads efficiently. Whether it’s distributing network requests among servers, allocating jobs to workers, or scheduling threads in a multithreaded application, an unfair distribution can lead to performance bottlenecks.</p><p>One simple yet effective algorithm for ensuring fairness is <strong>Round Robin Distribution</strong>. In this blog, we’ll explore how Round Robin works and implement a <strong>thread-safe</strong> version in Java.</p><h3>What is Round Robin Distribution?</h3><p>Round Robin is a cyclic allocation technique that ensures each entity (worker, thread, or server) gets an equal number of tasks before the cycle restarts. It works as follows:</p><ol><li><strong>Maintain an index</strong> pointing to the next recipient.</li><li><strong>Assign a task</strong> to the recipient at the current index.</li><li><strong>Move the index forward</strong>, cycling back when it reaches the end.</li><li><strong>Repeat the process</strong> for every new task.</li></ol><p>This ensures fairness, preventing any worker or resource from being overloaded while others remain idle.</p><h3>Where is Round Robin Used?</h3><ul><li><strong>Load balancing</strong> — Distributing client requests across multiple servers.</li><li><strong>Thread scheduling</strong> — Assigning jobs fairly among available CPU threads.</li><li><strong>Task assignment</strong> — Ensuring workers in a queue get equal workloads.</li><li><strong>Resource allocation</strong> — Distributing shared resources like database connections.</li></ul><h3>Basic Implementation of Round Robin in Java</h3><p>Let’s implement a simple Round Robin distributor that assigns tasks to workers fairly.</p><h3>Basic Round Robin Distributor</h3><pre>import java.util.List;<br>import java.util.ArrayList;<br><br>class RoundRobinDistributor&lt;T&gt; {<br>    private final List&lt;T&gt; items;<br>    private int index = 0;<br><br>    public RoundRobinDistributor(List&lt;T&gt; items) {<br>        this.items = new ArrayList&lt;&gt;(items);<br>    }<br><br>    public T getNext() {<br>        if (items.isEmpty()) {<br>            throw new IllegalStateException(&quot;No items to distribute&quot;);<br>        }<br>        T item = items.get(index);<br>        index = (index + 1) % items.size();  // Move to next in a circular fashion<br>        return item;<br>    }<br>}<br><br>public class RoundRobinExample {<br>    public static void main(String[] args) {<br>        List&lt;String&gt; workers = List.of(&quot;Worker A&quot;, &quot;Worker B&quot;, &quot;Worker C&quot;);<br>        RoundRobinDistributor&lt;String&gt; distributor = new RoundRobinDistributor&lt;&gt;(workers);<br><br>        for (int i = 0; i &lt; 10; i++) {<br>            System.out.println(&quot;Task &quot; + (i + 1) + &quot; assigned to: &quot; + distributor.getNext());<br>        }<br>    }<br>}</pre><p>Output</p><pre>Task 1 assigned to: Worker A <br>Task 2 assigned to: Worker B <br>Task 3 assigned to: Worker C <br>Task 4 assigned to: Worker A <br>Task 5 assigned to: Worker B <br>Task 6 assigned to: Worker C <br>Task 7 assigned to: Worker A</pre><p>This approach ensures that each worker gets tasks in an <strong>equal, rotating</strong> manner.</p><h3>Making Round Robin Thread-Safe</h3><p>In real-world applications, multiple threads may access the distributor simultaneously. To handle concurrency safely, we can use <strong>ReentrantLock</strong>.</p><h3>Thread-Safe Round Robin Implementation</h3><pre>import java.util.List;<br>import java.util.concurrent.locks.ReentrantLock;<br><br>class ThreadSafeRoundRobin&lt;T&gt; {<br>    private final List&lt;T&gt; items;<br>    private int index = 0;<br>    private final ReentrantLock lock = new ReentrantLock();<br><br>    public ThreadSafeRoundRobin(List&lt;T&gt; items) {<br>        if (items.isEmpty()) {<br>            throw new IllegalArgumentException(&quot;Item list cannot be empty&quot;);<br>        }<br>        this.items = List.copyOf(items); // Immutable copy<br>    }<br><br>    public T getNext() {<br>        lock.lock(); // Lock for thread safety<br>        try {<br>            T item = items.get(index);<br>            index = (index + 1) % items.size(); // Cycle through items<br>            return item;<br>        } finally {<br>            lock.unlock(); // Always unlock to prevent deadlocks<br>        }<br>    }<br>}<br><br>public class MultiThreadedRoundRobin {<br>    public static void main(String[] args) {<br>        List&lt;String&gt; servers = List.of(&quot;Server1&quot;, &quot;Server2&quot;, &quot;Server3&quot;);<br>        ThreadSafeRoundRobin&lt;String&gt; distributor = new ThreadSafeRoundRobin&lt;&gt;(servers);<br><br>        // Simulate multiple threads assigning tasks<br>        Runnable task = () -&gt; {<br>            for (int i = 0; i &lt; 5; i++) {<br>                System.out.println(Thread.currentThread().getName() + &quot; -&gt; &quot; + distributor.getNext());<br>                try {<br>                    Thread.sleep(100); // Simulate task execution time<br>                } catch (InterruptedException e) {<br>                    Thread.currentThread().interrupt();<br>                }<br>            }<br>        };<br><br>        // Creating multiple threads<br>        Thread t1 = new Thread(task, &quot;Worker-1&quot;);<br>        Thread t2 = new Thread(task, &quot;Worker-2&quot;);<br>        Thread t3 = new Thread(task, &quot;Worker-3&quot;);<br><br>        t1.start();<br>        t2.start();<br>        t3.start();<br>    }<br>}</pre><h3>Why is This Thread-Safe?</h3><p>✅ <strong>ReentrantLock ensures safe access</strong> – Prevents race conditions when multiple threads request the next task.<br> ✅ <strong>Fair task distribution</strong> – Each worker gets an equal number of tasks.<br> ✅ <strong>Avoids starvation</strong> – No single worker is overwhelmed while others remain idle.</p><h3>Performance Considerations</h3><p>While Round Robin is simple and fair, consider these factors:</p><p>✔ <strong>Use </strong><strong>AtomicInteger for performance</strong> – If high-speed access is needed, replacing ReentrantLock with AtomicInteger may improve efficiency.<br> ✔ <strong>Dynamic Workloads</strong> – If workers dynamically join or leave, use <strong>ConcurrentLinkedQueue</strong> instead of a fixed list.<br> ✔ <strong>Weighted Round Robin</strong> – If some workers can handle more tasks, introduce weights to distribute tasks proportionally.</p><h3>Conclusion</h3><p>Round Robin is an effective and simple algorithm for <strong>fair task assignment</strong> in multi-threaded applications. It ensures equal distribution without bias, whether used for <strong>load balancing</strong>, <strong>job scheduling</strong>, or <strong>resource allocation</strong>.</p><h3>Key Takeaways:</h3><p>✅ <strong>Basic Round Robin ensures fairness</strong> by distributing tasks cyclically.<br> ✅ <strong>Thread-safe implementation</strong> prevents race conditions.<br> ✅ <strong>Optimizations like AtomicInteger &amp; Weighted Round Robin</strong> can improve performance.</p><h3>Next Steps</h3><p>Want to take it further? Try implementing <strong>Weighted Round Robin</strong> to prioritize some workers over others based on capacity! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ce5fb16bbf1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot 3 + ShedLock: A Guide to Distributed Task Scheduling]]></title>
            <link>https://medium.com/@puspas99/spring-boot-3-shedlock-a-guide-to-distributed-task-scheduling-1dc24a6c09d5?source=rss-730bca56049c------2</link>
            <guid isPermaLink="false">https://medium.com/p/1dc24a6c09d5</guid>
            <dc:creator><![CDATA[Puspalata Sahoo]]></dc:creator>
            <pubDate>Wed, 12 Mar 2025 12:35:19 GMT</pubDate>
            <atom:updated>2025-03-12T12:35:19.997Z</atom:updated>
            <content:encoded><![CDATA[<h3>Using ShedLock in Spring Boot 3 for Distributed Task Scheduling</h3><h3>Introduction</h3><p>In microservices architecture or clustered applications, ensuring that scheduled tasks run only once across multiple instances is a common challenge. Spring’s @Scheduled annotation works well in single-instance applications but doesn’t prevent multiple nodes from executing the same task simultaneously.</p><p>This is where <strong>ShedLock</strong> comes in. ShedLock ensures that scheduled tasks execute only once across distributed instances by using a persistent lock mechanism. In this blog, we’ll explore how to integrate and use ShedLock in a <strong>Spring Boot 3</strong> application.</p><h3>Why Use ShedLock?</h3><p>Spring Boot’s @Scheduled annotation triggers tasks at fixed intervals. In a distributed environment, each instance of the application will execute the task, leading to duplicated operations. ShedLock solves this problem by using a <strong>lock mechanism</strong> backed by a shared database, Redis, or other persistence stores.</p><p><strong>Key Benefits of ShedLock:</strong></p><ul><li>Ensures scheduled tasks execute only once across multiple instances.</li><li>Supports various storage backends like relational databases, MongoDB, DynamoDB, and Redis.</li><li>Simple and lightweight.</li><li>Works seamlessly with Spring Boot’s @Scheduled tasks.</li></ul><h3>Setting Up ShedLock in Spring Boot 3</h3><h4>1. Add Dependencies</h4><p>First, add the required dependencies to your pom.xml if you are using Maven:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;net.javacrumbs.shedlock&lt;/groupId&gt;<br>    &lt;artifactId&gt;shedlock-spring&lt;/artifactId&gt;<br>    &lt;version&gt;5.8.0&lt;/version&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;net.javacrumbs.shedlock&lt;/groupId&gt;<br>    &lt;artifactId&gt;shedlock-provider-jdbc-template&lt;/artifactId&gt;<br>    &lt;version&gt;5.8.0&lt;/version&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-starter-jdbc&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><h4>2. Configure ShedLock with a Database</h4><p>ShedLock requires a <strong>persistent storage</strong> to manage locks. If using a relational database, create the necessary table:</p><pre>CREATE TABLE shedlock (<br>    name VARCHAR(64) NOT NULL,<br>    lock_until TIMESTAMP(3) NULL,<br>    locked_at TIMESTAMP(3) NOT NULL,<br>    locked_by VARCHAR(255) NOT NULL,<br>    PRIMARY KEY (name)<br>);</pre><p>Configure <strong>ShedLock</strong> in your Spring Boot application:</p><pre>import net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateLockProvider;<br>import net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.beans.factory.annotation.Qualifier;<br>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br>import org.springframework.jdbc.core.JdbcTemplate;<br><br>import javax.sql.DataSource;<br><br>@Configuration<br>@EnableSchedulerLock(defaultLockAtMostFor = &quot;${job.shedlock.lock.value}&quot;)<br>public class SchedulerConfiguration {<br>    @Bean<br>    public LockProvider lockProvider(@Autowired final DataSource dataSource) {<br>        return new JdbcTemplateLockProvider(<br>                JdbcTemplateLockProvider.Configuration.builder()<br>                        .withJdbcTemplate(new JdbcTemplate(dataSource))<br>                        .usingDbTime()<br>                        .build()<br>        );</pre><h4>3. Use ShedLock in Scheduled Tasks</h4><p>Now, update your scheduled tasks to use ShedLock:</p><pre>import net.javacrumbs.shedlock.spring.annotation.SchedulerLock;<br>import org.springframework.scheduling.annotation.Scheduled;<br>import org.springframework.stereotype.Service;<br><br>@Service<br>public class ScheduledTaskService {<br>    <br>    @Scheduled(fixedRate = 60000) // Runs every 60 seconds<br>    @SchedulerLock(name = &quot;uniqueTaskLock&quot;, lockAtMostFor = &quot;10m&quot;, lockAtLeastFor = &quot;1m&quot;)<br>    public void runScheduledTask() {<br>        System.out.println(&quot;Executing scheduled task at &quot; + System.currentTimeMillis());<br>    }<br>}</pre><h3>Explanation of ShedLock Parameters:</h3><ul><li><strong>name</strong>: A unique name for the task</li><li><strong>lockAtMostFor</strong>: Maximum time the lock will be held (ensures cleanup in case of crashes).</li><li><strong>lockAtLeastFor</strong>: Minimum time the lock is held to prevent quick re-execution.</li></ul><h3>Testing ShedLock</h3><p>Run multiple instances of your Spring Boot application. You should see that only one instance executes the scheduled task at a time, preventing duplicate execution.</p><p>To confirm the locks, check the <strong>shedlock</strong> table in your database:</p><pre>SELECT * FROM shedlock;</pre><h3>Alternative Storage Options</h3><p>If you don’t want to use a relational database, ShedLock supports other providers:</p><ul><li><strong>MongoDB</strong>: Use shedlock-provider-mongo</li><li><strong>Redis</strong>: Use shedlock-provider-redis-spring</li><li><strong>DynamoDB</strong>: Use shedlock-provider-dynamodb</li></ul><h3>Conclusion</h3><p><strong>ShedLock </strong>is a powerful yet simple library that prevents duplicate execution of scheduled tasks in distributed Spring Boot applications. By leveraging a database or external storage system, you ensure that tasks run <strong>exactly once</strong> across all instances, improving reliability and consistency.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1dc24a6c09d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Configuring Spring Batch in Spring Boot 3: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@puspas99/configuring-spring-batch-in-spring-boot-3-a-step-by-step-guide-9f107847268d?source=rss-730bca56049c------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f107847268d</guid>
            <dc:creator><![CDATA[Puspalata Sahoo]]></dc:creator>
            <pubDate>Thu, 06 Mar 2025 17:34:37 GMT</pubDate>
            <atom:updated>2025-03-06T17:34:37.877Z</atom:updated>
            <content:encoded><![CDATA[<p>Spring Batch is a powerful framework for processing large volumes of data in batch jobs. With <strong>Spring Boot 3</strong>, there are some changes and improvements in Spring Batch, making it easier to configure and use. In this guide, we’ll explore how to configure <strong>Spring Batch</strong> in a <strong>Spring Boot 3</strong> application.</p><h3>📌 Prerequisites</h3><p>Before we begin, ensure you have:<br>✔ Java 17 or later<br>✔ Spring Boot 3+<br>✔ Maven or Gradle<br>✔ A database (H2, PostgreSQL, MySQL, etc.)</p><h3>1️⃣ Adding Dependencies</h3><p>Add the following dependencies in your <strong>pom.xml</strong> (for Maven users):</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-starter-batch&lt;/artifactId&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;com.oracle.database.jdbc&lt;/groupId&gt;<br>    &lt;artifactId&gt;ojdbc10&lt;/artifactId&gt;<br>    &lt;version&gt;19.19.0.0&lt;/version&gt;<br>  &lt;/dependency&gt;</pre><p>For <strong>Gradle</strong>, add:</p><pre>dependencies {<br>    implementation &#39;org.springframework.boot:spring-boot-starter-batch&#39;<br>    implementation &#39;org.springframework.boot:spring-boot-starter-data-jpa&#39;<br>    runtimeOnly &#39;com.h2database:h2&#39;<br>}</pre><h3>2️⃣ Configuring Spring Batch</h3><p>Spring Boot 3 introduces improvements in the way batch jobs are configured. Let’s create a simple batch job that reads data from a file, processes it, and writes it to a database.</p><h3>Step 1: Define a Model</h3><p>Create a simple model class:</p><pre>@Entity<br>public class Customer {<br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br>    private String name;<br>    private String email;<br><br>    // Getters and setters<br>}</pre><h3>Step 2: Define a Repository</h3><p>Create a <strong>Spring Data JPA</strong> repository to store processed data:</p><pre>public interface CustomerRepository extends JpaRepository&lt;Customer, Long&gt; {<br>}</pre><pre>@Bean<br>public FlatFileItemReader&lt;Customer&gt; reader() {<br>    return new FlatFileItemReaderBuilder&lt;Customer&gt;()<br>        .name(&quot;customerItemReader&quot;)<br>        .resource(new ClassPathResource(&quot;customers.csv&quot;))<br>        .delimited()<br>        .names(&quot;name&quot;, &quot;email&quot;)<br>        .fieldSetMapper(new BeanWrapperFieldSetMapper&lt;&gt;() {{<br>            setTargetType(Customer.class);<br>        }})<br>        .build();<br>}</pre><p>Step 4: Define a Processor</p><pre>@Component<br>public class CustomerItemProcessor implements ItemProcessor&lt;Customer, Customer&gt; {<br>    @Override<br>    public Customer process(Customer customer) {<br>        customer.setEmail(customer.getEmail().toLowerCase()); // Convert email to lowercase<br>        return customer;<br>    }<br>}</pre><p>Step 5: Define a Writer</p><pre>@Bean<br>public ItemWriter&lt;Customer&gt; writer(CustomerRepository repository) {<br>    return items -&gt; repository.saveAll(items);<br>}</pre><p>Step 6: Configure the Batch Job</p><pre>@Bean<br>public Job importCustomerJob(JobRepository jobRepository, Step step, JobCompletionNotificationListener listener) {<br>    return new JobBuilder(&quot;importCustomerJob&quot;, jobRepository)<br>        .incrementer(new RunIdIncrementer())<br>        .listener(listener)<br>        .flow(step)<br>        .end()<br>        .build();<br>}<br><br>@Bean<br>public Step step(JobRepository jobRepository, PlatformTransactionManager transactionManager,<br>                 ItemReader&lt;Customer&gt; reader, ItemProcessor&lt;Customer, Customer&gt; processor, ItemWriter&lt;Customer&gt; writer) {<br>    return new StepBuilder(&quot;step&quot;, jobRepository)<br>        .&lt;Customer, Customer&gt;chunk(10, transactionManager)<br>        .reader(reader)<br>        .processor(processor)<br>        .writer(writer)<br>        .build();<br>}</pre><h3>Step 7: Run the Batch Job</h3><p>Spring Boot 3 runs batch jobs <strong>by default</strong> at startup. If you want to disable this and trigger it manually, add this to <strong>application.properties</strong>:</p><pre>spring.batch.job.enabled=false</pre><p>To run the job manually, you can use:</p><pre>@Autowired<br>JobLauncher jobLauncher;<br><br>@Autowired<br>Job job;<br><br>public void runBatchJob() throws Exception {<br>    JobParameters params = new JobParametersBuilder()<br>        .addLong(&quot;time&quot;, System.currentTimeMillis())<br>        .toJobParameters();<br>    jobLauncher.run(job, params);<br>}</pre><p>In <strong>Spring Batch</strong>, both .start() and .flow() are used to define the flow of steps within a <strong>Job</strong>, but they serve different purposes. Let&#39;s break it down.</p><p>🔹 .start() vs .flow() in Spring Batch</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*r-G3W3R52F-IxJcA" /></figure><h3>1️⃣ Using .start()</h3><p>.start() is used to <strong>begin</strong> a job with a specific step. It&#39;s typically followed by .next() to chain more steps.</p><pre>@Bean<br>public Job simpleJob(JobRepository jobRepository, Step step1, Step step2) {<br>    return new JobBuilder(&quot;simpleJob&quot;, jobRepository)<br>        .incrementer(new RunIdIncrementer())<br>        .start(step1)  // Start with step1<br>        .next(step2)   // Move to step2<br>        .build();<br>}</pre><p>✅ <strong>Use </strong><strong>.start() when your job has a straightforward, linear execution.</strong></p><p>2️⃣ Using .flow()</p><p>.flow() is used for <strong>more complex job flows</strong>, like conditional execution or parallel steps. It&#39;s useful when you want <strong>more control</strong> over how steps are executed.</p><pre>@Bean<br>public Job flowJob(JobRepository jobRepository, Step step1, Step step2, Step step3) {<br>    return new JobBuilder(&quot;flowJob&quot;, jobRepository)<br>        .incrementer(new RunIdIncrementer())<br>        .flow(step1)  // Start with step1<br>        .next(step2)  // Move to step2<br>        .next(step3)  // Move to step3<br>        .end()        // Marks the end of the job<br>        .build();<br>}</pre><p>✅ <strong>Use </strong><strong>.flow() when you need more structured job execution, especially for complex workflows.</strong></p><h3>3️⃣ When to Use .flow().end() Instead of .start()?</h3><p>If you’re using .flow(), you must call .end() to indicate that the job flow is complete. Otherwise, Spring Batch won&#39;t recognize the job structure properly.</p><pre>@Bean<br>public Job conditionalJob(JobRepository jobRepository, Step step1, Step step2, Step step3) {<br>    return new JobBuilder(&quot;conditionalJob&quot;, jobRepository)<br>        .incrementer(new RunIdIncrementer())<br>        .start(step1)<br>        .on(&quot;COMPLETED&quot;).to(step2)  // If step1 completes, go to step2<br>        .from(step2).on(&quot;FAILED&quot;).to(step3)  // If step2 fails, go to step3<br>        .end()<br>        .build();<br>}</pre><ul><li><strong>Use </strong><strong>.start()</strong> when you have a simple, sequential job.</li><li><strong>Use </strong><strong>.flow().end()</strong> for complex workflows, like conditional branching or multiple job flows.</li></ul><h3>📌 Conclusion</h3><p>Spring Boot 3 simplifies Spring Batch configuration with a more modern and modular approach. This guide covered:</p><p>✅ Setting up dependencies<br>✅ Configuring a batch job<br>✅ Using a reader, processor, and writer<br>✅ Running the job manually</p><p>Spring Batch is powerful for handling large datasets efficiently. 🚀 Experiment with different data sources, processors, and job triggers to optimize your batch processing!</p><p>💬 <strong>Got questions? Let me know in the comments!</strong> 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f107847268d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>