<?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 MEsfandiari on Medium]]></title>
        <description><![CDATA[Stories by MEsfandiari on Medium]]></description>
        <link>https://medium.com/@mesfandiari77?source=rss-6ba4fd8fc2d3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xZLaU_exYOA93wgRRsiNDA.jpeg</url>
            <title>Stories by MEsfandiari on Medium</title>
            <link>https://medium.com/@mesfandiari77?source=rss-6ba4fd8fc2d3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 11:46:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mesfandiari77/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[Money is Never Updated: Building a Zero-Loss Payment System in Spring Boot]]></title>
            <link>https://medium.com/@mesfandiari77/money-is-never-updated-building-a-zero-loss-payment-system-in-spring-boot-86b77b2de4b5?source=rss-6ba4fd8fc2d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/86b77b2de4b5</guid>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[kafka]]></category>
            <dc:creator><![CDATA[MEsfandiari]]></dc:creator>
            <pubDate>Wed, 09 Sep 2026 16:46:01 GMT</pubDate>
            <atom:updated>2026-09-09T16:46:01.012Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-AVFmNtSI4ZBuYn_9YZ_DA.png" /></figure><p>If you ask a junior developer to transfer $100 from Alice to Bob, you will likely see a piece of code that looks like this:</p><pre>@Transactional<br>public void transfer(String aliceId, String bobId, BigDecimal amount) {<br>    alice.setBalance(alice.getBalance().subtract(amount));<br>    bob.setBalance(bob.getBalance().add(amount));<br>    accountRepository.save(alice);<br>    accountRepository.save(bob);<br>}</pre><p>It looks clean. It uses @Transactional. In a monolith with a single database, it works perfectly.</p><p>But in a real-world Core Banking system or a distributed payment gateway (think Stripe or PayPal), <strong>this code is a disaster waiting to happen.</strong></p><p>When your architecture evolves into microservices — where the <em>Wallet Service</em>, <em>Ledger Service</em>, and <em>Notification Service</em> are separate and communicate via Kafka or RabbitMQ — the cozy blanket of @Transactional gets ripped away.</p><p>In this article, I’ll share the secrets of how core banking systems actually move money, why we <strong>never</strong> UPDATE balances, and how to build a bulletproof, event-driven ledger in Spring Boot without losing a single cent.</p><h3>Core Banking Secret #1: Money is Never “Updated”</h3><p>The first paradigm shift you need to make when designing financial systems is this: <strong>Financial ledgers are Append-Only.</strong></p><p>In real banking, we don’t do UPDATE accounts SET balance = balance - 100. Why? Because updates destroy history. If a bug accidentally overwrites a balance, the money is gone forever, and the audit trail is broken.</p><p>Instead, we use a <strong>Double-Entry Ledger</strong>. Every transaction creates at least two immutable records (entries). To move $100 from Alice to Bob, we <em>insert</em> two rows:</p><ol><li><strong>Debit (Alice):</strong> -$100</li><li><strong>Credit (Bob):</strong> +$100</li></ol><p><strong>The Rule of Conservation:</strong> At any given millisecond, the sum of all entries in the ledger must exactly equal zero. The “current balance” is just the sum of all past entries. It is calculated, never directly modified.</p><h3>The Microservices Nightmare: The Dual-Write Problem</h3><p>Now, let’s bring Kafka into the mix. Alice buys a coffee. The <em>Order Service</em> needs to deduct money from her wallet and notify the <em>Ledger Service</em>.</p><p>You might write something like this:</p><pre>@Transactional<br>public void processPayment(Order order) {<br>    ledgerRepository.insertDebit(order.getUserId(), order.getAmount()); // 1. Save to DB<br>    kafkaTemplate.send(&quot;payment-events&quot;, order); // 2. Send to Kafka<br>}</pre><p><strong>What could possibly go wrong?</strong></p><ol><li>The database commit succeeds, but Kafka is down. (Money deducted, but downstream services never know. Alice paid, but didn’t get her coffee).</li><li>Kafka receives the message, but the database commit fails right after. (Alice gets the coffee, but her money wasn’t deducted!).</li></ol><p>This is the infamous <strong>Dual-Write Problem</strong>. You cannot atomically write to a database and a message broker.</p><h3>The Guardian of the Ledger: Transactional Outbox Pattern</h3><p>To fix the dual-write problem, we use the <strong>Outbox Pattern</strong>. Instead of sending the message directly to Kafka, we save the event <em>inside the same database</em> as part of the same local transaction.</p><pre>@Transactional<br>public void processPayment(Order order) {<br>    // 1. Insert the financial entry<br>    ledgerRepository.insertDebit(order.getUserId(), order.getAmount()); <br>    <br>    // 2. Insert the event into the outbox table (Same DB!)<br>    OutboxEvent event = new OutboxEvent(&quot;payment-events&quot;, order);<br>    outboxRepository.save(event); <br>}</pre><p>Because both inserts happen in the same relational database, they succeed or fail together. Later, a background process (like <strong>Debezium</strong> using Change Data Capture, or a simple Spring @Scheduled poller) reads the outbox table and pushes the messages to Kafka.</p><p>Guaranteed delivery? Check.</p><h3>The Spring Boot Trap: @EventListener vs. @TransactionalEventListener</h3><p>Sometimes, you want to keep your domain logic clean and use Spring’s application events to handle the Outbox insertion.</p><p>Here is a massive trap that catches many mid-level Spring developers. If you use @EventListener to listen to a domain event and write to the outbox, <strong>it executes immediately</strong>. If the main transaction rolls back, your event might still get processed or sent out!</p><p><strong>The Solution:</strong> Use @TransactionalEventListener.</p><pre>@Service<br>public class OrderService {<br>    <br>    @Transactional<br>    public void processPayment(Order order) {<br>        ledgerRepository.insertDebit(...);<br>        // Publish an internal Spring event<br>        applicationEventPublisher.publishEvent(new PaymentProcessedEvent(order));<br>    }<br>}<br><br>@Component<br>public class OutboxEventHandler {<br><br>    // THIS IS THE MAGIC!<br>    // It only triggers if the main database transaction commits successfully.<br>    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)<br>    public void handlePaymentEvent(PaymentProcessedEvent event) {<br>        outboxRepository.save(new OutboxEvent(event));<br>    }<br>}</pre><p>This single annotation (@TransactionalEventListener) ensures your events are only published if the database state is definitively saved.</p><h3>Defending Against the Clones: Idempotency</h3><p>In distributed systems, message brokers like Kafka guarantee <strong>At-Least-Once Delivery</strong>. This means a network hiccup could cause Kafka to deliver the exact same payment event twice.</p><p>If we process it twice, we’ve just deducted Alice’s money twice. (In banking, this is called <em>Duplicate Consumption</em>, not to be confused with crypto’s <em>Double-Spending</em>).</p><p>How do we protect the ledger? <strong>Idempotency.</strong></p><p>Every event must have a globally unique event_id. Before processing an event, the consumer must check if it has seen this ID before.</p><p><em>Junior approach:</em> Check Redis. (Fails under high concurrency due to Race Conditions).</p><p><em>Senior approach:</em> Let the database handle it.</p><p>Create a processed_messages table with a <strong>UNIQUE constraint</strong> on the event_id.</p><pre>CREATE TABLE processed_messages (<br>    event_id VARCHAR(255) PRIMARY KEY,<br>    created_at TIMESTAMP<br>);</pre><p>When consuming the Kafka message, you do this in one transaction:</p><ol><li>Try to insert the event_id into processed_messages.</li><li>If it throws a DataIntegrityViolationException (Unique Constraint violation), <strong>stop</strong>. You’ve already processed this message. Just ACK Kafka and move on.</li><li>If it succeeds, insert the Ledger entries.</li></ol><h3>Reversing Time: The Saga Pattern &amp; Compensating Transactions</h3><p>What happens if the money is successfully deducted in the Ledger Service, but the subsequent call to an external Payment Gateway (like Stripe) fails?</p><p>In a monolith, you’d just rollback the transaction. But in microservices, the Ledger transaction is already committed.</p><p>This is where the <strong>Saga Pattern</strong> shines. But remember our first rule: <em>The Ledger is Append-Only</em>. We cannot delete the row.</p><p>Instead, we use a <strong>Double-Entry Ledger</strong>. Every transaction creates at least two immutable records (entries). To move $100 from Alice to Bob, we <em>insert</em> two rows:</p><ol><li><strong>Debit (Alice): $100</strong> (Decreases her balance)</li><li><strong>Credit (Bob): $100</strong> (Increases his balance)</li></ol><p><strong>The Rule of Conservation:</strong> At any given millisecond, the sum of all Credits must exactly equal the sum of all Debits.</p><pre>public void compensatePayment(String originalEventId, BigDecimal amount) {<br>    // We don&#39;t delete the debit. We append a credit to cancel it out!<br>    ledgerRepository.insertCredit(userId, amount, &quot;COMPENSATION_FOR_&quot; + originalEventId);<br>}</pre><p>This leaves a perfect audit trail. The finance team can see exactly when the money was deducted and exactly when it was refunded due to a system failure.</p><h3>Final Thoughts for System Design</h3><p>Building financial systems is less about learning the latest framework and more about <strong>protecting data integrity at all costs</strong>.</p><p>The next time you are asked to “Design a Payment Gateway” in a System Design interview, don’t just throw Kafka and Microservices at the whiteboard. Talk about:</p><ol><li><strong>Append-only Ledgers</strong> to preserve history.</li><li><strong>Transactional Outbox</strong> to prevent dual-write data loss.</li><li><strong>Database-level Idempotency</strong> to survive Kafka duplicate deliveries.</li><li><strong>Compensating Transactions (Saga)</strong> instead of distributed locks (2PC).</li></ol><p>By combining these battle-tested Core Banking principles with modern Spring Boot tools like @TransactionalEventListener, you transition from just writing code to architecting resilient, enterprise-grade systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86b77b2de4b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Sidecar in Your Spring Boot App: GraalVM Native + Virtual Threads — Real Numbers]]></title>
            <link>https://medium.com/@mesfandiari77/the-sidecar-in-your-spring-boot-app-graalvm-native-virtual-threads-real-numbers-db51a8c2b718?source=rss-6ba4fd8fc2d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/db51a8c2b718</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[MEsfandiari]]></dc:creator>
            <pubDate>Sat, 05 Sep 2026 13:21:00 GMT</pubDate>
            <atom:updated>2026-09-05T13:21:00.858Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2ov-TCdud1CX4dTgiFCCOQ.png" /></figure><p>If you are designing microservices for a Kubernetes environment, you are fighting two distinct battles: <strong>Throughput</strong> (handling thousands of concurrent requests) and <strong>Density</strong> (packing as many pods as possible into a single node without getting OOMKilled).</p><p>For years, Spring Boot developers had to accept a compromise. High throughput meant dedicating large Thread Pools, which in turn demanded massive JVM heaps. But with Spring Boot 3.2+, we finally have the ultimate combo to break this limitation: <strong>GraalVM Native Image</strong> combined with <strong>Java Virtual Threads (Project Loom)</strong>.</p><p>However, before we jump into the hype, we need to separate the variables. What exactly is saving our memory? And what are the hidden engineering costs? Let’s look at the real numbers.</p><h3>Conflating Variables: Separating the Powers</h3><p>When evaluating this stack, developers often conflate the benefits. Let’s be clear:</p><ul><li><strong>Virtual Threads (VT)</strong> solve the <em>Concurrency &amp; Throughput</em> problem. They allow you to handle 10,000 concurrent requests without starving the CPU or blocking OS threads.</li><li><strong>GraalVM Native Image</strong> solves the <em>Footprint &amp; Startup</em> problem. It removes the JVM overhead, giving you instant startup and drastically lower base memory.</li></ul><p>To see the real impact, we must benchmark them independently.</p><h3>The Benchmark: Apples to Apples</h3><p>We tested a standard Spring Boot 3.2 REST API (fetching data from a Postgres DB via Spring Data R2DBC, keeping I/O non-blocking) under a load of <strong>5,000 concurrent requests</strong>.</p><p>Here is how the numbers stack up across three different configurations:</p><p><em>content_copy</em></p><p>Configuration Startup Time Peak Memory (RSS) Max Concurrency CPU Utilization <strong>1. JVM + Platform Threads</strong> (Traditional) 2.8s ~850 MB Rejects load (Thread pool exhaustion) High (Context Switching) <strong>2. JVM + Virtual Threads</strong> (Modern JVM) 2.8s ~420 MB 5,000+ (Smooth) Low (Efficient Parking) <strong>3. Native Image + Virtual Threads</strong> (Bleeding Edge) <strong>0.08s</strong> <strong>~140 MB</strong> 5,000+ (Smooth) Low</p><p><em>Notice the jump from State 1 to State 2.</em></p><p>A common myth is that an OS thread immediately consumes 1MB of physical RAM. In reality, the OS allocates 1MB of <strong>Virtual Memory</strong>, but only commits physical RAM (RSS) as the call stack grows. However, thousands of OS threads still create immense GC pressure, native memory overhead, and context-switching penalties. By simply switching to Virtual Threads on a standard JVM (State 2), we cut memory usage by half and drastically improved concurrency.</p><p>Adding GraalVM (State 3) brought the RSS down to a staggering 140MB and reduced startup time to milliseconds.</p><h3>Sidecars vs. Serverless: Why Does This Matter?</h3><p>This 140MB footprint changes how we design system architecture, but we need to distinguish between two different deployment models:</p><ol><li><strong>The Serverless / Lambda Model (Scale-to-Zero):</strong> Here, the <strong>0.08s startup time</strong> is the hero. When a burst of traffic hits, AWS Lambda or Knative can spin up new instances instantly, eliminating the dreaded “Cold Start” penalty of traditional Java.</li><li><strong>The Sidecar / Kubernetes Model (High Density):</strong> For Sidecars (like API Gateways, BFFs, or mesh proxies) that are <em>always on</em>, startup time is nice, but <strong>Low RSS Memory</strong> is the critical factor. If you need to deploy a BFF sidecar next to 50 different microservices, a 850MB JVM footprint per pod is financially disastrous. A 140MB Native footprint makes Java a viable alternative to Go or Rust for sidecar patterns.</li></ol><h3>The Hidden Costs: What They Don’t Tell You</h3><p>Before you rewrite your CI/CD pipelines, be aware of the engineering trade-offs.</p><h4>1. The Thread Pinning Trap</h4><p>A common misconception is that GraalVM’s AOT compilation limits Virtual Threads. <strong>This is scientifically incorrect.</strong> Thread Pinning is a HotSpot/Project Loom issue, not an AOT artifact.</p><p>Virtual threads work by mounting onto a carrier (OS) thread. If your code (or a legacy library) uses synchronized blocks or JNI (Java Native Interface) calls during a blocking operation, the virtual thread gets “pinned” to the carrier thread, unable to unmount. This completely nullifies the benefit of Loom, reducing your throughput back to traditional levels.</p><p><em>Note: JDK 21 improved this, and JDK 24 is rewriting Object Monitors to solve </em><em>synchronized pinning entirely, but until then, you must carefully audit your dependencies (e.g., replacing synchronized blocks with </em><em>ReentrantLock).</em></p><h4>2. Peak Performance &amp; The PGO Nightmare</h4><p>GraalVM Native Image uses Ahead-of-Time (AOT) compilation. This means it has no JIT (Just-In-Time) compiler at runtime to analyze traffic and optimize hot loops. While your app starts faster and uses less memory, its <strong>peak sustained throughput</strong> might actually be <em>lower</em> than a warm JVM.</p><p>To fix this, you need <strong>Profile-Guided Optimization (PGO)</strong>. But PGO requires a highly complex, two-stage CI/CD pipeline:</p><ol><li>Build an “instrumented” native image.</li><li>Run automated, representative load-tests against it in the pipeline to generate a profiling file (default.iprof).</li><li>Feed this profile back into a second build step to generate the final, optimized native image.</li></ol><p><em>Furthermore, advanced PGO features are heavily tied to Oracle GraalVM (under the GFTC license), not the fully open-source Community Edition, which adds a layer of licensing complexity for enterprises.</em></p><h3>The Verdict</h3><p>The combination of <strong>GraalVM Native Image + Virtual Threads</strong> is not just hype; it is a paradigm shift. It allows Spring Boot to step into territories previously dominated by Go — specifically Serverless functions and low-memory Kubernetes sidecars.</p><p>However, it demands mature engineering. You must audit your code for Thread Pinning, monitor your RSS vs. Virtual Memory correctly, and decide if the CI/CD complexity of PGO is worth the peak performance.</p><p>For high-density microservices? <strong>Adopt it.</strong></p><p>For monolithic, CPU-heavy legacy apps? <strong>Stick to the JVM.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db51a8c2b718" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[10 Core Java Concepts That Mid-Level Developers Still Get Wrong in 2026]]></title>
            <link>https://medium.com/@mesfandiari77/10-core-java-concepts-that-mid-level-developers-still-get-wrong-in-2026-760eda67eaf9?source=rss-6ba4fd8fc2d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/760eda67eaf9</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[core-java]]></category>
            <dc:creator><![CDATA[MEsfandiari]]></dc:creator>
            <pubDate>Thu, 11 Jun 2026 11:36:00 GMT</pubDate>
            <atom:updated>2026-06-11T11:36:00.684Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_6s_sTddnPJ4n-Huxp9cFQ.png" /></figure><p>Confession time: Last week, I reviewed a PR from a very talented mid-level Java developer, and I found a bug that I used to write all the time back in my early days. It wasn’t a complex architectural flaw or a misunderstanding of microservices. It was a simple, innocent misunderstanding of how Java manages memory.</p><p>It’s <strong>2026</strong>. We have Virtual Threads, AI-powered IDEs, and Project Panama. Java has evolved at a blistering pace. Yet, the things that crash our production environments are rarely the shiny new features. It’s almost always the core fundamentals — the stuff we assume we mastered years ago.</p><p>No judgment here. We’ve all stared at a NullPointerException at 2 AM. But let’s clear the air. Here are 10 core Java concepts that still trip up mid-level developers today, and how to finally get them right.</p><h3>1. The Integer Pool Trap (== vs .equals())</h3><p>We all know we shouldn’t use == to compare Strings. But what about Integers?</p><pre>Integer a = 100;<br>Integer b = 100;<br>System.out.println(a == b); // true! <br><br>Integer x = 200;<br>Integer y = 200;<br>System.out.println(x == y); // false! Wait, what?</pre><p><strong>Why it happens:</strong> Java caches Integer objects from -128 to 127 by default. When you compare 100, you are comparing the same cached object reference. When you compare 200, you are comparing two entirely different objects in the heap. Always use .equals() for objects! <br><strong>Dive deeper:</strong> I wrote a whole breakdown on this exact memory quirk here: <strong>[“</strong><a href="https://medium.com/@mesfandiari77/understanding-the-integer-pool-in-java-how-it-works-and-why-it-matters-4a289831e5fd"><strong>Understanding the Integer Pool in Java: How It Works and Why It Matters</strong></a><strong>”]</strong></p><h3>2. Assuming Arrays.asList() is Immutable</h3><p>You want to create a quick list, so you use Arrays.asList(). Later in the code, someone tries to add an element to it.</p><pre>List&lt;String&gt; names = Arrays.asList(&quot;Alice&quot;, &quot;Bob&quot;);<br>names.add(&quot;Charlie&quot;); //UnsupportedOperationException!</pre><p><strong>Why it happens:</strong> Arrays.asList() returns a fixed-size list backed by the original array. You can’t add or remove elements, but you <em>can</em> modify existing ones. If you want a truly immutable list in modern Java, you should use List.of(). <br><strong>Dive deeper:</strong> This mistake is so common I dedicated an entire post to it: <strong>[“</strong><a href="https://medium.com/@mesfandiari77/list-of-vs-arrays-aslist-key-differences-that-could-crash-your-code-2a458a5d035f"><strong>List.of() vs. Arrays.asList(): Key Differences That Could Crash Your Code</strong></a><strong>”]</strong></p><h3>3. The ThreadLocal Disaster with Virtual Threads</h3><p>With Java 21+, Virtual Threads became the standard for handling high concurrency. But many developers simply lift-and-shift their old codebase, bringing their ThreadLocal variables with them. <strong>Why it happens:</strong> Millions of Virtual Threads holding onto ThreadLocal data can cause massive memory leaks because Virtual Threads are cheap, but the data you store inside them might not be!<br> <strong>Dive deeper:</strong> Before you migrate to Virtual Threads, read this: <strong>[“</strong><a href="https://medium.com/@mesfandiari77/exploring-thread-local-and-virtual-thread-in-java-a04a5d43a00d"><strong>Exploring Thread Local and Virtual Thread in Java</strong></a><strong>”]</strong></p><h3>4. Thinking Clone() Does a Deep Copy</h3><p>You have a complex object Order that contains a Customer object. You use the prototype pattern or clone() to copy it. You change the customer’s name in the cloned order, and suddenly, the original order’s customer name changes too! <strong>Why it happens:</strong> By default, Java performs a <strong>Shallow Copy</strong>. It copies primitive values, but for objects, it only copies the <em>reference</em>. Both your original and cloned objects are pointing to the exact same Customer in memory. <br><strong>Dive deeper:</strong> Learn how to fix this using serialization or copy constructors here: <strong>[“</strong><a href="https://medium.com/@mesfandiari77/deep-copy-vs-shallow-copy-in-java-whats-the-difference-and-how-to-implement-them-def4510d55c1"><strong>Deep Copy vs. Shallow Copy in Java: What’s the Difference and How to Implement Them</strong></a><strong>”]</strong></p><h3>5. String Concatenation in Loops (+ operator)</h3><p>I still see this in 2026, even in codebases written by experienced devs:</p><pre>String result = &quot;&quot;;<br>for(String word : words) {<br>    result += word; //Please stop doing this!<br>}</pre><p><strong>Why it happens:</strong> Strings in Java are immutable. Every time you use + in a loop, Java creates a brand new String object and throws the old one away. This triggers aggressive Garbage Collection and kills CPU performance. Use StringBuilder.</p><p><strong>Dive deeper:</strong> See the performance benchmarks here: <strong>[“</strong><a href="https://medium.com/@mesfandiari77/comparing-string-stringbuilder-and-stringbuffer-in-java-choosing-the-right-class-for-efficient-9f77cac4c2d8">Comparing String, StringBuilder, and StringBuffer in Java: Choosing the Right Class for Efficient String Manipulation</a><strong>”]</strong></p><h3>6. The “Silent Resource Leak” (Try-Catch)</h3><p>Opening a database connection or a file stream inside a try block, and forgetting to close it in a finally block (or closing it improperly so it throws another exception). <strong>Why it happens:</strong> We are humans, we forget things. Java gave us Try-With-Resources specifically to solve this. If a class implements AutoCloseable, let Java close it for you automatically.</p><p><strong>Dive deeper:</strong> Stop writing finally blocks and read this: <strong>[“</strong><a href="https://medium.com/@mesfandiari77/try-catch-vs-try-with-resources-in-java-03f262c571a8"><strong>Try-Catch vs. Try-With-Resources in Java</strong></a><strong>”]</strong></p><h3>7. HashSets and Missing hashCode()</h3><p>You create a Set&lt;User&gt; to ensure you don’t have duplicate users. But when you print the Set, you see the exact same user twice! <strong>Why it happens:</strong> A HashSet relies on the hashCode() and equals() methods to determine uniqueness. If you don’t override them in your User class, Java uses the memory address. To Java, two identical users in different memory locations are two completely different things.</p><p><strong>Dive deeper:</strong> Uncover the magic of Java’s Set interface here: <strong>[“</strong><a href="https://medium.com/@mesfandiari77/how-does-set-in-java-know-that-it-is-a-duplicate-item-35a94fbbfeef"><strong>How does set in Java know that it is a duplicate item?</strong></a><strong>”]</strong></p><h3>8. The Annotation Illusion (@NotNull vs @Nonnull)</h3><p>You add @NotNull to a field in your DTO, run the app, pass a null value, and… it processes successfully anyway. Wait, didn’t the annotation protect you? <strong>Why it happens:</strong> Annotations are just metadata. They don’t <em>do</em> anything on their own. Unless you have a validation framework (like Hibernate Validator) active and configured with @Valid, those annotations are practically invisible at runtime. Furthermore, picking the wrong import (e.g., Spring’s @NonNull vs Jakarta’s @NotNull) changes how tools react to them.</p><p><strong>Dive deeper:</strong> This article has helped thousands of devs clear up the confusion: <strong>[“</strong><a href="https://medium.com/@mesfandiari77/understanding-notnull-vs-nonnull-in-java-a-practical-guide-to-null-safety-5e179e918f37"><strong>Understanding @NotNull vs @Nonnull in Java: A Practical Guide to Null-Safety</strong></a><strong>”]</strong></p><h3>9. Confusion Around Generics (Type Erasure)</h3><p>You try to overload a method like this:</p><pre>public void process(List&lt;String&gt; strings) { ... }<br>public void process(List&lt;Integer&gt; integers) { ... } //Compile Error!</pre><p><strong>Why it happens:</strong> At runtime, Java doesn’t know about &lt;String&gt; or &lt;Integer&gt;. It erases the generics for backward compatibility (Type Erasure). To the JVM, both methods have the exact same signature: process(List).</p><p><strong>Dive deeper:</strong> Brush up on your polymorphism concepts here: <strong>[“</strong><a href="https://medium.com/@mesfandiari77/understanding-overloading-and-overriding-in-java-achieving-polymorphism-in-object-oriented-41a5315029cf"><strong>Understanding Overloading and Overriding in Java: Achieving Polymorphism in Object-Oriented Programming</strong></a><strong>”]</strong></p><h3>10. Pass-by-Value vs. Pass-by-Reference</h3><p>This is the ultimate classic. <em>Java is strictly pass-by-value.</em> Period. When you pass an object to a method, you are not passing the object itself, nor are you passing a reference. You are passing a <strong>copy of the reference</strong> by value. You can change the object’s internal state (like user.setName()), but you cannot reassign the object to a completely new instance inside the method and expect the caller to see it.</p><h3>The Takeaway</h3><p>Being a Senior developer doesn’t mean you know every new shiny framework out there. It means you have made all these core mistakes so many times that you instantly spot them in PRs.</p><p>Java is a deeply beautiful, sometimes eccentric language. Mastering these fundamentals will save you hours of debugging and make you a mentor to the juniors on your team.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=760eda67eaf9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Death of Passwords: How to Implement Passkeys (WebAuthn) in Spring Security 6.x]]></title>
            <link>https://medium.com/@mesfandiari77/the-death-of-passwords-how-to-implement-passkeys-webauthn-in-spring-security-6-x-a175cd1ebc3f?source=rss-6ba4fd8fc2d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/a175cd1ebc3f</guid>
            <category><![CDATA[webauthn]]></category>
            <category><![CDATA[spring-security]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[MEsfandiari]]></dc:creator>
            <pubDate>Sat, 06 Jun 2026 09:16:00 GMT</pubDate>
            <atom:updated>2026-06-06T09:16:00.589Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Death of Passwords: How to Implement Passkeys (WebAuthn) in Spring Security 6.x Without Going Crazy</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a3MneRqNs_r2YanDbK1L3w.png" /></figure><p>If there is one thing developers and end-users mutually despise, it’s <strong>passwords</strong>.</p><p>Users hate remembering them, so they reuse “P@ssw0rd123!” across 50 different websites. Developers hate them because we have to hash them, salt them, build “Forgot Password” flows, and lie awake at night praying our database doesn’t end up on the dark web.</p><p>It’s <strong>2026</strong>. Using passwords today feels like using a fax machine. The tech giants (Apple, Google, Microsoft) have already moved on to <strong>Passkeys (WebAuthn)</strong>. You know that smooth experience where you just look at your phone (FaceID) or touch your laptop’s fingerprint sensor to log in? That’s WebAuthn. No passwords, no phishing, no shared secrets.</p><p>But here is the problem: When you tell a Java developer to implement a new security protocol, their heart skips a beat. <em>“Oh no… do I have to configure Spring Security again?”</em></p><p>Configuring Spring Security historically felt like trying to defuse a bomb blindfolded. But I have good news! With <strong>Spring Security 6.x</strong>, implementing WebAuthn is surprisingly elegant. Today, I’m going to show you how to kill passwords in your Spring Boot app — without losing your sanity.</p><h3>What Exactly is a Passkey? (The ELI5 Version)</h3><p>Before we write code, let’s demystify the magic.</p><p>WebAuthn uses <strong>Public Key Cryptography</strong>.</p><ol><li>Registration: When a user signs up, their device (phone/laptop) generates a cryptographic key pair. The private key stays locked safely inside the device’s hardware (like Apple’s Secure Enclave). The public key is sent to your Spring Boot backend and saved in the database.</li><li>Login: When the user logs in, your server sends a random “challenge” string. The user’s device asks for their biometric (FaceID/TouchID) to unlock the private key, signs the challenge, and sends it back. Your server verifies it using the public key.</li></ol><p><strong>Why is this revolutionary?</strong> Even if a hacker dumps your entire database, they only get <em>public keys</em>. They are mathematically useless without the user’s physical phone and their actual face. Phishing is officially dead.</p><h3>Step 1: The Setup</h3><p>First, we need the right dependencies. Assuming you are on Spring Boot 3.x, open your pom.xml. Spring Security now has native support for WebAuthn!</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-starter-security&lt;/artifactId&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.security&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-security-webauthn&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><h3>Step 2: The Security Filter Chain (The Clean Way)</h3><p>Remember the dark days of extending WebSecurityConfigurerAdapter? Those days are gone. In Spring Security 6.x, we use the Lambda DSL to define our SecurityFilterChain.</p><p>Here is how you tell Spring to enable Passkeys:</p><pre>@Configuration<br>@EnableWebSecurity<br>public class SecurityConfig {<br><br>    @Bean<br>    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {<br>        http<br>            .authorizeHttpRequests(auth -&gt; auth<br>                .requestMatchers(&quot;/public/**&quot;, &quot;/login&quot;).permitAll()<br>                .anyRequest().authenticated()<br>            )<br>            // The Magic Line <br>            .webAuthn(webAuthn -&gt; webAuthn<br>                .rpName(&quot;My Awesome App&quot;)<br>                .rpId(&quot;localhost&quot;) // Change to your actual domain in production!<br>            )<br>            // Disable default form login because we don&#39;t want passwords!<br>            .formLogin(AbstractHttpConfigurer::disable);<br><br>        return http.build();<br>    }<br>}</pre><p>Yes, that’s it. By adding .webAuthn(), Spring Security automatically registers the endpoints required to handle the WebAuthn registration and authentication flows. It’s like magic, but better, because you can read the source code.</p><h3>Step 3: Storing the Keys (Where does the data go?)</h3><p>Your backend needs a place to store the Public Keys. Spring Security provides an interface called WebAuthnAuthenticatorRepository.</p><p>For a quick PoC, Spring provides an in-memory repository. But you’re a pro, so you’ll want to store this in a real database (PostgreSQL/MySQL) using JPA.</p><p>You just need to implement the interface:</p><pre>@Component<br>public class JpaWebAuthnRepository implements WebAuthnAuthenticatorRepository {<br><br>    private final CredentialRepository repository; // Your Spring Data JPA Interface<br><br>    public JpaWebAuthnRepository(CredentialRepository repository) {<br>        this.repository = repository;<br>    }<br><br>    @Override<br>    public void save(WebAuthnAuthenticator authenticator) {<br>        // Map Spring&#39;s object to your JPA Entity and save it<br>        CredentialEntity entity = mapToEntity(authenticator);<br>        repository.save(entity);<br>    }<br><br>    @Override<br>    public WebAuthnAuthenticator findByCredentialId(ByteArray credentialId) {<br>        // Fetch the public key from your DB when the user tries to log in<br>        return repository.findByCredentialId(credentialId.getBytes())<br>                         .map(this::mapToAuthenticator)<br>                         .orElse(null);<br>    }<br>    <br>    // ... implement other required methods<br>}</pre><p>Once you create this @Component, Spring Security automatically detects it and uses your database to store and retrieve the Passkeys.</p><h3>Step 4: The Frontend Touch</h3><p>I know this is a backend article, but WebAuthn requires a tiny bit of JavaScript on your frontend to trigger the biometric prompt on the user’s device.</p><p>Thanks to standard browser APIs, it’s surprisingly simple. When the user clicks “Log in with Passkey”, you call the standard navigator.credentials API:</p><pre>// This tells the browser to pop up the FaceID / TouchID prompt<br>const credential = await navigator.credentials.get({<br>    publicKey: optionsFromServer // The challenge string Spring Security generated<br>});<br><br>// Send the signed challenge back to Spring Boot<br>await fetch(&#39;/login/webauthn&#39;, {<br>    method: &#39;POST&#39;,<br>    body: JSON.stringify(credential)<br>});</pre><h3>The Bottom Line</h3><p>Implementing Passkeys used to require a PhD in cryptography and writing thousands of lines of custom security filters. In 2026, Spring Security 6.x has abstracted the hardest parts away.</p><p>By dropping passwords, you are:</p><ol><li>Enhancing Security: Eradicating credential stuffing and phishing attacks.</li><li>Improving UX: Nobody wants to reset their password for the 5th time this month. Looking at your phone is a 1-second process.</li><li>Reducing Liability: You no longer store secrets. A database breach is no longer a catastrophic company-ending event.</li></ol><p>It’s time to let passwords die peacefully. Let WebAuthn do the heavy lifting, and let your users log in with a smile (literally, FaceID needs to see it!).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a175cd1ebc3f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[REST is No Longer Enough: gRPC vs. GraphQL vs. REST in Spring Boot 3.5 (When to use what in 2026)]]></title>
            <link>https://medium.com/@mesfandiari77/rest-is-no-longer-enough-grpc-vs-graphql-vs-rest-in-spring-boot-3-5-when-to-use-what-in-2026-dfaf6f19891b?source=rss-6ba4fd8fc2d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfaf6f19891b</guid>
            <category><![CDATA[api-design]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[MEsfandiari]]></dc:creator>
            <pubDate>Wed, 03 Jun 2026 11:06:00 GMT</pubDate>
            <atom:updated>2026-06-03T11:06:00.588Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uql0uhk0L-Fmi8MHpD7ZuQ.png" /></figure><p><strong>Let’s be honest for a second.</strong> If I asked you to build a new API today, your muscle memory would probably kick in immediately: add spring-boot-starter-web, slap a @RestController on a class, return some JSON, and call it a day.</p><p>For the last decade, REST has been our trusty Swiss Army knife. It got the job done. But it’s <strong>May 2026</strong>, and application architectures have evolved. Microservices are chattier than ever, frontend frameworks are aggressively demanding optimized payloads, and milliseconds of latency can actually cost you users.</p><p>Using REST for <em>everything</em> in 2026 is like using a screwdriver to hammer a nail. It works, but it’s going to hurt eventually.</p><p>With <strong>Spring Boot 3.5</strong> maturing and making it easier than ever to integrate modern protocols, the “REST default” is officially being challenged. Today, we’re putting REST, GraphQL, and gRPC in the ring. By the end of this article, you’ll know exactly which tool to reach for in your next Spring Boot project.</p><h3>The Undisputed Heavyweight: REST (Representational State Transfer)</h3><p>Let’s get one thing straight: <strong>REST isn’t dead.</strong> Not by a long shot.</p><p>REST over HTTP/1.1 (or HTTP/2) returning JSON is still the undisputed king of public-facing APIs. It’s stateless, cacheable, and literally every developer on the planet knows how to consume it.</p><h3>Why we still love it:</h3><ul><li>Zero learning curve: Everyone understands GET, POST, PUT, DELETE.</li><li>Tooling: Postman, Swagger/OpenAPI, and browser DevTools make debugging a breeze.</li><li>Caching: HTTP-level caching works out of the box.</li></ul><h3>Where it breaks your heart (and your app):</h3><ul><li>Over-fetching &amp; Under-fetching: You call /api/users/123 just to get the user’s firstName, but the server sends back a massive 2KB JSON blob containing their entire life history.</li><li>The N+1 API Problem: To render a dashboard, your frontend has to make 5 different REST calls to 5 different endpoints, killing network performance.</li><li>Bloated Payloads: JSON is text-heavy. Parsing JSON at scale is surprisingly CPU-intensive for your backend.</li></ul><h3>The Frontend’s Best Friend: GraphQL</h3><p>Imagine going to a restaurant, opening the menu, and instead of ordering a pre-defined “Burger Meal”, you tell the chef: <em>“I want the bun, the beef patty, but skip the lettuce, and give me exactly 12 fries.”</em></p><p>That is <strong>GraphQL</strong>.</p><p>Developed by Facebook and now a massive part of the Spring ecosystem (thanks to spring-boot-starter-graphql), GraphQL shifts the power from the backend to the client. There is only <strong>one endpoint</strong> (usually /graphql), and the client sends a query specifying exactly what fields it wants.</p><h3>How it looks in Spring Boot 3.5:</h3><p>Gone are the days of complex boilerplate. Spring Boot makes GraphQL feel like magic:</p><pre>@Controller<br>public class UserController {<br><br>    @QueryMapping<br>    public User userById(@Argument String id) {<br>        return userRepository.findById(id);<br>    }<br><br>    @SchemaMapping<br>    public List&lt;Order&gt; orders(User user) {<br>        // Only executed if the client specifically asks for the user&#39;s orders!<br>        return orderRepository.findByUserId(user.getId());<br>    }<br>}</pre><h3>Why you should use it:</h3><ul><li>No more over-fetching: Mobile developers will love you. The payload is exactly what they asked for, saving bandwidth and battery life.</li><li>Rapid Frontend iteration: Frontend teams don’t need to beg backend teams to “add a new field to the API.”</li></ul><h3>The dark side of GraphQL:</h3><ul><li>Caching is a nightmare: Because everything goes through a single POST /graphql endpoint, you can’t rely on standard HTTP caching.</li><li>Performance risks: If you aren’t careful, a client can send a deeply nested query that accidentally triggers an N+1 database problem on your backend.</li></ul><h3>The Backend Speed Demon: gRPC</h3><p>If REST is a commercial airliner and GraphQL is a private jet, <strong>gRPC is a teleportation device.</strong></p><p>Created by Google, gRPC uses <strong>HTTP/2</strong> and <strong>Protocol Buffers (Protobuf)</strong> instead of JSON. Instead of sending bulky text back and forth, it sends heavily compressed, binary data.</p><p>In a modern microservices architecture, where Service A talks to Service B, which talks to Service C, using REST (JSON) adds massive serialization/deserialization overhead. gRPC eliminates this.</p><h3>Why it’s taking over the backend:</h3><ul><li>Blazing Fast: Binary data is significantly smaller and much faster to serialize/deserialize than JSON.</li><li>Strict Contracts: You define your API in a .proto file. From this file, you generate client and server code in Java, Go, Python, etc. If you break the contract, your code literally won’t compile. No more guessing game!</li><li>Streaming out of the box: gRPC supports bidirectional streaming effortlessly.</li></ul><h3>How it looks (The Contract):</h3><pre>syntax = &quot;proto3&quot;;<br><br>service UserService {<br>  rpc GetUser (UserRequest) returns (UserResponse);<br>}<br><br>message UserRequest {<br>  string user_id = 1;<br>}<br><br>message UserResponse {<br>  string name = 1;<br>  string email = 2;<br>}</pre><p>In Spring Boot 3.5, native integration for gRPC has reached a point where you just add a @GrpcService annotation, and you’re good to go.</p><h3>The Catch:</h3><ul><li>Not browser-friendly: Browsers don’t natively speak gRPC (yet). You usually need a proxy (like gRPC-Web or an API Gateway) to expose it to frontend clients.</li><li>Harder to debug: You can’t just read binary data in your browser’s network tab. You need specific tools to inspect gRPC traffic.</li></ul><h3>The Ultimate Decision Matrix (2026 Edition)</h3><p>So, you are starting a new Spring Boot service tomorrow. Which one do you pick? Here is your cheat sheet:</p><ol><li>Choose REST if:</li></ol><ul><li>You are building a public-facing API for third-party developers.</li><li>Your service is mostly simple CRUD operations.</li><li>You need aggressive, standard HTTP caching.</li></ul><p>2. Choose GraphQL if:</p><ul><li>Your API is primarily consumed by modern Web/Mobile frontends.</li><li>Your data graph is highly relational (e.g., fetching a User, their Posts, and Comments on those posts in one go).</li><li>You have multiple client apps that need different data shapes from the same API.</li></ul><p>3. Choose gRPC if:</p><ul><li>You are building internal Service-to-Service communication (Microservices).</li><li>Performance, low latency, and high throughput are your top priorities.</li><li>You are building polyglot microservices (e.g., a Java Spring Boot app talking to a Go or Rust service) and want strict API contracts.</li></ul><h3>The Hybrid Reality</h3><p>In most modern architectures I see in 2026, the answer is usually a combination. A very common and highly scalable pattern is:</p><ul><li>GraphQL at the API Gateway level (for frontends to query exactly what they need).</li><li>gRPC behind the scenes, where internal Spring Boot microservices communicate with each other at lightning speed.</li></ul><p>REST is no longer the default — it’s just one of the options. As Senior developers, our job isn’t just to write code; it’s to choose the right communication protocol for the exact problem we’re solving.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfaf6f19891b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Returning Generic 400 Errors: The Senior Developer’s Guide to RFC 7807 (Problem Details) in…]]></title>
            <link>https://medium.com/@mesfandiari77/stop-returning-generic-400-errors-the-senior-developers-guide-to-rfc-7807-problem-details-in-ac5be6127950?source=rss-6ba4fd8fc2d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac5be6127950</guid>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[api-design]]></category>
            <dc:creator><![CDATA[MEsfandiari]]></dc:creator>
            <pubDate>Thu, 28 May 2026 14:16:00 GMT</pubDate>
            <atom:updated>2026-05-28T14:16:00.908Z</atom:updated>
            <content:encoded><![CDATA[<h3>Stop Returning Generic 400 Errors: The Senior Developer’s Guide to RFC 7807 (Problem Details) in Spring Boot 3</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*37MNFRC_GX2aGTU28_NW0A.png" /></figure><p>We’ve all been there. You’re integrating with a third-party API, you send a payload, and you get this highly “helpful” response back:</p><pre>{<br>  &quot;timestamp&quot;: &quot;2025-05-17T10:15:30Z&quot;,<br>  &quot;status&quot;: 400,<br>  &quot;error&quot;: &quot;Bad Request&quot;,<br>  &quot;message&quot;: &quot;Validation failed&quot;,<br>  &quot;path&quot;: &quot;/api/v1/users&quot;<br>}</pre><p><em>Great.</em> What exactly failed? Was it the email format? Was the password too short? Did I forget a mandatory field? The frontend developer is now messaging you on Slack, asking why your API is rejecting their form.</p><p>For years, the Java community has solved this by creating massive, custom @RestControllerAdvice classes. Every team invents its own ApiErrorResponse object. One team uses errorCode, another uses internalCode, and someone else uses developerMessage. It’s a chaotic mess.</p><p>It’s time to stop reinventing the wheel. Let’s talk about <strong>RFC 7807 (Problem Details)</strong> and how Spring Boot 3 makes standardizing your API errors almost embarrassingly easy.</p><h3>What is RFC 7807?</h3><p>RFC 7807 is an IETF standard that defines a universal, standardized JSON structure for HTTP API errors. Instead of making the frontend guess how you formatted your error response, you give them a predictable structure.</p><p>A standard “Problem Details” response looks like this:</p><pre>{<br>  &quot;type&quot;: &quot;https://api.mycoolapp.com/errors/insufficient-funds&quot;,<br>  &quot;title&quot;: &quot;Insufficient Funds&quot;,<br>  &quot;status&quot;: 400,<br>  &quot;detail&quot;: &quot;Your current balance is $30, but the item costs $50.&quot;,<br>  &quot;instance&quot;: &quot;/users/123/transactions&quot;,<br>  &quot;balance&quot;: 30<br>}</pre><p>Notice a few cool things?</p><ol><li><strong>type</strong>: A URI identifying the specific problem.</li><li><strong>title</strong>: A short, human-readable summary.</li><li><strong>detail</strong>: The exact reason it failed.</li><li><strong>Custom fields</strong>: Notice the balance field? You can add your own custom properties to the standard object!</li></ol><h3>The Spring Boot 3 Magic Trick</h3><p>In the old days of Spring Boot 2.x, implementing this meant adding third-party libraries (like Zalando’s Problem library) or writing a lot of boilerplate.</p><p>In Spring Boot 3, it is built directly into the framework. You can enable the standard globally with exactly <strong>one line</strong> in your application.yml or application.properties:</p><pre>spring:<br>  mvc:<br>    problem-details:<br>      enabled: true</pre><p><em>(Note: If you are using WebFlux, it’s </em><em>spring.webflux.problem-details.enabled=true)</em></p><p>Just by adding that line, Spring Boot will instantly convert all standard framework exceptions (like MethodArgumentNotValidException or NoHandlerFoundException) into beautiful, RFC 7807 compliant JSON.</p><h3>Taking Control: Throwing Custom Problem Details</h3><p>What about your custom business logic exceptions? Spring Boot 3 provides a brilliant ProblemDetail class that you can use in your @ExceptionHandler.</p><p>Instead of mapping your UserNotFoundException to a custom Map, do this:</p><pre>import org.springframework.http.HttpStatus;<br>import org.springframework.http.ProblemDetail;<br>import org.springframework.web.bind.annotation.ExceptionHandler;<br>import org.springframework.web.bind.annotation.RestControllerAdvice;<br>import java.net.URI;<br><br>@RestControllerAdvice<br>public class GlobalExceptionHandler {<br><br>    @ExceptionHandler(InsufficientFundsException.class)<br>    public ProblemDetail handleInsufficientFunds(InsufficientFundsException ex) {<br>        <br>        ProblemDetail problem = ProblemDetail.forStatusAndDetail(<br>                HttpStatus.BAD_REQUEST, <br>                &quot;Your current balance is insufficient to complete this transaction.&quot;<br>        );<br>        <br>        problem.setType(URI.create(&quot;https://api.mycoolapp.com/errors/insufficient-funds&quot;));<br>        problem.setTitle(&quot;Insufficient Funds&quot;);<br>        <br>        // Add custom properties!<br>        problem.setProperty(&quot;current_balance&quot;, ex.getCurrentBalance());<br>        problem.setProperty(&quot;required_amount&quot;, ex.getRequiredAmount());<br>        <br>        return problem;<br>    }<br>}</pre><p>Alternatively, you can have your custom exceptions extend ErrorResponseException, and Spring will handle the mapping automatically without even needing an @ExceptionHandler!</p><h3>The Verdict</h3><p>As senior developers, our job isn’t just to write code that works; it’s to write APIs that are a joy to consume. By adopting RFC 7807, you instantly make your API feel more professional, you eliminate endless frontend/backend communication loops, and you get rid of hundreds of lines of custom error-handling boilerplate.</p><p>If you are starting a new Spring Boot 3 project today, turning on Problem Details should be step number one.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac5be6127950" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Offset vs. Cursor Pagination in Spring Boot: Why “LIMIT & OFFSET” is Killing Your Database]]></title>
            <link>https://medium.com/@mesfandiari77/offset-vs-cursor-pagination-in-spring-boot-why-limit-offset-is-killing-your-database-f3ff1063b049?source=rss-6ba4fd8fc2d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3ff1063b049</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[pagination]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[database-performance]]></category>
            <dc:creator><![CDATA[MEsfandiari]]></dc:creator>
            <pubDate>Fri, 22 May 2026 12:01:00 GMT</pubDate>
            <atom:updated>2026-05-22T12:01:00.705Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*COmUvRkycfeHX3ixh0cI7A.png" /></figure><h3>Performance</h3><p>Picture this: You’ve just deployed a shiny new REST API. Your database has a few thousand records, and your standard PageRequest.of(page, size) is running fast. You feel like a genius.</p><p>Fast forward six months. Your app went viral. Your table now has 10 million rows. Suddenly, users are complaining that the app freezes when they jump to older records. You check your logs and see database queries taking 5, 10, or even 20 seconds.</p><p>What happened? You just became a victim of <strong>Offset Pagination</strong>.</p><p>Let’s talk about why the traditional way we do pagination is secretly destroying your database performance, and how Spring Boot 3 gives you the ultimate weapon to fix it: <strong>Cursor (or Keyset) Pagination</strong>.</p><h3>The Silent Killer: How OFFSET Actually Works</h3><p>When you use Spring Data JPA’s standard Pageable, Hibernate translates it into a SQL query using LIMIT and OFFSET.</p><p>If a user wants page 10,000 (assuming 10 items per page), the query looks something like this:</p><pre>SELECT * FROM orders ORDER BY created_at DESC LIMIT 10 OFFSET 100000;</pre><p><strong>Here is the ugly truth about relational databases:</strong> To skip 100,000100,000100,000 rows, the database doesn’t just magically jump to row 100,001100,001100,001. It actually has to fetch, read, and discard all 100,000100,000100,000 preceding rows before giving you the 10 rows you asked for.</p><p>As your OFFSET grows, the query gets exponentially slower. The time complexity degrades to O(N)O(N)O(N), where NNN is the offset. If a search engine bot or a curious user clicks “Next Page” enough times, they can accidentally DDoS your database.</p><h3>The Savior: Cursor Pagination</h3><p>What if, instead of telling the database “skip 100,000 rows,” we simply said: “Give me the next 10 rows that come <em>after</em> this specific item”?</p><p>This is <strong>Cursor Pagination</strong> (also known as Keyset Pagination). Instead of passing a page number, you pass a unique identifier (the cursor) from the last item of the previous page.</p><p>The query changes to this:</p><pre>SELECT * FROM orders WHERE id &lt; 987654 ORDER BY id DESC LIMIT 10;</pre><p><strong>Why is this a game-changer?</strong></p><p>Because if id is indexed, the database uses a B-Tree lookup to instantly find row 987654 and grab the next 10 items. The performance remains O(1)O(1)O(1). It takes the exact same milliseconds to fetch page 1 as it does to fetch page 1,000,000!</p><h3>How to do it in Spring Boot 3.x</h3><p>In the past, implementing cursor pagination in Spring required writing custom JPQL or native queries. But Spring Boot 3 (and Spring Data JPA 3.x) finally made it a first-class citizen!</p><p>Instead of returning a Page&lt;T&gt;, you can now return a Window&lt;T&gt; and use ScrollPosition.</p><p>Here is how simple it is in your Repository:</p><pre>import org.springframework.data.domain.Window;<br>import org.springframework.data.domain.ScrollPosition;<br>import org.springframework.data.repository.ListCrudRepository;<br><br>public interface OrderRepository extends ListCrudRepository&lt;Order, Long&gt; {<br>    <br>    // The magic happens here!<br>    Window&lt;Order&gt; findFirst10ByOrderByCreatedAtDesc(ScrollPosition position);<br>}</pre><p>And in your Service layer, you handle it like this:</p><pre>// Fetching the first page<br>Window&lt;Order&gt; firstPage = orderRepository.findFirst10ByOrderByCreatedAtDesc(ScrollPosition.keyset());<br><br>// Fetching the next page using the cursor from the last element<br>if (firstPage.hasNext()) {<br>    ScrollPosition nextCursor = firstPage.positionAt(firstPage.getSize() - 1);<br>    Window&lt;Order&gt; secondPage = orderRepository.findFirst10ByOrderByCreatedAtDesc(nextCursor);<br>}</pre><h3>The Verdict: Which one should you use?</h3><p>Does this mean you should delete Pageable from your codebase right now? Not exactly.</p><p><strong>Use Offset Pagination (Pageable) if:</strong></p><ul><li>Your dataset is small and will never grow massive.</li><li>You strictly need “Jump to Page X” functionality (like a grid on an admin dashboard).</li><li>You need to show the “Total Pages” count to the user.</li></ul><p><strong>Use Cursor Pagination (ScrollPosition) if:</strong></p><ul><li>You are building “Infinite Scroll” functionality (like social media feeds).</li><li>Your dataset is huge, and performance is critical.</li><li>Data is being added or deleted constantly (Offset pagination can cause items to be skipped or duplicated if data changes while the user is clicking “Next”, but Cursor pagination prevents this!).</li></ul><p><strong>Final Thoughts</strong></p><p>Stop letting OFFSET drag down your API response times. With Spring Boot 3 making it this easy, upgrading your heavy endpoints to Cursor Pagination is a no-brainer. Your database (and your users) will thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3ff1063b049" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond Logs: Why Spring Boot 3.x + OpenTelemetry is the Only Observability Stack You Need]]></title>
            <link>https://medium.com/@mesfandiari77/beyond-logs-why-spring-boot-3-x-opentelemetry-is-the-only-observability-stack-you-need-6ceb0fde71ab?source=rss-6ba4fd8fc2d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ceb0fde71ab</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[opentelemetry]]></category>
            <dc:creator><![CDATA[MEsfandiari]]></dc:creator>
            <pubDate>Sat, 16 May 2026 06:36:00 GMT</pubDate>
            <atom:updated>2026-05-16T06:36:00.619Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Tn7wKkzqajutuaRZq9VGg.png" /></figure><p>Picture this: It’s 3:00 AM. Your phone buzzes. The payment service in your microservices architecture is failing. You grab your laptop, open your logging dashboard, and search for the error.</p><p>What do you see? A chaotic waterfall of log.info(), log.error(), and meaningless stack traces from five different services, all mixed together. Finding the root cause feels like trying to find a needle in a haystack—while the haystack is on fire.</p><p>If you’ve been building Java applications for a while, you know this pain. But what if I told you that in 2026, hunting down bugs in distributed systems doesn’t have to be a nightmare?</p><p>Thanks to the incredible pairing of <strong>Spring Boot 3.x</strong> and <strong>OpenTelemetry (OTel)</strong>, the days of relying purely on logs are over. Let’s talk about why this duo is the only observability stack you need.</p><h3>The Problem with “Just Logs”</h3><p>For years, our debugging strategy was simple: whenever something important happens, print a log.</p><p>This works great for monoliths. But in a modern system where a single user click triggers a frontend API, an auth service, a database, a message broker, and a billing service… logs are no longer enough.</p><p>If the request fails at step four, looking at the auth service’s logs won’t help you. You need a way to track that specific request as it travels across your entire architecture. You don’t just need logs; you need <strong>Observability</strong>.</p><p>Observability relies on three pillars working together:</p><ol><li><strong>Logs:</strong> <em>What</em> went wrong?</li><li><strong>Metrics:</strong> <em>How often</em> is it going wrong?</li><li><strong>Traces:</strong> <em>Where</em> did it go wrong?</li></ol><h3>Enter OpenTelemetry: The Universal Translator</h3><p>In the past, to get traces and metrics, you had to install specific vendor agents (like Datadog, New Relic, or Dynatrace). If you wanted to switch vendors later, you had to rewrite code and change configurations across all your microservices.</p><p><strong>OpenTelemetry</strong> changed the game. It is a vendor-neutral, open-source standard for generating and collecting observability data.</p><p>Think of it as a universal adapter. Your Spring Boot app generates OTel data, and you can point that data to <em>any</em> backend you want — Jaeger, Prometheus, Grafana, or commercial tools — without changing a single line of Java code!</p><h3>Spring Boot 3.x Makes It Ridiculously Easy</h3><p>When Spring Boot 3 was released, it brought a massive shift: native, built-in support for Observability via the Micrometer Tracing library.</p><p>Spring Boot now automatically puts a “GPS tracker” on your requests. It auto-configures tracing for your REST controllers, RestTemplates, WebClients, and even your database calls.</p><h4>How simple is it?</h4><p>You don’t need to write complex Java code to enable this. You just need a couple of dependencies in your pom.xml:</p><pre>&lt;!-- The Micrometer tracing API --&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;io.micrometer&lt;/groupId&gt;<br>    &lt;artifactId&gt;micrometer-tracing-bridge-otel&lt;/artifactId&gt;<br>&lt;/dependency&gt;<br>&lt;!-- The OpenTelemetry exporter (to send data out) --&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;io.opentelemetry&lt;/groupId&gt;<br>    &lt;artifactId&gt;opentelemetry-exporter-otlp&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p>And then, tell your application.yml where to send the data (for example, to a local Jaeger instance for testing):</p><pre>management:<br>  tracing:<br>    sampling:<br>      probability: 1.0 # Send 100% of traces<br>  otlp:<br>    tracing:<br>      endpoint: http://localhost:4318/v1/traces</pre><p><strong>That’s it.</strong> You restart your app, and suddenly, every log statement is automatically tagged with a traceId and spanId. You can visualize exactly how long a database query took, which external API is slowing down your app, and exactly where an exception was thrown.</p><h3>Why is this the only stack you need?</h3><ol><li><strong>Zero Vendor Lock-in:</strong> Want to switch from a paid tool to an open-source tool to save money? Just change the endpoint URL in your application.yml. The code stays exactly the same.</li><li><strong>Out-of-the-box Magic:</strong> Spring Boot automatically instruments almost everything you care about. You rarely have to write manual spans.</li><li><strong>Unified Context:</strong> Because Spring Boot injects the traceId into your standard logs, you can jump directly from a spike in a metric chart, to the exact distributed trace, to the specific line of log that threw the error.</li></ol><h3>Final Thoughts</h3><p>Upgrading to Spring Boot 3.x and embracing OpenTelemetry feels like putting on a pair of X-ray glasses for your architecture. It turns debugging from a stressful, guessing-game chore into a quick, visual process.</p><p>If you are starting a new project in 2026, or migrating an older Spring Boot app, do yourself a favor: skip the vendor-specific SDKs. Add OpenTelemetry, connect it to your favorite dashboard, and finally get a good night’s sleep.</p><p><em>Have you made the jump to OpenTelemetry yet? What dashboard are you using to visualize your traces? Let’s discuss in the comments!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ceb0fde71ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring AI vs LangChain4j: The Ultimate Guide to Building LLM-Powered Java Apps in 2026]]></title>
            <link>https://medium.com/@mesfandiari77/spring-ai-vs-langchain4j-the-ultimate-guide-to-building-llm-powered-java-apps-in-2026-c5a24dd0a04f?source=rss-6ba4fd8fc2d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5a24dd0a04f</guid>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[MEsfandiari]]></dc:creator>
            <pubDate>Wed, 13 May 2026 05:28:44 GMT</pubDate>
            <atom:updated>2026-05-13T05:28:44.214Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UFuquYJMKSfNpr9p3P3EZA.png" /></figure><p>Let’s be honest: for the past couple of years, watching the AI boom felt a bit lonely for Java developers. While our Python colleagues were having a blast throwing together LLM wrappers in ten lines of code, we were left wondering if we had to abandon our beloved JVM to join the AI revolution.</p><p>Fast forward to 2026, and the landscape has completely changed. You no longer need to learn Python to build cutting-edge, LLM-powered applications. The Java ecosystem has responded, and two heavyweights have emerged as the absolute best ways to bring AI into the enterprise: <strong>Spring AI</strong> and <strong>LangChain4j</strong>.</p><p>But which one should you choose for your next project? Let’s break it down so you can stop guessing and start building.</p><h3>The Contenders at a Glance</h3><p>Before we dive deep, here is the short version of what we are dealing with:</p><ul><li><strong>Spring AI:</strong> The “Spring Way” of doing AI. If you dream in @Autowired and love Spring Boot’s auto-configuration, this framework is built specifically for you.</li><li><strong>LangChain4j:</strong> The Java port of the wildly popular LangChain framework. It is modular, highly flexible, and doesn’t care if you use Spring, Quarkus, or plain old Java.</li></ul><p>Let’s look at how they stack up against each other.</p><h3>1. Spring AI: The Comfortable Enterprise Choice</h3><p>Spring AI was created with a clear mission: make integrating AI as easy as adding a database or a message broker to a Spring Boot app. It abstracts away the complex REST APIs of OpenAI, Anthropic, or local models, giving you clean, predictable Java interfaces.</p><h4>What makes it great?</h4><ul><li><strong>Zero Learning Curve (Almost):</strong> It uses the exact same design patterns you already know. JdbcTemplate? Meet ChatClient.</li><li><strong>Seamless Spring Boot Integration:</strong> Just add the starter dependency, drop your API key in application.yml, and you are ready to go.</li><li><strong>Enterprise-Grade Observability:</strong> Built-in integration with Micrometer and OpenTelemetry.</li></ul><h4>A Quick Look at the Code:</h4><p>Here is how simple it is to generate text using Spring AI:</p><pre>@RestController<br>public class AiController {<br><br>    private final ChatClient chatClient;<br><br>    public AiController(ChatClient.Builder builder) {<br>        this.chatClient = builder.build();<br>    }<br><br>    @GetMapping(&quot;/joke&quot;)<br>    public String tellJoke() {<br>        return chatClient.prompt()<br>                .user(&quot;Tell me a joke about Java developers&quot;)<br>                .call()<br>                .content();<br>    }<br>}</pre><p><em>Notice how clean that is? No manual HTTP requests, no JSON parsing. Just pure Spring goodness.</em></p><h3>2. LangChain4j: The Flexible Powerhouse</h3><p>If Spring AI is a luxurious automatic car, LangChain4j is a manual sports car. It gives you incredible control and offers a vast array of integrations out of the box. Because it started as a direct conceptual port of Python’s LangChain, it adopted a highly modular architecture from day one.</p><h4>What makes it great?</h4><ul><li><strong>Framework Agnostic:</strong> You can use it in Spring Boot, but also in Quarkus, Micronaut, or even Android.</li><li><strong>Declarative AI Services:</strong> This is LangChain4j’s killer feature. You can define an interface, annotate it, and the framework dynamically generates the implementation.</li><li><strong>Massive Integration Ecosystem:</strong> It usually gets support for new Vector Databases and LLM providers slightly faster than Spring AI.</li></ul><h4>A Quick Look at the Code:</h4><p>Check out LangChain4j’s “AI Services” feature. It feels like Spring Data JPA, but for AI:</p><pre>public interface Assistant {<br>    @SystemMessage(&quot;You are a polite, helpful customer support agent.&quot;)<br>    String chat(String userMessage);<br>}<br><br>// Usage:<br>Assistant assistant = AiServices.builder(Assistant.class)<br>    .chatLanguageModel(OpenAiChatModel.withApiKey(&quot;your-key&quot;))<br>    .build();<br><br>String response = assistant.chat(&quot;How do I reset my password?&quot;);</pre><p><em>You define the interface, the framework handles the prompt engineering and API calls. Pure magic.</em></p><h3>The Verdict: Which One Should You Choose?</h3><p>Both frameworks are mature, production-ready, and capable of building complex systems like RAG (Retrieval-Augmented Generation) pipelines and autonomous agents.</p><p>Here is my cheat sheet for choosing:</p><p><strong>Choose Spring AI if:</strong></p><ol><li>Your entire stack is already built on Spring Boot.</li><li>You prefer official Spring-supported libraries for better long-term compatibility and security updates.</li><li>You want out-of-the-box observability and metrics integrated with your existing Spring actuators.</li></ol><p><strong>Choose LangChain4j if:</strong></p><ol><li>You are using a non-Spring framework (Quarkus, Micronaut) or plain Java.</li><li>You love the declarative @SystemMessage interface approach.</li><li>You need to integrate with a very specific, niche Vector Database or newly released LLM that Spring AI doesn’t support yet.</li></ol><h3>Final Thoughts</h3><p>The days of needing Python to build serious AI applications are over. Whether you choose the warm, familiar embrace of Spring AI or the flexible, feature-rich power of LangChain4j, you are well-equipped to bring state-of-the-art LLM capabilities to your Java applications in 2026.</p><p><em>Which framework are you leaning towards for your next project?</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5a24dd0a04f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The End of RestTemplate: Spring RestClient vs. WebClient vs. Retrofit in 2026]]></title>
            <link>https://medium.com/@mesfandiari77/the-end-of-resttemplate-spring-restclient-vs-webclient-vs-retrofit-in-2026-0ca96c463544?source=rss-6ba4fd8fc2d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/0ca96c463544</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[MEsfandiari]]></dc:creator>
            <pubDate>Mon, 02 Mar 2026 09:16:00 GMT</pubDate>
            <atom:updated>2026-03-02T09:16:00.628Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*yRmjyGm5wTE4Mcm_D4KiFg.png" /></figure><h3>Stop using deprecated code. Here is the modern way to consume APIs in Spring Boot 3.x.</h3><p>Raise your hand if you still copy-paste RestTemplate configurations from StackOverflow into your Spring Boot projects. 🙋‍♂️</p><p>We’ve all been there. For over a decade, RestTemplate was the trusty hammer in our toolbox. It was blocking, it was verbose, and frankly, it was a bit ugly—but it worked.</p><p>Then came the “Reactive Era.” Everyone shouted, “Use WebClient! It’s non-blocking! It’s the future!” So, we started dragging the entire Netty and Project Reactor dependency tree into our simple CRUD applications just to make a GET request.</p><p>But here we are in 2026. RestTemplate is effectively in maintenance mode. WebClient feels like overkill for synchronous apps. And external libraries like <strong>Retrofit</strong> are cool, but do we really need another dependency?</p><p>The answer lies in the new standard: <strong>Spring RestClient</strong>.</p><p>Let’s break down the battle of the HTTP clients and see why one is the clear winner for 90% of developers today.</p><h3>1. The Dinosaur: RestTemplate</h3><p>Let’s pay our respects. RestTemplate built the Spring ecosystem. But if you look at the JavaDoc today, it screams “Please stop using me.”</p><p><strong>The Problem in 2026:</strong></p><ul><li>It’s API Heavy: exchange(), getForObject(), postForEntity()… the method signatures are clunky.</li><li>No Fluent API: You can’t chain methods. Configuration (timeouts, headers) is often a global mess inside a @Bean.</li><li>Maintenance Mode: The Spring team has been clear: no new features. It’s on life support.</li></ul><p><strong>Verdict:</strong> Legacy code only. Do not use for greenfield projects.</p><h3>2. The Overkill: WebClient</h3><p>When Spring 5 came out, WebClient was pitched as the successor. It has a beautiful, fluent API.</p><pre>// It looks pretty...<br>webClient.get()<br>    .uri(&quot;/users&quot;)<br>    .retrieve()<br>    .bodyToMono(User.class)<br>    .block(); // &lt;-- The crime scene</pre><p><strong>The Catch:</strong> WebClient is built for <strong>Reactive Programming (Spring WebFlux)</strong>. If you are building a standard Spring MVC app (running on Tomcat/Jetty with Virtual Threads), using WebClient forces you to import the reactive stack.</p><p>You are essentially bringing a Ferrari engine (Netty + Reactor) to drive to the grocery store. Plus, if you call .block() at the end of every request, you are defeating the purpose of reactive streams anyway.</p><p><strong>Verdict:</strong> Use ONLY if your tech stack is fully Reactive (WebFlux).</p><h3>3. The Hipster Choice: Retrofit</h3><p>Android developers love Square’s Retrofit, and many backend devs brought it to Spring. It uses interfaces and annotations to define clients. It’s clean, type-safe, and elegant.</p><p><strong>The Problem:</strong> It’s not native to Spring. You have to configure the converters, the okHttp client, and wire it up manually. It works, but it feels like a guest in your Spring Boot house.</p><h3>4. The 2026 Champion: Spring RestClient</h3><p>Introduced quietly in Spring Boot 3.2 and matured by 2026, <strong>RestClient</strong> is the Goldilocks solution we’ve been waiting for.</p><p>It gives you the <strong>Fluent API</strong> of WebClient, but it runs on the <strong>Synchronous Servlet Stack</strong> (like RestTemplate). It uses the HTTP client you already have (Jetty, JDK Client, Apache).</p><h3>Why it wins:</h3><ol><li>Zero Reactive Overhead: No Mono, no Flux, no Netty. Just plain Java Objects.</li><li>Fluent &amp; Readable: Chaining requests makes sense.</li><li>Virtual Thread Ready: It plays perfectly with Java 21+ Virtual Threads for high concurrency without the complexity of reactive code.</li></ol><h3>The Code Transformation</h3><p><strong>The Old Way (RestTemplate):</strong></p><pre>HttpHeaders headers = new HttpHeaders();<br>headers.setContentType(MediaType.APPLICATION_JSON);<br>HttpEntity&lt;String&gt; entity = new HttpEntity&lt;&gt;(requestJson, headers);<br><br>ResponseEntity&lt;User&gt; response = restTemplate.exchange(<br>    &quot;https://api.example.com/users/1&quot;, <br>    HttpMethod.GET, <br>    entity, <br>    User.class<br>);</pre><p><strong>The Modern Way (RestClient):</strong></p><pre>User user = restClient.get()<br>    .uri(&quot;https://api.example.com/users/1&quot;)<br>    .accept(MediaType.APPLICATION_JSON)<br>    .retrieve()<br>    .body(User.class);</pre><p>Clean. Simple. No .block().</p><h3>Bonus: The “Declarative Client” (The Retrofit Killer)</h3><p>This is the feature that truly ends the debate. In 2026, Spring allows you to define HTTP clients as <strong>Interfaces</strong>, just like Spring Data Repositories or Retrofit.</p><p>You define an interface:</p><pre>import org.springframework.web.service.annotation.GetExchange;<br><br>public interface UserClient {<br>    @GetExchange(&quot;/users/{id}&quot;)<br>    User getUser(@PathVariable(&quot;id&quot;) Long id);<br>}</pre><p>And you inject it:</p><pre>@Configuration<br>class ClientConfig {<br>    @Bean<br>    UserClient userClient(RestClient.Builder builder) {<br>        RestClient client = builder.baseUrl(&quot;https://api.example.com&quot;).build();<br>        return HttpServiceProxyFactory<br>            .builderFor(RestClientAdapter.create(client))<br>            .build()<br>            .createClient(UserClient.class);<br>    }<br>}</pre><p>Now, in your Service layer, you just call userClient.getUser(1). It’s pure magic.</p><h3>Final Thoughts</h3><p>The era of debating HTTP clients is over.</p><ol><li>Refactoring legacy code? Move from RestTemplate to RestClient to clean up the syntax.</li><li>Starting a new Microservice? Use Declarative Clients backed by RestClient.</li><li>Building a Reactive System? Stick with WebClient.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0ca96c463544" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>