<?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 Olayiwola Akinnagbe on Medium]]></title>
        <description><![CDATA[Stories by Olayiwola Akinnagbe on Medium]]></description>
        <link>https://medium.com/@olayiwola72?source=rss-2bf0b686476e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*aPKn15IrMLxXShpW1YQmkA.jpeg</url>
            <title>Stories by Olayiwola Akinnagbe on Medium</title>
            <link>https://medium.com/@olayiwola72?source=rss-2bf0b686476e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 17:28:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@olayiwola72/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[Why You Can’t Sort a HashMap (And What to Do Instead)]]></title>
            <link>https://blog.stackademic.com/why-you-cant-sort-a-hashmap-and-what-to-do-instead-08194a42da07?source=rss-2bf0b686476e------2</link>
            <guid isPermaLink="false">https://medium.com/p/08194a42da07</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[collection]]></category>
            <category><![CDATA[sorting-algorithms]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Olayiwola Akinnagbe]]></dc:creator>
            <pubDate>Tue, 09 Jun 2026 12:52:50 GMT</pubDate>
            <atom:updated>2026-06-09T12:52:50.880Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>A junior engineer’s mistake taught me something I wish I had been told earlier.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XEeETHZe3DuLP30pSFW5WQ.png" /></figure><p>Earlier this week, I was mentoring a couple of junior engineers when I gave one of them a small challenge: sort a <em>HashMap</em> by its values.</p><p>He thought about it, typed confidently, and submitted this:</p><pre>Map&lt;Character, Integer&gt; map = new HashMap&lt;&gt;();<br>map.put(&#39;c&#39;, 3);<br>map.put(&#39;a&#39;, 5);<br>map.put(&#39;b&#39;, 4);<br>map.put(&#39;d&#39;, 2);<br>map.put(&#39;e&#39;, 1);<br><br>Comparator&lt;Map.Entry&lt;Character, Integer&gt;&gt; comparator =<br>    Comparator.comparingInt(Map.Entry::getValue);<br><br>Collections.sort(map, comparator);</pre><p>It did not compile. The error:</p><pre>no instance(s) of type variable(s) T exist so that<br>Map&lt;String, Integer&gt; conforms to List&lt;T&gt;</pre><p>It was a good attempt. Thoughtful, even. But it reveals a misconception that I suspect a lot of developers carry quietly, including some who have been writing Java for years.</p><h3>The Root Problem: A Map Is Not a List</h3><p><strong><em>Collections.sort() </em></strong>only works on lists. A <strong>Map</strong> is not a sequence. It is a key-value structure — and it has no concept of order in the way a <strong>List</strong> does.</p><p>So you cannot sort a <strong>Map</strong> directly. You have to:</p><ol><li>Extract a list of entries from the map</li><li>Sort that list</li><li>Build a new map from the sorted result</li></ol><p>Let us do exactly that.</p><h3>Step-by-Step: Sorting by Value</h3><pre>// Step 1: Get a list of entries<br>List&lt;Map.Entry&lt;Character, Integer&gt;&gt; entryList = new ArrayList&lt;&gt;(map.entrySet());<br><br>// Step 2: Define a comparator (the same one from before — still valid)<br>Comparator&lt;Map.Entry&lt;Character, Integer&gt;&gt; comparator =<br>    Comparator.comparingInt(Map.Entry::getValue);<br><br>// Step 3: Sort the entry list<br>entryList.sort(comparator);<br><br>// Step 4: Build a new map, preserving insertion order<br>Map&lt;Character, Integer&gt; sortedMap = new LinkedHashMap&lt;&gt;();<br>for (Map.Entry&lt;Character, Integer&gt; entry : entryList) {<br>    sortedMap.put(entry.getKey(), entry.getValue());<br>}</pre><h4><strong>Output:</strong></h4><p>Before sorting: {a=5, e=1, d=2, c=3, b=4}</p><p>After sorting by value: {e=1, d=2, c=3, b=4, a=5}</p><p><strong>One thing to flag</strong>: I switched from <strong>HashMap</strong> to <strong>LinkedHashMap</strong> for the result. This is intentional. <strong>LinkedHashMap</strong> preserves insertion order, so after sorting and inserting, the entries stay in the order you put them in. A regular <strong>HashMap</strong> would shuffle everything again and we don’t want that.</p><p>If you just need to print the result and do not need a new map, you can skip the <strong>LinkedHashMap</strong> entirely:</p><pre>for (Map.Entry&lt;Character, Integer&gt; entry : entryList) {<br>  System.out.println(entry.getKey() + &quot; &quot; + entry.getValue());<br>}</pre><p>And if the task is to sort by <strong>key</strong> instead of value, you only need to swap the comparator:</p><pre>Comparator&lt;Map.Entry&lt;Character, Integer&gt;&gt; comparator = <br>Comparator.comparing(Map.Entry::getKey);</pre><p>Everything else stays the same.</p><h3>The TreeMap Trap</h3><p>Here is where a lot of engineers get tripped up, sometimes even senior ones.</p><p>You might think: <em>”Wait, doesn’t </em><strong><em>TreeMap</em></strong><em> already give me a sorted map?”</em></p><pre>Map&lt;Character, Integer&gt; sortedTreeMap = new TreeMap&lt;&gt;(map);<br>System.out.println(sortedTreeMap);</pre><h4><strong>Output:</strong></h4><p>{a=5, b=4, c=3, d=2, e=1}</p><p>That looks sorted. But look carefully. It sorted by <strong>key</strong> — alphabetically — not by <strong>value</strong>. It only appears to sort by value here because our values happen to decrease as the keys go from “a” to “e”. That is a coincidence, not a feature.</p><p><strong>TreeMap</strong> sorts by <strong>keys</strong>, always. That is its design.</p><h3>Can TreeMap Sort by Value?</h3><p>Astute readers are asking, can TreeMap sort by value? Technically yes. But it is awkward enough that I would not recommend it in production code:</p><pre>Comparator&lt;Character&gt; valueComparator = (k1, k2) -&gt; {<br>  int compare = map.get(k1).compareTo(map.get(k2));<br>  if (compare == 0) {<br>      return k1.compareTo(k2); // tiebreak by key<br>  }<br>  return compare;<br>};<br><br>Map&lt;Character, Integer&gt; sortedByValue = new TreeMap&lt;&gt;(valueComparator);<br>sortedByValue.putAll(map);</pre><p>In summary, the table below summarizes the main important points that we have discussed in this section</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Aa_3PO3m69bcAm8bmjPtMA.png" /></figure><p>Now that we are done here, let us look at a more cleaner and elegant way to approach this</p><h3>The Clean Way: Java 8 Streams</h3><p>In my experience, this looks like a lot of hassle just to sort a Map, and once you understand the Stream API, this is the approach you will reach for every time.</p><pre>Map&lt;Character, Integer&gt; sortedByValue = map.entrySet()<br>  .stream()<br>  .sorted(Map.Entry.comparingByValue())<br>  .collect(Collectors.toMap(<br>    e -&gt; e.getKey(),<br>    e -&gt; e.getValue(),<br>    (e1, e2) -&gt; e1, // merge function (handles duplicate keys)<br>    LinkedHashMap::new // preserve insertion order<br>  )<br>);</pre><p>Now this feels hard to understand with Method References here and there, especially when you are not so familiar with it. Let us write an equivalent without method references and further explain the reasoning behind them.</p><pre>Map&lt;Character, Integer&gt; sortedByValue = map.entrySet()<br>   .stream()<br>   .sorted((entry1, entry2) -&gt;    entry1.getValue().compareTo(entry2.getValue()))<br>   .collect(<br>      () -&gt; new LinkedHashMap&lt;&gt;(),                     // Supplier<br>      (m, e) -&gt; m.put(e.getKey(), e.getValue()),     // Accumulator<br>      (m1, m2) -&gt; m1.putAll(m2)                            // Combiner<br>    );<br>}</pre><h4>Reasoning behind this</h4><ul><li>() -&gt; new LinkedHashMap&lt;&gt;(): creates a new LinkedHashMap (same as LinkedHashMap::new)</li><li>(m, e) -&gt; m.put(e.getKey(), e.getValue(): adds each entry to the map (same as before)</li><li>(m1, m2) -&gt; m1.putAll(m2: merges partial results when parallel streams are used (same as LinkedHashMap::putAll)</li></ul><h4>Full working example</h4><pre>import java.util.*;<br>import java.util.stream.*;<br><br>public<br>class Main {<br> public<br>  static void main(String[] args) {<br>    Map&lt;Character, Integer&gt; map = new HashMap&lt;&gt;();<br>    map.put(&#39;c&#39;, 3);<br>    map.put(&#39;a&#39;, 5);<br>    map.put(&#39;b&#39;, 4);<br>    map.put(&#39;d&#39;, 2);<br>    map.put(&#39;e&#39;, 1);<br><br>    Map&lt;Character, Integer&gt; sortedByValue = map.entrySet()<br>            .stream()<br>            .sorted((entry1, entry2) -&gt; entry1.getValue()<br>                      .compareTo(entry2.getValue())<br>            )<br>            .collect(<br>                () -&gt; new LinkedHashMap&lt;&gt;(),<br>                (m, e) -&gt; m.put(e.getKey(), e.getValue()),<br>                (m1, m2 )-&gt; m1.putAll(m2)<br>            );<br><br>    System.out.println(sortedByValue);<br>  }<br>}</pre><p>There are variations to these, in most places Collectors.toMap() is used, this is because it feels easier to read to most developers. The above manual .collect(...) form is equivalent to:</p><pre>Map&lt;Character, Integer&gt; sortedByValue = map.entrySet()<br>        .stream()<br>        .sorted(Map.Entry.comparingByValue())<br>        .collect(Collectors.toMap(<br>              e -&gt; e.getKey(),<br>              e -&gt; e.getValue(),<br>              (e1, e2) -&gt; e1, // merge function (in case of duplicate keys)<br>              LinkedHashMap::new // use LinkedHashMap to preserve order<br>            )<br>        );</pre><p>This version uses:</p><ul><li>key mapper → e -&gt; e.getKey()</li><li>value mapper → e -&gt; e.getValue()</li><li>merge function → (e1, e2) -&gt; e1</li><li>map supplier → LinkedHashMap::new</li></ul><p>It’s more readable to most developers.</p><p>I don’t want to make this a long read, but you might be wondering why we use the terms <em>Supplier</em>, <em>Accumulator</em>, or <em>Combiner</em>.</p><p>Remember the mental model we discussed at the beginning: you take a list of entries, sort it, and then build a new map. These three functional interfaces are exactly what help us achieve that workflow with minimal code, by clearly separating each step of the process.</p><h3>Going Deeper: What Is “.collect()” Actually Doing?</h3><p>Here is where I want to slow down because this is the part most tutorials skip.</p><p>When I showed this stream version to my junior engineers, one of them asked: <em>”What is that three-argument </em><strong><em>.collect()</em></strong><em> doing? I’ve seen </em><strong><em>Collectors.toList()</em></strong><em> before, but not this.”</em></p><p>That is exactly the right question.</p><p><strong>“.collect()”</strong> is a <strong>terminal operation</strong> on a stream. It gathers the stream’s elements into a container, which could be a list, a set, or, in our case, a map.</p><p>There are two main ways to use it:</p><h4><strong>Option A: A prebuilt collector</strong></h4><pre>.collect(Collectors.toList())<br>.collect(Collectors.toSet())<br>.collect(Collectors.toMap(…))</pre><h4><strong>Option B: The three-argument form, written manually</strong></h4><pre>&lt;R&gt; R collect(<br>  Supplier&lt;R&gt; supplier,<br>  BiConsumer&lt;R, ? super T&gt; accumulator,<br>  BiConsumer&lt;R, R&gt; combiner<br>)</pre><p>Understanding the three-argument form is what separates someone who uses Streams from someone who <strong><em>understands</em></strong> them.</p><h3>The Three Arguments, Explained</h3><p>Think of it like this diagram:</p><figure><img alt="Java Stream Collector Flow" src="https://cdn-images-1.medium.com/max/1024/1*78HOna5FbskVwN8UqFmoqg.png" /><figcaption>Java Stream Collector Flow</figcaption></figure><h3><strong>1. Supplier: () -&gt; new LinkedHashMap&lt;&gt;()</strong></h3><p>The Supplier tells Java <em>*how to create*</em> the result container. It runs once at the start of collection.</p><pre>() -&gt; new LinkedHashMap&lt;&gt;()</pre><p>In verbose form:</p><pre>new Supplier&lt;LinkedHashMap&lt;Character, Integer&gt;&gt;() {<br>  @Override<br>    public LinkedHashMap&lt;Character, Integer&gt; get() {  <br>    return new LinkedHashMap&lt;&gt;();<br>  }<br>}</pre><p>In plain English: “<em>When collecting starts, give me a new empty LinkedHashMap.”</em></p><p><strong>2. Accumulator: (m, e) -&gt; m.put(e.getKey(), e.getValue())</strong></p><p>The Accumulator tells Java “<strong><em>how to add one element”</em> </strong>from the stream into the container.</p><pre>(m, e) -&gt; m.put(e.getKey(), e.getValue())</pre><p>In verbose form:</p><pre>new BiConsumer&lt;Map&lt;Character, Integer&gt;, Map.Entry&lt;Character, Integer&gt;&gt;() {<br>  @Override<br>  public void accept(Map&lt;Character, Integer&gt; m, Map.Entry&lt;Character, Integer&gt; e) {<br>    m.put(e.getKey(), e.getValue());<br>  }<br>}</pre><p>In plain English: “<em>For each entry in the stream, take its key and value and put them into the map.”</em></p><h3><strong>3. Combiner: (m1, m2) -&gt; m1.putAll(m2)</strong></h3><p>The Combiner is only relevant when the stream runs in <strong>parallel</strong>. It merges two partially filled containers into one.</p><p>In a sequential stream, which is what we are using here, the Combiner never actually runs. But it must still be provided; the API requires it.</p><pre>(m1, m2) -&gt; m1.putAll(m2)</pre><p>In plain English: “<em>If two chefs each filled half a container, combine them into one.”</em></p><h3>Why Collectors.toMap() Feels Simpler</h3><p>Because under the hood, <strong>Collectors.toMap()</strong> is doing exactly this — building a Supplier, Accumulator, and Combiner internally. It just hides the wiring from you.</p><p>When you write <strong>Collectors.toMap()</strong>, you are using a higher-level abstraction over the same three parts.</p><h3>The Cooking Analogy</h3><p>If you are a visual thinker, here is how I think about it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mmrBJu2-ESN7_iPC9TbcLA.png" /></figure><p>Java Streams are powerful. But like a professional kitchen, they have rules. If you do not understand where the bowl comes from, how the ingredients go in, and what happens when multiple chefs are working, you will occasionally produce something unexpected.</p><p>Now you know exactly how the kitchen works.</p><h3>The Big Lesson: Sorting Is Only Half the Job</h3><p>Here is the insight I want you to leave with.</p><p>When you sort a stream, the sorting happens <strong><em>in the stream pipeline</em></strong>. The moment you collect those sorted elements into a container that does not preserve order, the sort is lost.</p><p>Think of it this way:</p><p>You carefully line up cupcakes in perfect order. Then you tip them into a random box. That is <strong>HashMap</strong>.</p><p><strong>LinkedHashMap</strong> is the serving tray that keeps them aligned.</p><p>Every time you sort a stream and collect the result, ask yourself: <em>Is my container preserving the order I just worked for?</em></p><h3>Closing Thought</h3><p>My junior engineer did not get the answer right on his first try. But he asked, the right follow-up questions and that is what matters most.</p><p>Understanding <strong><em>why</em></strong> “Collections.sort(map, comparator)” does not compile is not just a Java trivia fact. It is a window into how the collections framework thinks about structure, order, and mutability.</p><p>Once you see it clearly, you stop fighting the API and start working with it.</p><p>And the next time your sorted ma, mysteriously unsorts itself — you will know exactly which container to blame.</p><p><em>If you found this useful, you might also enjoy my deep dive on Java memory management: </em><a href="https://medium.com/stackademic/memory-is-a-budget-understanding-strong-soft-weak-and-phantom-references-in-java-14e8768916be"><em>Memory Is a Budget: Understanding Strong, Soft, Weak, and Phantom References in Java</em></a><em>.</em></p><p>I started writing because a mentor once took the time to explain something clearly, and it changed how I thought.</p><p>If this article did even a small version of that for you, here is how you can help it reach the next person:</p><p>👉 Share it with one engineer who would find it useful.</p><p>👏 Hold down the clap button — 50 claps helps Medium show it to more readers.</p><p>💬 Leave a comment. Questions, pushback, war stories — all welcome.</p><p>🔔 <a href="https://medium.com/@olayiwola72">Follow me on Medium</a> if you want more of this.</p><p>Good ideas spread when people pass them along. I genuinely appreciate it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=08194a42da07" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/why-you-cant-sort-a-hashmap-and-what-to-do-instead-08194a42da07">Why You Can’t Sort a HashMap (And What to Do Instead)</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[State vs Strategy Pattern in Fintech: Designing Payment Systems That Scale with Compliance and Risk]]></title>
            <link>https://blog.stackademic.com/state-vs-strategy-pattern-in-fintech-designing-payment-systems-that-scale-with-compliance-and-risk-98ad0a58f6c2?source=rss-2bf0b686476e------2</link>
            <guid isPermaLink="false">https://medium.com/p/98ad0a58f6c2</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[fintech]]></category>
            <dc:creator><![CDATA[Olayiwola Akinnagbe]]></dc:creator>
            <pubDate>Thu, 30 Apr 2026 22:27:35 GMT</pubDate>
            <atom:updated>2026-04-30T22:27:35.656Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to model payment lifecycles as state machines while keeping fraud detection, pricing, and routing logic flexible with the Strategy pattern.</h3><h3>Introduction: The Subtle Complexity of Moving Money</h3><p>State and Strategy are two behavioral design patterns from the Gang of Four. When applied together correctly, they enable high cohesion, low coupling, maintianable and scalable architecture. This becomes especially relevant when integrating with third-party payment gateways.</p><p>Payment lifecycles behave like state machines. One moment, you submit a payment intent with <em>status=Initiated </em>to an external payment service provider such as Stripe. Moments later, a webhook callback arrives carrying a new status: <em>success</em>, <em>failure</em>, or <em>pending_settlement</em>.</p><p>But designing payment systems is more than handling API callbacks.</p><p>Transfer channels operate differently. Some provide synchronous settlement, where the sender is debited and the receiver credited in the same request. Others rely on asynchronous backbones, paired with push-based webhooks for accurate status tracking and settlement confirmation.</p><p>Money does not simply move. It transitions through clearly defined states, governed by strict financial rules.</p><p>In a fintech system, a single transaction can travel through all of the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sCRRXumLg0KESZS8jPWcFw.png" /><figcaption>Figure 1: Transaction lifecycle flowchart diagram</figcaption></figure><ul><li>Initiated — The transaction has been created and submitted to the payment service provider (PSP), but processing has not yet begun.<br>• Pending — The payment is being processed. The system is waiting for confirmation from the bank, card network, or external provider.<br>• Authorized — Funds have been reserved on the customer’s account but not yet captured or transferred.<br>• Failed — The transaction could not be completed due to insufficient funds, fraud rejection, network errors, or validation failure.<br>• Settled — Funds have been successfully captured and transferred to the merchant’s account.<br>• Reversed — An authorized or pending transaction has been cancelled before settlement; held funds are released.<br>• Refunded — A settled transaction has been partially or fully returned to the customer.</li></ul><p>Each state represents more than a label. It represents financial truth.</p><h3>Synchronous Flow: A Simpler State Journey</h3><p>Consider what happens in a synchronous payment flow:</p><p>• An API request is made to a payment gateway.<br>• Validations are performed (balance check, fraud detection, restrictions).<br>• The sender is debited and the receiver is credited instantly.<br>• In failure scenarios, the API returns an error (e.g., 400 Bad Request — insufficient funds, restrictions, etc.).</p><p>In this flow, a transaction might only pass through Authorized or Failed. States like Initiated, Pending, or Settled may not surface explicitly at all, e.g., direct debit, or some wallet-to-wallet money transfers.</p><p>Even in simpler flows, transitions must be traceable, auditable, and deterministic.</p><p>But here is where things get interesting. While the transaction lifecycle follows a clear progression of states, the rules applied during that lifecycle, including fraud detection, retry policies, routing logic, and pricing models, often need to evolve independently.</p><p>This is where many fintech systems become unnecessarily rigid. Integrations get tightly coupled to a specific payment gateway. In short, engineers confuse State with Strategy. Consequently, the codebase fills with bloated classes, hard-to-test logic, and fragile compliance flows.</p><h3>1. Where the State Pattern Naturally Fits in Fintech</h3><p>The State pattern models systems where behaviour changes because the internal state changes.</p><p>That is exactly how payment lifecycles work. A transaction behaves differently depending on where it sits in the lifecycle:</p><p>• Pending — you can cancel it<br>• Authorized — you can capture it<br>• Settled — you can refund it<br>• Reversed — no further action is permitted or allowed</p><p>This is not algorithm swapping. This is lifecycle control.</p><h3>Example: Payment Lifecycle in Code</h3><pre>interface PaymentState {<br>    void handle(PaymentContext context);<br>}<br><br>class AuthorizedState implements PaymentState {<br>    public void handle(PaymentContext context) {<br>        context.captureFunds();<br>        context.setState(new SettledState());<br>    }<br>}</pre><p>Notice what is happening here:</p><p>• The behaviour changes because the state changes.<br>• The object delegates logic to its current state.<br>• Transitions are explicit and controlled.</p><p>This model fits naturally in:</p><p>• Payment lifecycle management<br>• Loan approval progression<br>• KYC verification stages<br>• Subscription status changes</p><p>In fintech, lifecycle modelling is rarely optional. It is compliance-critical.</p><h3>2. Where Strategy Belongs: Risk, Pricing, and Adaptive Logic</h3><p>Now consider something different. Suppose you are implementing fraud detection logic. Today, you might use rule-based scoring. Tomorrow, you may switch to an ML model or a third-party API. The day after, a regulator mandates a new risk threshold.</p><p>This is not a state transition problem. It is algorithm substitution. And this is where the Strategy pattern excels.</p><pre>interface FraudStrategy {<br>    boolean evaluate(Transaction tx);<br>}<br><br>class RuleBasedFraudStrategy implements FraudStrategy {<br>    public boolean evaluate(Transaction tx) {<br>        return tx.amount() &gt; 10000;<br>    }<br>}<br>class MachineLearningFraudStrategy implements FraudStrategy {<br>    public boolean evaluate(Transaction tx) {<br>        return mlModel.predict(tx) &gt; 0.85;<br>    }<br>}</pre><p>The transaction state remains the same. What changes is how we evaluate it.</p><p>Strategy is the right tool for:</p><p>• Fraud detection engines<br>• Pricing models<br>• Retry policies<br>• Routing decisions<br>• Currency conversion strategies<br>• Settlement optimization</p><p>The behaviour changes because you inject a different strategy, not because the object moved to a new lifecycle phase.</p><h3>3. The Architectural Mistake Many Fintech Systems Make</h3><p>Over the course of my career, I have seen a common mistake:</p><p>Engineers embed fraud logic inside state classes.</p><p>Or worse, they encode lifecycle transitions inside strategy implementations.</p><p>That leads to:</p><p>• Tight coupling between compliance and algorithm logic<br>• Combinatorial explosion of states<br>• Impossible-to-test edge cases<br>• Feature toggles are scattered across the lifecycle code</p><h3>What Not to Do</h3><pre>class AuthorizedState implements PaymentState {<br>    public void handle(PaymentContext context) {<br>        // Fraud logic embedded in a lifecycle state<br>        if (fraudModel.predict(context.tx) &gt; 0.9) {<br>            context.setState(new FlaggedState());<br>        }<br>    }<br>}</pre><p>Fraud logic is now hardcoded into lifecycle transitions. Changing your fraud policy means touching lifecycle control. This violates the Open/Closed Principle from SOLID and that is how technical debt accumulates in financial systems.</p><h3>4. The Correct Separation: Lifecycle vs Policy</h3><p>Think of it this way:</p><p>• State controls progression.<br>• Strategy controls decision-making.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*9GFHCQJ1BNVLR4W7fmscXA.png" /></figure><p>When this separation is enforced correctly:</p><p>• Lifecycle remains deterministic<br>• Policies become swappable<br>• Compliance auditing becomes clearer<br>• Testing becomes modular</p><p>This separation is not aesthetic. It directly impacts regulatory traceability.</p><h3>5. Why This Matters in Real Fintech Systems</h3><p>Fintech systems are mission-critical and operate under intense regulatory scrutiny. At any point, they must support:</p><p>• Audit requirements<br>• Deterministic transaction histories<br>• Regulatory replayability<br>• Risk model versioning<br>• Historical state reconstruction</p><p>When State and Strategy are entangled, the consequences are real:</p><p>• You cannot replay transactions cleanly.<br>• You cannot easily version fraud models.<br>• You risk retroactively altering decision logic already deployed in production.</p><p>In a heavily regulated industry, that is not just dangerous. It is unacceptable.</p><p>Design patterns in fintech are not academic exercises. They are governance mechanisms: engineering tools that guard against what could go wrong in the future.</p><h3>6. A Practical Hybrid Approach</h3><p>In mature fintech architectures, these two patterns work together, not in isolation:</p><p>• State machine controlling lifecycle<br>• Strategy injected into states<br>• Versioned strategy registry<br>• Immutable event logs</p><h3>Example: Coordinated Lifecycle and Policy</h3><pre>class PaymentContext {<br>    private PaymentState state;<br>    private FraudStrategy fraudStrategy;<br><br>    public void process() {<br>        if (!fraudStrategy.evaluate(this.transaction)) {<br>            state.handle(this);<br>        }<br>    }<br>}</pre><p>Lifecycle and policy are decoupled but coordinated. State transitions remain stable. Decision logic stays flexible. Audit trails remain intact.</p><h3>7. Final Insight: Patterns Are Governance Tools</h3><p>Design patterns in fintech are not about elegance. They are about:</p><p>• Risk containment<br>• Regulatory clarity<br>• Operational resilience<br>• System evolvability</p><p>The State pattern protects lifecycle integrity. The Strategy pattern protects policy flexibility.</p><p>Confuse them, and your system becomes rigid. Separate them correctly, and your architecture scales with regulation.</p><h3>Closing Thought</h3><p>In fintech, money must move.</p><p>But what is at stake is people’s trust and their hard-earned savings. Money cannot move arbitrarily. Every decision governing its movement must be predictable, flexible, auditable, and adaptable.</p><p>Let me leave you with two things:</p><p>• The State pattern governs progression. It tells you where a transaction is in its lifecycle.<br>• The Strategy pattern governs intelligence. It tells you how decisions are made at each step.</p><p>Architectural maturity is knowing when to use each and never letting them bleed into one another.</p><p>—</p><p>If you found this useful, you may also enjoy my article on <a href="https://blog.stackademic.com/raft-consensus-explained-visually-leader-election-quorum-and-failure-recovery-in-distributed-c641d9dca2b5">Raft Consensus and failure recovery in distributed systems.</a></p><p><a href="https://blog.stackademic.com/raft-consensus-explained-visually-leader-election-quorum-and-failure-recovery-in-distributed-c641d9dca2b5">Raft Consensus Explained Visually: Leader Election, Quorum, and Failure Recovery in Distributed…</a></p><h3>A message from our Founder</h3><p>Hey, <a href="https://linkedin.com/in/sunilsandhu">Sunil</a> here. I wanted to take a moment to thank you for reading until the end and for being a part of this community. Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? We don’t receive any funding, we do this to support the community.</p><p>If you want to show some love, please take a moment to follow me on <a href="https://linkedin.com/in/sunilsandhu">LinkedIn</a>, <a href="https://tiktok.com/@messyfounder">TikTok</a>, <a href="https://instagram.com/sunilsandhu">Instagram</a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/">weekly newsletter</a>. And before you go, don’t forget to clap and follow the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98ad0a58f6c2" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/state-vs-strategy-pattern-in-fintech-designing-payment-systems-that-scale-with-compliance-and-risk-98ad0a58f6c2">State vs Strategy Pattern in Fintech: Designing Payment Systems That Scale with Compliance and Risk</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rate Limiting Explained with Real Examples: Fixed Window, Sliding Window, Token Bucket & Leaky…]]></title>
            <link>https://blog.stackademic.com/rate-limiting-explained-with-real-examples-fixed-window-sliding-window-token-bucket-leaky-14988de1a05f?source=rss-2bf0b686476e------2</link>
            <guid isPermaLink="false">https://medium.com/p/14988de1a05f</guid>
            <category><![CDATA[rate-limiting]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Olayiwola Akinnagbe]]></dc:creator>
            <pubDate>Wed, 15 Apr 2026 08:24:21 GMT</pubDate>
            <atom:updated>2026-04-15T08:24:21.507Z</atom:updated>
            <content:encoded><![CDATA[<h3>Rate Limiting Explained with Real Examples: Fixed Window, Sliding Window, Token Bucket &amp; Leaky Bucket</h3><p>Why ChatGPT says “You’ve hit the limit”, and what that teaches us about distributed systems</p><h3>Introduction</h3><p>Have you ever been told by ChatGPT on the free plan:</p><p>“You’ve reached your usage limit. Please try again later.”</p><p>It feels like friction. But pause for a moment.</p><p>What you just experienced wasn’t random. It wasn’t arbitrary. It wasn’t a bug.</p><p>In technical terms, it is called rate-limiting, a fundamental distributed systems strategy happening in real time.</p><p>And once I realised that, I couldn’t stop thinking about it.</p><h3>What Problem Is Rate Limiting Really Solving?</h3><p>Imagine you own a small restaurant. Suddenly, 5,000 people show up at once. Even with great chefs, the kitchen collapses.</p><p>Now scale that problem to:</p><p>· APIs</p><p>· AI platforms</p><p>· Payment systems</p><p>· Cloud infrastructure</p><p>Without traffic control, systems don’t degrade gracefully. They crash. Rate limiting is not about restricting users. It’s about protecting the system and ensuring fairness. And that curiosity led me deeper.</p><h3>The Question That Changed How I Studied This</h3><p>Reading about rate limiting wasn’t enough.</p><p>I kept asking:</p><p>· What actually happens during a traffic spike?</p><p>· How do different algorithms behave under stress?</p><p>· Why does one feel “smoother” than another?</p><p>So instead of just reading documentation, I built a simulation.</p><p>But before that, let’s walk through the core algorithms in a way that sticks in the memory.</p><h3>Fixed Window: The Simplest Rule</h3><p>Imagine a security guard counting people entering a building every minute.</p><p>“100 people allowed per minute.” At the 60-second mark, the counter resets. That’s Fixed Window. But here’s the catch. If 100 people enter at 10:00:59 and another 100 at 10:01:00, that’s 200 people in two seconds. This is also referred to as the boundary problem.</p><p>The system technically followed the rule. But the system still gets overwhelmed.</p><p>Overall, Fixed Window is simple but naive under burst conditions.</p><figure><img alt="Diagram showing two adjacent windows and burst at boundary" src="https://cdn-images-1.medium.com/max/902/1*WeFhve5oAvLXoM5hjdsQHQ.png" /><figcaption>Fig 1: Diagram showing two adjacent windows and burst at boundary</figcaption></figure><h3>Sliding Window Log: Precision at a Cost</h3><p>What if instead of resetting every minute, we tracked every person entering?</p><p>Now the guard keeps a log:</p><p>“Count how many entered in the last 60 seconds.”</p><p>While it eliminates the boundary problem, imagine millions of users; every request timestamp becomes expensive in memory.</p><p>Precision matters, but memory cost increases, too. In distributed systems, every gain has a tradeoff.</p><figure><img alt="Timeline diagram showing sliding window movement" src="https://cdn-images-1.medium.com/max/902/1*8VQbea4IU4CNW9XC3luLGQ.png" /><figcaption>Fig 2: Timeline diagram showing sliding window movement</figcaption></figure><h3>Sliding Window Counter: The Optimisation Trick</h3><p>Here’s where engineering gets clever. Instead of storing every request:</p><p>We keep:</p><p>· Count for current window</p><p>· Count for the previous window</p><p>· Weight them based on time overlap</p><p>We approximate and sacrifice tiny accuracy for massive scalability, and this is where system design becomes art.</p><figure><img alt="Two-window interpolation diagram" src="https://cdn-images-1.medium.com/max/902/1*mWznHRYTIQIqhVTXN22rcw.png" /><figcaption>Fig 3: Two-window interpolation diagram</figcaption></figure><h3>Token Bucket: Controlled Bursts</h3><p>Now imagine something different. Instead of counting requests, we give users tokens and refill them at a constant rate.</p><p>Each request consumes one token. If tokens run out, we reject.</p><p>But what if the user was idle? tokens get accumulated.</p><p>Suddenly, they can make a burst of requests. This is why Token Bucket feels “flexible”.</p><p>It allows short spikes without breaking the system. That balance between flexibility and protection is why the token bucket algorithm is widely used in production systems.</p><figure><img alt="Bucket filling with tokens over time" src="https://cdn-images-1.medium.com/max/902/1*6KOyaS4ITz0Qi5WBxdq88Q.png" /><figcaption>Fig 4: Bucket filling with tokens over time</figcaption></figure><h3>Leaky Bucket: Smooth and Strict</h3><p>Now imagine a bucket with a small hole at the bottom. Water flows in randomly, but it leaks out at a constant rate. No sudden bursts or spikes, just gradual flow.</p><p>Leaky bucket guarantees steady processing, but sacrifices flexibility. Some systems prefer smoothness over burst tolerance. Again, we are dealing with trade-offs.</p><figure><img alt="Leaky bucket with constant drain rate" src="https://cdn-images-1.medium.com/max/902/1*vP3bRuPkt02Q5UcsmmEohg.png" /><figcaption>Fig 5: Leaky bucket with constant drain rate</figcaption></figure><h3>Where It Gets Interesting — Distributed State</h3><p>Now, astute readers will ask, how does this scale?</p><p>What happens when you have 10 servers?</p><p>Where is the counter stored?</p><p>How do you synchronise tokens?</p><p>Now, rate limiting becomes:</p><p>· A distributed state problem</p><p>· A consistency problem</p><p>· A fault tolerance problem</p><p>This is no longer an algorithm exercise. This is distributed systems engineering. In future, we will discuss more on how to persist this data. This write-up is meant to explain rate-limiting algorithms and their trade-offs.</p><h3>So I Built It</h3><p>Curiosity turned into code, so I built an interactive in-memory simulation where you can:</p><p>· Trigger burst traffic</p><p>· Compare algorithms side-by-side</p><p>· Observe fairness under load</p><p>· See acceptance vs rejection patterns</p><p>Live demo: <a href="https://rate-limiting-simulations.netlify.app/">https://rate-limiting-simulations.netlify.app/</a></p><figure><img alt="Rate Limiting Explained with Real Examples: Fixed Window, Sliding Window, Token Bucket &amp; Leaky Bucket" src="https://cdn-images-1.medium.com/max/800/1*dnfvhUC2rvgwlz29zqI3vw.gif" /></figure><p>GitHub: <a href="https://github.com/Olayiwola72/rate-limiting-simulations/">https://github.com/Olayiwola72/rate-limiting-simulations/</a></p><p>Source code is open as well. If this helps your understanding, feel free to star the repo. I am actively improving both.</p><h3>Final Thought</h3><p>So, the next time you see: “429 Too Many Requests”.</p><p>You will know that’s not friction but infrastructure discipline.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14988de1a05f" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/rate-limiting-explained-with-real-examples-fixed-window-sliding-window-token-bucket-leaky-14988de1a05f">Rate Limiting Explained with Real Examples: Fixed Window, Sliding Window, Token Bucket &amp; Leaky…</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Raft Consensus Explained Visually: Leader Election, Quorum, and Failure Recovery in Distributed…]]></title>
            <link>https://blog.stackademic.com/raft-consensus-explained-visually-leader-election-quorum-and-failure-recovery-in-distributed-c641d9dca2b5?source=rss-2bf0b686476e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c641d9dca2b5</guid>
            <category><![CDATA[distributed-system-design]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[consensus-algorithm]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[backend-engineering]]></category>
            <dc:creator><![CDATA[Olayiwola Akinnagbe]]></dc:creator>
            <pubDate>Tue, 07 Apr 2026 16:54:30 GMT</pubDate>
            <atom:updated>2026-04-10T07:11:06.824Z</atom:updated>
            <content:encoded><![CDATA[<h3>Raft Consensus Explained Visually: Leader Election, Quorum, and Failure Recovery in Distributed Systems</h3><p><em>Why distributed systems need leaders, and how they replace them without chaos.</em></p><h3>The Problem No One Sees</h3><p>Imagine a democratic country with five senators. They debate and argue policies. They propose new laws, but nothing becomes official unless the President approves it.</p><p>Now imagine something uncomfortable. The President disappears.</p><p>No announcement, no explanation, just silence. The senators wait, seconds pass, and there is still silence. At some point, someone must stand up and say: “We need a new leader.”</p><p>That tension, that moment between stability and uncertainty, is where distributed systems thrive. This is exactly the problem Raft was designed to solve.</p><figure><img alt="A 5-node cluster with one highlighted Leader node and four Followers." src="https://cdn-images-1.medium.com/max/1024/1*4fjJbh-PLZwClhbNTfwPtQ.png" /><figcaption>Image 1: A 5-node cluster with one highlighted Leader node and four Followers.</figcaption></figure><h3>Why Distributed Systems Need a Leader</h3><p>In a distributed system, multiple nodes replicate the same state. They cannot act independently.</p><p>If two nodes accept conflicting operations, your database becomes fiction. So the system needs coordination.</p><p>Raft solves this with a simple idea: <strong>At any time, there is exactly one leader.</strong></p><p>The leader:</p><p>· Accepts client requests</p><p>· Appends them to its log</p><p>· Replicates them to followers</p><p>· Commits entries once a majority agrees</p><p>No leader, no writes, no progress.</p><p>But leadership is not permanent, nor is it inherited, and that is where things get interesting.</p><h3>Heartbeats: “I Am Still the Leader”</h3><p>Leadership in Raft is not symbolic. It is earned and must be constantly proven. The leader periodically sends heartbeat messages to followers.</p><p>Think of it as the king riding through the kingdom shouting: “I am still here.”</p><p>As long as followers hear these heartbeats, they remain calm.</p><p>But if the heartbeats stop…</p><p>Silence becomes suspicion, and suspicion triggers an election.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2muJvIXIVyC7yXdZ5dHrKw.png" /><figcaption>Image 2: Heartbeat flow</figcaption></figure><h3>The Moment Silence Becomes an Election</h3><p>Every node starts as a follower waiting for heartbeats. If it does not hear from a leader within a randomised timeout:</p><p>· It increments its term</p><p>· It becomes a candidate</p><p>· It votes for itself</p><p>· It requests votes from others</p><p>This is not emotional; it is procedural. Each node asks:</p><p>“Is this candidate’s log at least as up-to-date as mine?”</p><p>If yes, it grants its vote. If a candidate receives a majority( a quorum), it becomes the new leader.</p><p>Why majority?</p><p>Because minority agreement is dangerous. Majority guarantees safety.</p><figure><img alt="Leader Election Sequence" src="https://cdn-images-1.medium.com/max/1024/1*U1WwIadwS_2Us5uDf4TvIg.png" /><figcaption>Image 3: Leader Election Sequence</figcaption></figure><h3>Why Majority Matters: The Mathematics of Safety</h3><p>Here is the quiet mathematical truth that makes Raft safe:</p><p>Any two majorities must intersect.</p><p>In a 5-node cluster:</p><p>· Majority = 3</p><p>· Any two groups of 3 nodes must share at least one node</p><p>That shared node prevents conflicting histories. If a log entry is committed by one majority, no different entry can be committed by another majority without overlapping at least one node that knows the truth.</p><p>This intersection property is not decorative. It is the backbone of consistency.</p><figure><img alt="Majority Intersection Illustration" src="https://cdn-images-1.medium.com/max/1024/1*bZ__sPh03v0CpoUiZTSErw.png" /><figcaption>Image 4: Majority Intersection Illustration</figcaption></figure><h3>Terms: The March of Logical Time</h3><p>Raft divides time into <strong>terms</strong>. Each election begins a new term.</p><p>Terms serve as logical clocks:</p><p>· If a node sees a higher term, it steps down.</p><p>· Leaders from old terms cannot remain in power.</p><p>· History only moves forward.</p><p>Terms prevent split-brain scenarios from persisting.</p><p>Leadership is temporary. The system always converges.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*csNqrotD2ISX9Di8K2xYgA.png" /><figcaption>Image 5: Term Progression Diagram</figcaption></figure><h3>Log Replication: Turning Agreement into History</h3><p>Leadership alone is not enough. The leader must replicate commands.</p><p>Here’s how it works:</p><p>1. Client sends request to the leader</p><p>2. Leader appends entry to its log</p><p>3. Leader sends AppendEntries RPCs to followers</p><p>4. Followers acknowledge</p><p>5. Once a majority acknowledges, the entry is committed</p><p>Only then is it applied to the state machine. Committed entries are permanent. They are not “probably safe”; they are permanent.</p><h3>What Happens During Failure?</h3><p>Let’s make it uncomfortable again. The leader crashes.</p><p>The cluster does not panic; they wait. This is because their randomised timers expire at different moments, which allows one to become a candidate first.</p><p>Furthermore, this node requests votes and wins the majority. A new leader has been elected and the system continues gracefully.</p><p>No chaos, no corruption, no rewriting history. Just structured recovery.</p><h3>Formal Safety and Liveness Guarantees</h3><p>Now we step beyond intuition. Consensus algorithms are judged by formal properties.</p><p>Raft guarantees both <strong>safety</strong> and <strong>liveness</strong> under defined conditions.</p><h3>Safety Properties (Nothing Bad Ever Happens)</h3><h3>1. Leader Completeness Property</h3><p>If a log entry is committed in a given term, then that entry will appear in the logs of all future leaders.</p><p>This is enforced by:</p><ul><li>Majority commit rule.</li><li>Log up-to-date checks during voting.</li></ul><p>A candidate lacking committed entries cannot win an election.</p><h3>2. Log Matching Property</h3><p>If two logs contain an entry with the same index and term, then the logs are identical up to that index.</p><p>This ensures that once logs converge at a particular point, they do not diverge afterward.</p><p>Followers reject inconsistent entries and request corrections from the leader.</p><h3>3. State Machine Safety</h3><p>If a node has applied a log entry at a given index to its state machine, no other node will apply a different entry at that same index.</p><p>This property ensures a consistent state across replicas.</p><h3>Liveness Guarantees (Something Good Eventually Happens)</h3><p>If:</p><p>· A majority of nodes are operational</p><p>· The network eventually delivers messages</p><p>Then:</p><p>· A leader will eventually be elected</p><p>· Client requests will eventually complete</p><p>Randomised election timeouts prevent perpetual split votes. Eventually, one candidate wins. Progress resumes.</p><h3>Safety Over Availability</h3><p>During a network partition:</p><p>· The majority partition continues</p><p>· The minority partition cannot elect a leader</p><p>This is deliberate because Raft chooses consistency over availability under partition.</p><p>In CAP terms: When partition occurs, Raft preserves Consistency. A minority must not define history.</p><h3>Failure Model Assumptions</h3><p>Raft assumes:</p><p>· Nodes may crash and restart</p><p>· Messages may be delayed or reordered</p><p>· Nodes are not malicious</p><p>This is a crash-stop model. Raft does not tolerate Byzantine failures.</p><h3>Why Raft Feels Calm</h3><p>Distributed systems are chaotic environments.</p><p>· Nodes fail.</p><p>· Networks delay.</p><p>· Messages reorder.</p><p>Raft feels calm, not because failure disappears…</p><p>But because strict rules constrain what is allowed to happen.</p><p>Leadership is temporary.<br> Majority defines truth.<br> Terms move forward.<br> Committed history cannot be rewritten.</p><p>Consensus is not magic.</p><p>It is mathematics applied to failure.</p><h3>Learn It Visually</h3><p>Reading about consensus builds understanding. Watching it unfold builds intuition. I built an interactive Raft consensus visualizer where you can simulate:</p><p>· Leader election</p><p>· Term changes</p><p>· Log replication</p><p>· Node failures</p><p>· Quorum behavior</p><p>Live demo:<br> <a href="https://raft-consensus-visualizer.netlify.app/">https://raft-consensus-visualizer.netlify.app/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*OjD_icgoctLm38-fD8VnAg.gif" /></figure><p>Because distributed consensus is not something you memorise. It is something you experience.</p><h3>Closing Thought</h3><p>Every time a distributed database survives a crash…</p><p>Every time a cluster elects a new leader without corrupting data…</p><p>Every time your system continues after failure…</p><p>Somewhere, a majority agreed.</p><p>And history moved forward safely.</p><p>That is Raft.</p><p><strong>A message from our Founder</strong></p><p>Hey, <a href="https://linkedin.com/in/sunilsandhu">Sunil</a> here. I wanted to take a moment to thank you for reading until the end and for being a part of this community. Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? We don’t receive any funding, we do this to support the community.</p><p>If you want to show some love, please take a moment to follow me on <a href="https://linkedin.com/in/sunilsandhu">LinkedIn</a>, <a href="https://tiktok.com/@messyfounder">TikTok</a>, <a href="https://instagram.com/sunilsandhu">Instagram</a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/">weekly newsletter</a>. And before you go, don’t forget to clap and follow the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c641d9dca2b5" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/raft-consensus-explained-visually-leader-election-quorum-and-failure-recovery-in-distributed-c641d9dca2b5">Raft Consensus Explained Visually: Leader Election, Quorum, and Failure Recovery in Distributed…</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Memory Is a Budget: Understanding Strong, Soft, Weak, and Phantom References in Java]]></title>
            <link>https://blog.stackademic.com/memory-is-a-budget-understanding-strong-soft-weak-and-phantom-references-in-java-14e8768916be?source=rss-2bf0b686476e------2</link>
            <guid isPermaLink="false">https://medium.com/p/14e8768916be</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[jvm]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Olayiwola Akinnagbe]]></dc:creator>
            <pubDate>Wed, 01 Apr 2026 18:47:24 GMT</pubDate>
            <atom:updated>2026-04-14T08:54:20.855Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction: Why JVM Reference Types Matter</strong></p><p>I am going to begin this write-up by discussing one of my interview failures and what I learned from it.</p><p>A few years ago, I successfully scaled through the HR and technical coding rounds for a company I really wanted to work for. During the Hiring Manager interview, I was asked to explain the different types of references in Java.</p><p>I knew them briefly. Sadly, that was not enough to pass the interview.</p><p>That experience taught me something important: understanding Java memory management at a surface level is not enough. You need to understand how the JVM actually thinks about object reachability.</p><p>In this article, we will discuss memory management and object references in Java in a way that truly sticks.</p><p>Java provides automatic memory management through the Garbage Collector (GC). It creates the illusion that memory is unlimited because developers do not explicitly allocate and deallocate memory. Unlike C++, we do not manually free memory.</p><p>However, this convenience comes with a trade-off: we do not directly control when garbage collection happens.</p><p>Because of this, it is imperative to understand object references properly. Poor reference management can lead to memory leaks, performance degradation, and eventually OutOfMemoryError.</p><p>A useful way to think about this is through a <strong>household budget analogy</strong>.</p><p>Memory in software is like money in a household account. Both are limited resources. If you manage them carelessly, you will eventually run into trouble.</p><p><strong>Quick Refresher: How GC Works in the JVM</strong></p><p>The Garbage Collector does not randomly delete objects. It works based on <strong>reachability analysis</strong>.</p><p>The JVM starts from special entry points known as <strong>GC Roots</strong>, such as:</p><ul><li>Local variables in active stack frames</li><li>Static fields</li><li>Active threads</li><li>JNI references</li></ul><p>If an object is reachable (directly or indirectly) from any GC Root, it stays in memory.</p><p>If it is not reachable, it becomes <strong>eligible for garbage collection</strong>.</p><p>For example:</p><ol><li><strong>Setting a Reference to <em>null</em></strong></li></ol><pre>class Money {<br>  int amount = 1;<br>}<br><br>Money money = new Money();<br>money = null; // Eligible for GC if no other references exist</pre><p><strong>2. When a Method Scope Ends</strong></p><pre>public void tempMoney() {<br>  Money tempMoney = new Money();<br>}<br><br>// After the method exits, the local reference is removed.<br>// If no other references exist, the object becomes eligible for GC.</pre><p>But reachability does not stop at “referenced or not referenced.”</p><p>This is where reference types come in.</p><p><strong>The Reachability Hierarchy (The Real Mental Model)</strong></p><p>Under the hood, the JVM evaluates objects through a hierarchy of reachability levels.</p><p>Think of it as a ladder</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iFmZjcHlMiotVIF3w7Z8iw.png" /></figure><p>An object moves down this ladder as its references weaken.</p><p>This is the real mental model behind strong, soft, weak, and phantom references.</p><p>Now let’s examine each one.</p><p><strong>Strong References</strong></p><p>This is the default in Java.</p><pre><br>class LargeMoney {<br>  int amount = 10_000_000;<br>  String currency = &quot;USD&quot;;<br>}<br><br>public class Main {<br>  public static void main(String[] args) {<br>    LargeMoney largeMoney = new LargeMoney();<br>  }<br>}</pre><p>As long as at least one strong reference exists, the object is <strong>strongly reachable</strong> and cannot be garbage collected.</p><p>If you store objects in long-lived static collections or caches using strong references, they remain in memory indefinitely. This is one of the most common causes of memory leaks in Java applications.</p><p><strong>Household Budget Analogy</strong></p><p>A strong reference is like money locked in your main account for ongoing expenses. As long as it is allocated there, it is not going anywhere.</p><p><strong>Soft References</strong></p><p>Soft references sit one level below strong references.</p><p>If an object has no strong references but is still referenced by a SoftReference, it becomes <strong>softly reachable</strong>.</p><pre>import java.lang.ref.SoftReference;<br><br>SoftReference&lt;LargeMoney&gt; softRef = new SoftReference&lt;&gt;(new LargeMoney());</pre><p>Softly reachable objects:</p><ul><li>Usually survive several GC cycles</li><li>Are cleared only under memory pressure</li><li>Are collected before the JVM throws OutOfMemoryError</li></ul><p>They are ideal for memory-sensitive caches.</p><p><strong>Household Budget Analogy</strong></p><p>A soft reference is like an emergency fund. It is not touched during normal operations. But if the household faces serious financial pressure, it becomes available.</p><p><strong>Weak References</strong></p><p>If an object has no strong or soft references and is referenced only by a WeakReference, it becomes <strong>weakly reachable</strong>.</p><pre>import java.lang.ref.WeakReference;<br><br>LargeMoney money = new LargeMoney();<br>WeakReference&lt;LargeMoney&gt; weakRef = new WeakReference&lt;&gt;(money);<br>money = null; // Now weakly reachable<br></pre><p>During the next GC cycle, the object is typically collected. A well-known example is WeakHashMap. Its keys are weakly referenced. If a key is not strongly referenced elsewhere, the entry automatically disappears.</p><p><strong>Household Budget Analogy</strong></p><p>A weak reference is like loose cash in your wallet. The moment the household needs money, it is the first to go.</p><p><strong>Phantom References</strong></p><p>Phantom references are the most advanced type.</p><p>When an object has no strong, soft, or weak references left, it may become <strong>phantom reachable</strong> if it is associated with a PhantomReference.</p><pre>import java.lang.ref.PhantomReference;<br>import java.lang.ref.ReferenceQueue;<br><br>LargeMoney money = new LargeMoney();<br>ReferenceQueue&lt;LargeMoney&gt; queue = new ReferenceQueue&lt;&gt;();<br>PhantomReference&lt;LargeMoney&gt; phantomRef = new PhantomReference&lt;&gt;(money, queue);<br><br>money = null;</pre><p>Important characteristics:</p><ul><li>get() always returns null</li><li>Used with ReferenceQueue</li><li>Used for post-mortem cleanup</li><li>Safer alternative to finalize()</li></ul><p>When the object is ready to be reclaimed, the phantom reference is enqueued. This allows you to perform cleanup safely.</p><p><strong>Household Budget Analogy</strong></p><p>A phantom reference is like receiving a bank notification after money has already left your account. You cannot access it anymore; you are simply informed that it is gone.</p><p><strong>Summary Comparison</strong></p><p>Here is a quick comparison:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6fhgqVTv4TVJnjm68g2RGg.png" /></figure><p><strong>Why the Reachability Ladder Matters</strong></p><p>Understanding this ladder is what separates memorization from mastery. Developers who misunderstand object references treat memory like unlimited income.</p><p>· Strong references keep objects at the top.</p><p>· Soft references delay their fall.</p><p>· Weak references allow quick descent.</p><p>· Phantom references notify you when the fall is complete.</p><p>Once you understand this state transition model, interview questions about Java references become straightforward.</p><p>You are no longer recalling definitions.</p><p>You are reasoning about reachability.</p><p><strong>Conclusion</strong></p><p>I hope this explanation and the household budget analogy help these concepts stick, so you do not fail your interview the way I did.</p><p>Memory is limited.<br>The GC reclaims unreachable objects.<br>Reference types influence <em>when</em> objects move down the reachability ladder.</p><p>Your job as a developer is not to manually free memory; that is the JVM’s responsibility.</p><p>Your job is to manage references wisely.</p><p>Do that well, and you let the Java Virtual Machine do what it was designed to do: manage memory automatically and efficiently.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14e8768916be" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/memory-is-a-budget-understanding-strong-soft-weak-and-phantom-references-in-java-14e8768916be">Memory Is a Budget: Understanding Strong, Soft, Weak, and Phantom References in Java</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>