<?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 Muhammad Bagas Sudibyo on Medium]]></title>
        <description><![CDATA[Stories by Muhammad Bagas Sudibyo on Medium]]></description>
        <link>https://medium.com/@bagasdisini?source=rss-20d596ba5555------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Eh1PYU_8gzM3UidsmEDlCw.jpeg</url>
            <title>Stories by Muhammad Bagas Sudibyo on Medium</title>
            <link>https://medium.com/@bagasdisini?source=rss-20d596ba5555------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 09:15:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bagasdisini/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[Building My Own Secrets Manager]]></title>
            <link>https://bagasdisini.medium.com/building-my-own-secrets-manager-1f37bfb7b2c8?source=rss-20d596ba5555------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f37bfb7b2c8</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[secrets]]></category>
            <dc:creator><![CDATA[Muhammad Bagas Sudibyo]]></dc:creator>
            <pubDate>Sun, 20 Sep 2026 03:41:51 GMT</pubDate>
            <atom:updated>2026-09-20T04:18:16.893Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h1rHeqQiuPOstfKgjew18g.png" /><figcaption>If you want to poke around, the code is at <a href="https://github.com/bagasdisini/polyvault">github.com/bagasdisini/polyvault</a>. Issues, roast, and PRs welcome.</figcaption></figure><p>I’ve used HashiCorp Vault enough times to respect it and also to resent it a little. Every time I ran vault operator init and watched those unseal keys print out, some part of my brain went: <em>okay, but what&#39;s actually happening under there?</em> Not in a &quot;I should read the docs&quot; way. In a &quot;I bet I could build a tiny one from scratch&quot; way.</p><p>So I decided to try. The goal wasn’t to replace Vault. The goal was to see whether the idea of a secrets manager (seal/unseal, encrypted storage, an audit log, encryption-as-a-service) could fit in my head all at once, written in plain Go, with no external dependencies to lean on. Just the standard library, a bunch of test files, and the faint hope that I wasn’t about to embarrass myself in front of finite-field arithmetic.</p><p>Also, I wanted a single binary. There’s something deeply satisfying about go build producing one file that claims to keep your secrets safe. Even if, as it turned out, some of those secrets were mostly safe from <em>me</em>.</p><h3>What PolyVault actually is</h3><p>At its core, PolyVault is four ideas duct-taped together with JSON:</p><ol><li><strong>Shamir’s Secret Sharing</strong> splits a master key into shares so you need, say, 3 out of 5 to reconstruct it.</li><li><strong>AES-256-GCM</strong> encrypts your secrets with that master key.</li><li><strong>An HMAC-chained audit log</strong> makes tampering obvious.</li><li><strong>A transit service</strong> lets apps encrypt/decrypt data with named keys without ever seeing the raw key.</li></ol><p>The whole thing is file-based, single-node, and auth-is-implemented-but-not-enforced. Think of it as Vault’s little cousin who skipped leg day.</p><h3>Shamir’s Secret Sharing, for people who forgot high school math</h3><p>Shamir’s idea is annoyingly elegant. You have a secret. You build a polynomial where the secret is the constant term. Then you pick random coefficients. Every share is just a point on that curve.</p><pre>y = secret + a1*x + a2*x^2 + ... + ak*x^k<br><br>share 1 = (x=1, y=...)<br>share 2 = (x=2, y=...)<br>share 3 = (x=3, y=...)</pre><p>With a threshold of k+1, any k+1 points uniquely determine the polynomial, so you can recover the constant term, the secret. Fewer points? You get nothing. That&#39;s the whole trick.</p><p>The catch: you can’t do this with normal floating-point numbers because computers are <strong><em>VERY </em></strong>bad at secrecy when rounding errors exist. So you do it over a finite field, specifically GF(256), where every value is one byte and arithmetic wraps around the AES irreducible polynomial 0x11B. Sounds fancy. It just means &quot;addition is XOR, multiplication is a lookup table&#39;s worst nightmare.&quot;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*1NfOvMPk7pif5pd2T8KfRg.png" /><figcaption>GF(256) black box diagram</figcaption></figure><h3>The first time it actually worked</h3><p>The first genuinely exciting moment was watching Shamir’s Secret Sharing work. I’ve written the GF(256) arithmetic, implemented Lagrange interpolation, and then watched a 32-byte master key split into five shares and come back together from any three of them (sumpah, ini SUSAH). It felt like actual magic. The kind of magic where you go “<em>Yeah, math b*tch</em>” and immediately want to show someone.</p><p>I didn’t show anyone, though, because about ten minutes later I wrote this test:</p><pre>func TestGfInv(t *testing.T) {<br>    for a := byte(1); a != 0; a++ {<br>        inv := gfInv(a)<br>        if gfMul(a, inv) != 1 {<br>            t.Fatalf(&quot;gfInv failed for %d&quot;, a)<br>        }<br>    }<br>}</pre><p>It failed for all 255 non-zero bytes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*Ubrb8LkXXUGQy0f0UJxGoQ.png" /><figcaption>Failed unit test</figcaption></figure><p>So the first time it “actually worked” was really the first time it <em>almost</em> worked, which I think is more honest. The split looked fine. The combine looked fine. But the multiplicative inverse at the heart of the whole thing was quietly wrong in a way that only showed up when you tested every value instead of a couple of lucky ones. That test became my favorite test in the whole project. It went from “nice to have” to “the reason I trust any of this.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*MSlG5n8O6cI6Ka8-UsnIAw.png" /><figcaption>Passed unit test</figcaption></figure><h3>The bug where the math looked right (but wasn’t)</h3><p>This is the part of the project I keep thinking about, because it’s such a perfect trap. I needed multiplicative inverses in GF(256) for Shamir reconstruction. I knew the trick: for any non-zero a, a^254 == 1, so a^253 == a^-1. I wrote a comment explaining the exponent decomposition. The comment was correct. The math in the comment was correct. I read the comment several times and <em>felt </em>smart 😎.</p><p>The loop next to the comment, however, was not correct.</p><p>Here was the original, confidently broken version:</p><pre>// a^254 = a^(2+4+8+16+32+64+128)<br>func gfInv(a byte) byte {<br>    result := a          // should be 1<br>    for i := 0; i &lt; 7; i++ {<br>        a = gfMul(a, a)<br>        if (254 &gt;&gt; (uint(i) + 1)) &amp; 1 == 1 {  // shifted wrong<br>            result = gfMul(result, a)<br>        }<br>    }<br>    return result<br>}</pre><p>I had the initial result set to a instead of 1, which is the kind of off-by-one-in-exponent-space bug that makes you want to lie down. Then I was shifting the bitmask by the wrong amount, so the loop wasn&#39;t even following the bits it claimed to follow. The result was an inverse function that confidently returned wrong values for every single input.</p><p>The embarrassing part is how long I stared at it before I saw it. The comment kept reassuring me. The code had to match the comment, right? The comment was so clear. Eventually I rewrote it as the textbook square-and-multiply loop:</p><pre>func gfInv(a byte) byte {<br>    result := byte(1)<br>    exp := 254<br>    for exp &gt; 0 {<br>        if exp&amp;1 == 1 {<br>            result = gfMul(result, a)<br>        }<br>        a = gfMul(a, a)<br>        exp &gt;&gt;= 1<br>    }<br>    return result<br>}</pre><p>And the property test turned green for all 255 non-zero bytes. I have never trusted a comment since.</p><h3>The bug where unsealing forgets shares have names</h3><p>Once the crypto worked, I hooked up an HTTP API. You could initialize the vault, get back a set of shares, and then submit them one at a time to unseal it. At least that was the theory. In practice, if you needed more than one share (which is kind of the whole point of a threshold) the vault would refuse to unseal and complain about duplicate shares.</p><p>It took me a while to understand why. Each share has two things: a value and an ID. The ID tells reconstruction which point on the polynomial this share represents. The CLI init command was only printing the value. The unseal handler was assuming every incoming share had ID 1. So two totally different shares would arrive looking like the same share submitted twice. The vault, correctly, said “you gave me the same thing twice, that’s not a threshold.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dH12e_Ns6C6iwEmsqbsYnA.png" /><figcaption>Share-ID loss diagram</figcaption></figure><p>The code looked roughly like this on the server side:</p><pre>share := shamir.Share{<br>    ID:     1,           // nope<br>    Values: shareBytes,<br>}<br>pendingShares = append(pendingShares, share)</pre><p>And on the CLI side, the init command only printed the hex bytes:</p><pre>for _, share := range shares {<br>    fmt.Printf(&quot;Share: %x\n&quot;, share.Values) // ID? never heard of her<br>}</pre><p>What’s funny is that the underlying Shamir package was fine. The direct library call worked. The integration tests passed because they used the library directly. The bug lived entirely in the glue between the CLI and the HTTP handler, which is exactly the kind of place you stop thinking about once the hard crypto feels solved. I still haven’t fully decided how share IDs should travel over the wire, as a prefix? a header? a separate argument? So this one is still sitting there, quietly broken, waiting for me to make a design decision.</p><h3>The feature that exists but doesn’t exist</h3><p>At some point I built a whole token authentication package. It creates tokens, validates them, revokes them, checks policies, handles TTL cleanup, even has an admin override. The config has an auth.enabled flag. The README lists &quot;Token Authentication&quot; as a feature. The HTTP server sets CORS headers that specifically allow the Authorization header, just in case a client wants to send one.</p><p><strong>The server never checks it.</strong></p><pre>// pkg/auth/auth.go has all of this...<br>func (a *Authenticator) CreateToken(...) (*Token, error) { ... }<br>func (a *Authenticator) Validate(token string) (*Token, error) { ... }<br>func (a *Authenticator) HasPolicy(token, policy string) bool { ... }<br><br>// internal/api/server.go has... none of it.</pre><p>The auth package is constructed, passed into the API layer, and then politely ignored. There is no middleware, no handler calls Validate, no policy enforcement. You can read, write, and delete secrets without ever proving who you are. The feature exists in code, in config, and in documentation, but not in behavior. It&#39;s a security feature that provides the illusion of security, which is arguably worse than no security at all.</p><p>I don’t have a good excuse (baca: malas). I built the auth layer, felt productive, and moved on to the next interesting thing before wiring it up. It’s the software-engineering equivalent of installing a deadbolt and never attaching the strike plate.</p><h3>The aha moment</h3><p>There were two moments where the project stopped feeling like a collection of packages and started feeling like a thing.</p><p>The first was the property test. Not the bug itself, the realization that spot-checking cryptography is a trap. When I wrote a loop that verified the inverse for every single non-zero byte, the test went from “probably fine” to “mathematically exhaustive.” That one test changed how I thought about the whole layer. If you can’t check every value, check enough values that you can’t hide from them.</p><p>The second was the wiring refactor. For a while the project was just loose command files that each reached into the packages they needed. It worked, but it felt fragile, like a breadboard project where one bumped wire kills the LED. Then I made a single struct that owns the vault, storage, auth, audit, transit, and HTTP server, and everything else reads from that. Suddenly the CLI commands, the server startup, and the config all talked to the same object. It wasn’t glamorous, but it was the moment the architecture clicked into place.</p><p>Both moments had the same shape: I had been clever, and then I simplified (jadi inget salah satu pepatah bahasa Go, “Clear is better than clever”)</p><h3>How the audit log actually works</h3><p>The audit log is one of my favorite parts because it sounds complicated but is actually just a linked list in a trench coat.</p><p>Every operation writes one JSON line. Each line contains the operation details plus an HMAC-SHA256 of the entire line. That HMAC includes the previous line’s HMAC. So if you delete or modify any single line, the next line’s HMAC no longer verifies, and the chain breaks.</p><pre>Entry 1: { op: &quot;init&quot;, data: ..., hmac: HMAC(entry1 + &quot;seed&quot;) }<br>Entry 2: { op: &quot;put&quot;,  data: ..., hmac: HMAC(entry2 + entry1.hmac) }<br>Entry 3: { op: &quot;get&quot;,  data: ..., hmac: HMAC(entry3 + entry2.hmac) }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TAL5H2qtrIdWZUNH0SkX4Q.png" /><figcaption>Audit chain diagram</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bmUQOX_QRmpR7-jfHANlvA.png" /><figcaption>Audit chain diagram (tampered version)</figcaption></figure><p><strong>It’s not blockchain. Please don’t call it blockchain. It’s just a chain of blocks.</strong></p><h3>How transit encryption works</h3><p>The transit service lets applications encrypt data with named keys without ever holding those keys. Each key has versions. When you encrypt, the current version is used. The ciphertext includes a one-byte version header, so even after you rotate the key, you can still decrypt old data.</p><pre>ciphertext = [1 byte key version][nonce][encrypted data][tag]</pre><p>The catch? Right now those keys live only in memory. Restart the server and they vanish, gone, hilang ditelan bumi. So transit encryption works great until you sneeze near the process.</p><h3>The thing I still don’t fully get</h3><p>I honestly don’t know what the right behavior is when storage fails to load.</p><p>Right now, if the vault can’t read its persisted state (missing file, corrupt JSON, permissions issue, whatever) it shrugs and starts fresh. No error. No warning to the operator. Just a clean, empty vault as if nothing was ever there. On one hand, that’s robust. On the other hand, it’s a production foot-gun the size of a barn. If your secrets file disappears, do you want the server to keep running and quietly accept new data? I don’t think so. But do you want it to crash on startup and take down everything with it? Maybe? I genuinely haven’t decided.</p><p>Same problem with the share IDs. The HTTP unseal bug is easy to describe (i am throwing away the ID) but the fix requires deciding on a wire format. Should the CLI print numbered shares? Should the API accept an id parameter? Should shares be self-describing? Every option changes the user experience and the API contract, and I keep bouncing between them. The bug is still open because the design question is still open.</p><p>I used to think “I don’t know” was something to hide in a blog post. Now I think it’s the most honest part.</p><h3>Does it actually work?</h3><p>If by “work” you mean “does the scary crypto part perform well enough that I stopped worrying about it,” then yes. Splitting a 256-byte master key into five shares and recombining it from three takes a couple hundred microseconds on a normal laptop. The raw finite-field multiply is in the nanoseconds. For a side project, that’s absurdly fast.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*omZjBZ7tEwyJPkHtAZFayQ.png" /><figcaption>Benchmark result</figcaption></figure><p>I ran the benchmarks once, nodded, and never optimized the Shamir layer again.</p><p>If by “work” you mean “can I trust this with real secrets,” then no, <strong>absolutely not</strong>. The auth isn’t enforced. The HTTP unseal path is broken for any threshold above one. Transit keys evaporate when the process restarts. The audit key is hardcoded. And there’s no TLS, no clustering, and no real graceful shutdown.</p><p>So the honest answer is that it works exactly as well as a learning project should: the core idea is solid, the crypto layer is fast, and the surrounding production concerns are a roadmap of things I haven’t done yet.</p><p><strong>Sekali lagi, ini fun project, jangan dipake buat nyimpen secrets beneran!</strong></p><p>The parts I’m proud of are real. The secrets engine encrypts and decrypts. The Shamir layer is correct and fast. The audit log is tamper-evident. The transit encryption service handles key rotation. The HTTP API understands Vault-like routes. The CLI exists and mostly works.</p><p>The parts I’m not proud of are also real. Authentication is implemented but not enforced. The HTTP unseal path can’t handle thresholds above one. Transit keys only live in memory, so they disappear on restart. Storage errors are swallowed. The audit key is hardcoded. Graceful shutdown isn’t. And the whole thing runs without TLS, clustering, or any serious production hardening.</p><p>So PolyVault is somewhere between a working prototype and a bad idea. It’s exactly the kind of project <strong>you build to understand a thing, not to ship a thing</strong>. The next steps are obvious: wire up auth, fix the share-ID protocol, persist transit keys, decide what to do about storage failures, and add TLS. Whether I do all of that or just leave it here and start the next project is, still an open question (its not, udah muak banget).</p><p>But I understand Vault a lot better than I did before.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f37bfb7b2c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Abstraction That Cost 3 Weeks of Debugging]]></title>
            <link>https://bagasdisini.medium.com/the-abstraction-that-cost-3-weeks-of-debugging-1919b4d5d311?source=rss-20d596ba5555------2</link>
            <guid isPermaLink="false">https://medium.com/p/1919b4d5d311</guid>
            <category><![CDATA[decision-making]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[abstraction]]></category>
            <dc:creator><![CDATA[Muhammad Bagas Sudibyo]]></dc:creator>
            <pubDate>Tue, 04 Aug 2026 03:27:26 GMT</pubDate>
            <atom:updated>2026-08-04T03:27:26.918Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dYqCotD_RDRzS4oyOQW0CQ.png" /></figure><p>There is a refactor that every mid-level engineer makes exactly once — and then, if they are lucky, never again. It happens around the 3-year mark, when you have read enough Clean Code to feel the weight of every duplicated line like a personal moral failing. You are reviewing a pull request, or working on a feature, and you notice it: two modules, each with a function that looks almost the same. The same five lines. The same query shape. The same error handling. One handles orders. The other handles refunds. But the structure — the structure is identical.</p><p>You extract a shared base class. You parameterize the difference. You write a generic `<em>processTransaction</em>` method that accepts a `<em>TransactionConfig</em>` and a list of `<em>TransactionStep</em>` objects. You commit it with a message like “DRY up transaction processing.” The tests pass. The PR is approved with compliments on the clean abstraction.</p><p>Three weeks later, the orders team needs to add fraud checking — but only for orders, not refunds. The `<em>TransactionConfig</em>` gets a `<em>skipFraudCheck</em>` boolean. Two weeks after that, refunds need a new step for payment gateway reversal, but orders do not. The `<em>TransactionConfig</em>` gets a `<em>reversalConfig</em>` object, nullable. A month later, a new engineer joins and spends two days reading the `<em>processTransaction</em>` method trying to understand what happens for a standard order — the logic is buried under 14 conditional branches, 6 configuration flags, and a comment at the top of the file that says “TODO: split this into separate implementations.”</p><p>The abstraction has become more complex than the duplication it replaced. And you cannot go back — the abstraction is now called from 40 places across the codebase. Reversing it would mean rewriting all 40 call sites. The cost of the wrong abstraction is not just the time spent debugging it. It is the time spent locked into it.</p><h3>Duplication Is Cheaper Than the Wrong Abstraction</h3><p>Sandi Metz, one of the most influential voices in object-oriented design, said something that should be printed on the wall of every engineering team: “Prefer duplication over the wrong abstraction.” This is not a defense of sloppy code. It is an empirical observation about the relative cost of two types of mistakes.</p><p>Duplication is a local problem. Two modules each contain a function that looks similar. When you need to change one, you change one. If you forget to change the other, the bug is isolated — it affects only the unmodified module. Debugging is straightforward: you look at the module, you see the old code, you update it. The cost of the mistake is linear in the number of duplicated sites, and each fix is independent.</p><p>The wrong abstraction is a global problem. Every change must pass through the abstraction’s interface. If the interface does not fit the change, you must either warp the change to fit the interface, warp the interface to fit the change, or add a configuration flag that makes the interface slightly more generic and slightly harder to understand. Each warping increases the abstraction’s complexity. Each configuration flag increases the cognitive load on every future reader. The cost of the mistake <strong>compounds</strong> with every new use of the abstraction. Debugging means tracing through the generic logic to understand which configuration path applies to your specific case — and then discovering that your specific case is not quite covered by any existing path, which is why the bug exists in the first place.</p><p>The rule is not “<em>never abstract.</em>” The rule is: <strong>abstract only when you understand the domain well enough to know what will change and what will not.</strong> That understanding does not come from reading Clean Code. It comes from shipping features, watching them evolve, and noticing which differences between two similar-looking things are accidental and which are essential.</p><h3>Three Deadly Sins of Premature Abstraction</h3><p>Every costly abstraction I have debugged falls into one of three categories. Learn to recognize them before you create them.</p><h4>Abstracting by Structure, Not by Meaning</h4><p>Two pieces of code look the same. They both iterate over a list, filter by a condition, and aggregate a result. You extract a generic `<em>filterAndAggregate</em>` function. But the reason they look the same is coincidental. One is computing revenue totals for a financial report. The other is counting error occurrences for a monitoring dashboard. The business meaning is completely different. Next quarter, the revenue calculation needs to include tax, and the error count needs to exclude retries. The generic function now needs two new parameters, or a strategy pattern, or — worst of all — it gets split back into two, but with the generic name still attached to both, so nobody knows which one does what.</p><p>The fix: <strong>abstract by business meaning, not by structural similarity.</strong> If two functions serve different business purposes, let them be structurally similar. The similarity is a coincidence, not an invitation.</p><h4>Abstracting Too Early, With Too Little Data</h4><p>You see two examples of a pattern. Two services that handle webhooks. Two endpoints that return paginated results. Two message consumers that deserialize and validate. Two examples is not a pattern. Two examples is a coincidence that is about to become a third example that breaks your abstraction. Wait until you have at least three examples before abstracting. Wait until you have seen how the pattern evolves across at least one major feature change. The abstraction you build after two examples will be optimized for exactly the two things you have seen, and wrong about the third.</p><p>The fix: <strong>the Rule of Three.</strong> When you see the same pattern twice, add a comment: “If a third instance of this pattern appears, extract a shared abstraction.” When the third instance appears, you now have three concrete cases to design against, not two. Your abstraction will be better.</p><h4>Abstracting to Remove All Duplication, Including the Accidental Kind.</h4><p>Not all duplication is the same. There are two kinds, and mistaking one for the other is the root cause of over-abstraction.</p><ul><li><strong>Essential duplication</strong> is two pieces of code that do the same thing for the same business reason. Two order processing pipelines, one for online orders and one for phone orders, both computing sales tax. The tax calculation should be extracted because the business rule is identical and will change identically.</li><li><strong>Accidental duplication</strong> is two pieces of code that happen to do the same thing today but answer to different business forces. The online order pipeline and the refund pipeline both compute a “<em>total amount.</em>” Today, the formula is `<em>price * quantity</em>`. Next month, online orders add a loyalty discount, and refunds add a restocking fee. The formulas diverge. If you extracted a shared `<em>computeTotal</em>`, you now have to add `<em>includeLoyaltyDiscount</em>` and `<em>includeRestockingFee</em>` booleans, and the function becomes a branching nightmare.</li></ul><p>The fix: <strong>before extracting, ask whether the two sites will change for the same reason in the future.</strong> If the answer is “I do not know,” wait. If the answer is “probably not,” do not extract. If the answer is “yes, they are governed by the same business rule,” extract.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uuCoh3Gn6iCTUZmw7suhxg.png" /></figure><h3>The Cost Profile Nobody Talks About</h3><p>Let’s put numbers on this, because abstract discussions about abstractions are how we got into this mess.</p><ul><li><strong>Cost of duplication:</strong> You have the same 15 lines in 4 places. Someone changes the logic. They update 3 of the 4 places. The fourth place has the old bug. A customer reports it. An engineer spends 45 minutes finding the stale code, 5 minutes fixing it. Total cost: 50 minutes, once, for a bug that is trivial to diagnose because it is local.</li><li><strong>Cost of the wrong abstraction:</strong> You extract the 15 lines into a shared function with 3 parameters. Over 18 months, the 4 original call sites grow to 12. Each new call site adds a requirement that does not quite fit. The function accumulates 7 optional parameters, a strategy interface with 4 implementations, and a 40-line docstring explaining which parameter combinations are valid for which use cases. A new engineer spends 3 days reading the function and its call sites to understand what it actually does. A bug is introduced when someone passes a parameter combination that the function’s internal logic does not handle correctly — but the function does not reject it, it just produces wrong output. The bug takes 2 weeks to find because the root cause is buried in the abstraction’s internal branching. Total cost: 3 days of onboarding + 2 weeks of debugging + the ongoing tax of every future change to any call site needing to thread through the abstraction’s interface.</li></ul><p><strong>The breakeven point for duplication vs. abstraction is far further out than most engineers assume.</strong> Duplication has to be very expensive — dozens of sites, frequent coordinated changes, high-severity bugs from missing a site — before the abstraction’s compounding complexity tax becomes the cheaper option.</p><p>This is why the industry’s best practitioners have been pushing back against aggressive DRY for years.</p><blockquote>“Duplication is far cheaper than the wrong abstraction.” — Kent Beck</blockquote><blockquote>“Try to resist the urge to DRY everything up until you feel the pain.” — Dan Abramov</blockquote><p>The pain they are talking about is not the aesthetic discomfort of seeing similar code in two files. It is the operational pain of coordinating changes across multiple sites, feeling the same bug recur because you forgot to update one of them. If you have not felt that pain yet, you do not need the abstraction.</p><h3>How to Abstract Correctly: The Protocol-First Approach</h3><p>When you do have enough data to justify an abstraction — multiple sites, stable domain understanding, shared business meaning — the most reliable technique is to define the interface first, not the implementation.</p><p><strong>Step 1: Define the protocol.</strong> What does every consumer of this abstraction need? Write it as an interface or a protocol, with one concrete comment per method explaining what the method accomplishes, not how.</p><pre>class PaymentProcessor(Protocol):<br>    def authorize(self, amount: Decimal, currency: str) -&gt; AuthorizationResult:<br>        &quot;&quot;&quot;Reserve funds. Does NOT transfer them. Call capture() to transfer.&quot;&quot;&quot;<br>        ...<br><br>    def capture(self, authorization_id: str, amount: Decimal) -&gt; CaptureResult:<br>        &quot;&quot;&quot;Transfer previously authorized funds. Idempotent — calling twice with<br>        the same authorization_id returns the same CaptureResult.&quot;&quot;&quot;<br>        ...<br><br>    def refund(self, capture_id: str, amount: Decimal) -&gt; RefundResult:<br>        &quot;&quot;&quot;Return captured funds to the customer. Partial refunds are allowed<br>        up to the captured amount.&quot;&quot;&quot;<br>        ...</pre><p>The protocol does not mention Stripe, Braintree, or any specific provider. It describes the business capability, not the technical implementation. This is the abstraction. It will survive provider changes, API version bumps, and internal refactors because it is defined in terms of what the business needs, not what the current provider offers.</p><p><strong>Step 2: Implement against the protocol.</strong> Write one concrete implementation for each provider. Each implementation is simple — it maps the business protocol to the provider’s specific API. It does not have configuration flags because it does not need them. It does one thing: translate from the business language to the provider language and back.</p><p><strong>Step 3: Compose, do not extend.</strong> When a new requirement arrives that does not fit the protocol, do not add a parameter to the protocol. Create a new protocol. `<em>FraudChecker</em>` is a separate protocol from `<em>PaymentProcessor</em>`. The order flow composes both. The refund flow composes only `<em>PaymentProcessor</em>`. Neither flow carries configuration flags for a concern it does not have.</p><p>This is the inversion of the standard abstraction mistake.</p><ul><li>The mistake: extract the shared code, then try to make it work for everyone by adding flags.</li><li>The fix: define the shared interface, then implement it separately for each distinct case. The interface is the abstraction. The implementations are allowed to be different.</li></ul><p>The same shape holds in any language. Here is the composition step in TypeScript, where the protocol becomes an interface and the flows become small classes that declare their dependencies instead of inheriting them:</p><pre>interface PaymentProcessor {<br>  authorize(amount: number, currency: string): Promise&lt;AuthorizationResult&gt;;<br>  capture(authorizationId: string, amount: number): Promise&lt;CaptureResult&gt;;<br>  refund(captureId: string, amount: number): Promise&lt;RefundResult&gt;;<br>}<br><br>interface FraudChecker {<br>  check(customerId: string): Promise&lt;FraudDecision&gt;;<br>}<br><br>class OrderFlow {<br>  constructor(<br>    private readonly payments: PaymentProcessor,<br>    private readonly fraud: FraudChecker,<br>  ) {}<br><br>  async checkout(cart: Cart): Promise&lt;Order&gt; {<br>    await this.fraud.check(cart.customerId);<br>    const authorization = await this.payments.authorize(cart.total, &quot;USD&quot;);<br>    const capture = await this.payments.capture(authorization.id, cart.total);<br>    return new Order(capture);<br>  }<br>}<br><br>class RefundFlow {<br>  constructor(private readonly payments: PaymentProcessor) {}<br><br>  async refund(captureId: string, amount: number): Promise&lt;RefundResult&gt; {<br>    return this.payments.refund(captureId, amount);<br>  }<br>}</pre><p>Notice what is absent: `<em>OrderFlow</em>` has no `<em>skipFraudCheck</em>` boolean, because it never skips fraud checks. `<em>RefundFlow</em>` has no optional reversal configuration, because refunds never authorize. When the day comes that phone orders need fraud checking but online orders do not, the answer is a third implementation of `<em>FraudChecker</em>` — or a third flow class — not a new flag on a shared constructor. TypeScript enforces this at compile time: if the dependency is not declared, it cannot be passed, and the mistake becomes a build error instead of a runtime surprise.</p><h3>When to Undo an Abstraction</h3><p>Sometimes the right move is to reverse a previous abstraction. The signs are recognizable:</p><ul><li>The abstraction has more than 3 boolean parameters that control which code path executes. These are not configuration — they are evidence that the abstraction is trying to be multiple different things.</li><li>New team members cannot understand the abstraction without reading all of its implementations. A good abstraction can be understood from its interface alone.</li><li>Changes that should be local — “add fraud check to the order flow” — require modifying the shared abstraction and testing all other call sites to ensure they are unaffected.</li><li>The abstraction’s tests are larger and more complex than the combined tests of the individual implementations would be.</li></ul><p>The abstraction’s tests are larger and more complex than the combined tests of the individual implementations would be.</p><ol><li><strong>Inventory the use cases before writing any code.</strong> Grep every call site. List which parameters and flags each call site actually passes. Then group the call sites: each group that passes a distinct combination is a latent use case, even if the code treats them as variations on a single theme. There are almost always 3–5 of them. A call site that passes a bizarre flag combination you forgot existed is not an anomaly — it is the fourth use case your inventory just revealed.</li><li><strong>Write characterization tests first.</strong> Before changing a single line, capture the abstraction’s current behavior: feed it representative inputs, record the outputs, and commit them as regression tests. This is the safety net that lets you restructure code and know, with certainty, that you changed structure and not behavior. Without it, you cannot tell the difference between “the new module is correct” and “the new module fails differently than the old code.”</li><li><strong>Extract one use case at a time. </strong>Do not delete the abstraction in the same PR that creates the first dedicated module. Extract the first use case, migrate its call sites, merge, deploy. Then extract the next one. Each PR is small, independently deployable, and trivially reviewable. The abstraction stays in place, shrinking, until the final PR — which is the only one that should be scary, and by then it is a deletion, not a refactor.</li><li><strong>Migrate call sites in lockstep with their use case.</strong> When you extract a use case, move all of its call sites in the same PR. Do not leave half the call sites on the old abstraction “for later” — that is how you end up with two implementations of the same thing, maintained by nobody.</li><li><strong>Delete the abstraction last — and only when it is truly empty.</strong> When the final call site moves, the abstraction dies. If you cannot delete it because something still depends on it, you missed a use case in step 1. That is not a failure; it is the inventory being wrong, and the fix is to extract that use case too. An abstraction with zero call sites is dead code. Do not keep it “in case we need it.”<strong> You are not going to need it</strong>. Your inventory proved that.</li><li><strong>Manage the PR like a migration, not a refactor.</strong> The PR description should contain a table: use case, new module, call sites moved, expected behavior change — which should read “none” for every row, because of step 2. Request one reviewer who has context, ideally the engineer who wrote the original abstraction, both as a courtesy and because they will catch semantic nuances nobody else knows. Point them at the characterization tests first, the diff second.</li><li><strong>Communicate before, during, and after.</strong> Before you start, post a short brief in the team channel: what you are de-abstracting, why, and — most importantly — what will not change. Nobody likes a surprise rewrite of code they depend on. During the work, keep the branch short-lived and the PRs small: a week of de-abstraction PRs is fine, a month of open branch is not. After the merge, update the wiki page or README that documents the abstraction, or the next engineer will spend an hour hunting for a class that no longer exists.</li><li><strong>Measure for two weeks after the merge.</strong> The whole point of dedicated modules is that they are isolated. If a new module misbehaves, it is the only place to look. Watch the error rates of the new modules, and if something regressed, the revert is small and surgical. Then hold a short retro: how long did the migration take, what surprised you, which call sites did you mis-classify. That data feeds the next de-abstraction, because there will be a next one.</li></ol><p>This refactor is called <strong>de-abstraction</strong>, and it is one of the highest-value activities a senior engineer can perform on a codebase. It replaces complexity with clarity, one module at a time. The commit messages should be celebratory: “De-abstracted payment processing — 3 dedicated modules replacing 1 generic processor with 11 configuration flags.” The team will thank you. The next engineer will not spend 3 days reading the code. They will spend 30 minutes.</p><p>Two case studies shows up from someone on the internet, across the industry, different company, different domain, same shape:</p><blockquote>“In 2024, our billing team de-abstracted the invoice generation pipeline. The pipeline had grown over 5 years from a single `generateInvoice` function with 2 parameters into an `InvoiceGenerator` class with 17 constructor parameters, 4 strategy interfaces, and a 600-line `generate` method that handled subscription invoices, one-time purchase invoices, credit memos, and prorated upgrades — all through branching logic. The team split it into 4 dedicated generators: `SubscriptionInvoiceGenerator`, `OneTimePurchaseInvoiceGenerator`, `CreditMemoGenerator`, and `ProrationGenerator`. Each was under 150 lines. The combined line count went up by 40%, and the team’s bug rate on invoice generation dropped by 80%. The post-de-abstraction code was longer but simpler — and ‘longer but simpler’ is almost always the right trade-off.”</blockquote><blockquote>“In 2023, our pricing team de-abstracted the trip pricing engine. The `TripPricingEngine` class had absorbed eight years of surge pricing, driver incentives, and promotions into a 900-line `calculate` method with 6 boolean flags and 5 strategy implementations. We split it into 6 dedicated calculators — surge, base fare, incentive, promo, cancellation, and fee — each under 120 lines. The public `estimateFare` interface did not change, so no consumer of the API changed a single line. The metrics after three months: support tickets about incorrect fares down 65%, median time to fix a pricing bug down from 3 days to 4 hours, and pricing experiment deploys up from one per week to one per day. We did not delete complexity — the engine still had roughly the same total line count. We relocated the complexity to where it could be changed in isolation, and that was the entire point.”</blockquote><p>Two companies, two domains, one lesson. The billing team measured a bug-rate drop; the pricing team measured velocity. Both kept their interfaces stable and let the implementations diverge. The interface was the abstraction — it survived both refactors — while the implementations finally told the truth about being different things.</p><h3>The Abstraction Health Check</h3><p>Abstractions rot the same way everything else does: slowly, one small compromise at a time, until the day you look at the class you once loved and cannot remember why you built it. The difference between an abstraction that rots and one that stays healthy is not the engineer who wrote it. It is the team that reviews it. The fix is a scheduled, cheap, recurring review: the abstraction health check.</p><p>Run it once per quarter, on the same cadence as your architecture review or sprint planning. You do not need a formal meeting — a 30-minute slot on the calendar, one engineer per abstraction, is enough. For each candidate abstraction, work through the checklist:</p><ul><li><strong>Count the parameters and flags.</strong> More than 3 booleans that control which code path executes is a yellow flag. More than 5 is a red flag: that abstraction is trying to be multiple things, and it should be scheduled for de-abstraction, not another parameter.</li><li><strong>Measure call-site diversity.</strong> Group the call sites by the parameter combinations they pass. One group means the abstraction is doing one job. Three or more groups means it is doing three or more jobs behind a shared door.</li><li><strong>Read the interface alone.</strong> Can you understand what the abstraction does from its interface, without opening any implementation? If the docstring is longer than the interface, or the interface cannot be understood without the implementations, the abstraction has failed its first test.</li><li><strong>Check the git history for feature churn.</strong> Look at the last 3 months of commits. If most changes to the abstraction were made to serve one specific call site — a flag added here, an edge case handled there — the abstraction is being warped by one tenant, and everyone else pays the cognitive tax.</li><li><strong>Compare the tests.</strong> If the abstraction’s test suite is larger and more complex than the combined tests of its hypothetical individual implementations would be, the abstraction is being tested for every specific case it was never meant to be.</li><li><strong>Run the new-hire test.</strong> Hand a new engineer the interface and ask them what it does. If they need to read the implementations to answer, the interface is lying about what the abstraction is.</li></ul><p>Score it simply. 0 failures: leave it alone, check again next quarter. 1–2 failures: simplify — remove dead flags, tighten the docstring, document the call-site groups. 3 or more failures: schedule the de-abstraction as an explicit task in the next sprint, using the process above. Name an owner for each abstraction, because an abstraction owned by everyone is reviewed by no one.</p><p>The health check is cheap: 30 minutes a quarter per candidate, and you will run it on maybe a dozen abstractions. It converts the cost of the wrong abstraction from an unknown, compounding liability into a known, scheduled one — which is the only kind of technical debt you can actually manage.</p><h3>Further Reading</h3><p>Key Concepts: Rule of Three, essential vs. accidental duplication, protocol-first abstraction, de-abstraction, composition over inheritance, the wrong abstraction cost curve, Sandi Metz’s duplication rule, interface segregation principle.</p><p>Essential Resources:</p><ul><li>Sandi Metz, <strong>Practical Object-Oriented Design in Ruby</strong> — Chapter 3 (Managing Dependencies) and the famous “Duplication is far cheaper than the wrong abstraction” talk</li><li>Kent Beck,<strong> Implementation Patterns</strong> — the section on when to abstract and when to inline</li><li>Dan Abramov, <a href="https://overreacted.io/goodbye-clean-code/">Goodbye, Clean Code</a> — a personal account of de-abstracting a codebase and watching team velocity increase</li><li>John Ousterhout, <strong>A Philosophy of Software Design</strong> — the concept of “deep modules” and why simple interfaces with complex implementations are better than complex interfaces with simple implementations</li><li>The <a href="https://sandimetz.com/blog/2016/1/20/the-wrong-abstraction">Wrong Abstraction</a> — Sandi Metz’s original post that started the anti-over-abstraction movement</li></ul><h3>Conclusion: Patience Is the Hardest Refactor</h3><p>The urge to abstract is not a technical impulse. It is an aesthetic one. Duplication looks wrong because it violates a rule we were taught early: Don’t Repeat Yourself. The rule is good. The premature application of the rule is not.</p><p>The discipline to leave duplication in place — to add a comment instead of an abstraction, to wait for a third example, to ask “do these two things change for the same reason” and honestly answer “I don’t know yet” — is harder than writing the abstraction. Abstraction feels productive. Waiting feels lazy. But the cost of the wrong abstraction is paid over months and years, while the cost of waiting is paid in the 45 minutes it takes to fix a duplicated bug. The trade-off, once you see the numbers, is not close.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e2jvrme8GNbhUnGCvy30Eg.png" /></figure><blockquote>The next time you see two similar functions and feel the urge to merge them, ask yourself: do they look the same because they serve the same business purpose, or do they look the same because you have only seen two of them? If you cannot answer with confidence, leave them alone. The bug you prevent by not creating the wrong abstraction is invisible — but it is larger than the bug you prevent by removing the duplication. Happy Coding!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1919b4d5d311" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Architecture for a 5 Million Request Traffic Burst]]></title>
            <link>https://bagasdisini.medium.com/architecture-for-a-5-million-request-traffic-burst-c87895331cfa?source=rss-20d596ba5555------2</link>
            <guid isPermaLink="false">https://medium.com/p/c87895331cfa</guid>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Muhammad Bagas Sudibyo]]></dc:creator>
            <pubDate>Sat, 23 May 2026 08:31:32 GMT</pubDate>
            <atom:updated>2026-05-23T08:31:32.158Z</atom:updated>
            <content:encoded><![CDATA[<p>Last month I went to war, not a literal war, but something arguably just as stressful, a concert ticket war. I had my three monitors set up, my credit card taped to my forehead, and my mouse finger twitching. At exactly 10:00:00 AM, I clicked “Buy.”</p><p>I was immediately met with the spinning wheel of death, followed by a polite message telling me there were 500k people ahead of me. Ten minutes later? Sold out. I didn’t get them.</p><p>I was devastated. But the grief quickly mutated into a burning obsession. I found myself staring at the ceiling wondering: <em>How do they actually design a system that doesn’t just instantly burst into flames when 5 million people hit the same database at the exact same millisecond?</em></p><p>And oh boy, I jumped down to an incredibly deep rabbit hole.</p><p>Whether it’s concert tickets, a limited-edition sneaker drop, or a PS5 restock, the core engineering challenge is identical.</p><p>Here is the exact scenario we are dealing with:</p><ul><li><strong>The Inventory:</strong> Exactly 50,000 items.</li><li><strong>The Traffic:</strong> 5 million unhinged users hitting your API in a 3-second window.</li><li><strong>The Golden Rule:</strong> You absolutely <em>cannot</em> oversell. If you sell 50,001 tickets, legal is going to have a very bad day.</li><li><strong>The Flow:</strong> When a user clicks “Buy,” the system reserves the item for exactly 10 minutes to allow them to pay. If they fail, the item goes back into the wild.</li></ul><p>If you try to build this using a standard REST API and a PostgreSQL database, your servers will melt before 10:00:01 AM. Here is how big tech actually solves it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uKiA_zVY84HoeaggHPfffA.png" /></figure><h3>Step 1: Flat the Curve</h3><p>The biggest mistake junior engineers make is thinking the goal of the “Buy” button is to immediately process the order. It isn’t. <strong>The goal of the API at 10:00:00 AM is simply to survive.</strong></p><p>If 5 million requests try to open a database connection simultaneously, you will exhaust your connection pool, max out your CPU, and crash. You have effectively DDOS’d yourself.</p><p>Instead, we have to flatten the curve.</p><ul><li><strong>The Shield (CDN/WAF):</strong> Before the request even reach our backend servers, it hits a Web Application Firewall (like Cloudflare or Akamai). This blocks the bots, handles the SSL handshakes, and absorbs the initial network shock.</li><li><strong>The API Gateway:</strong> The request reaches our API. At this stage, our code does absolutely zero database queries. No SELECT, no INSERT.</li><li><strong>The Asynchronous Job:</strong> The API handler generates a unique RequestID, drops a tiny JSON payload into an <strong>Asynchronous Message Queue</strong> (like Apache Kafka or AWS SQS), and immediately fires back an HTTP 202 Accepted response.</li><li><strong>The Waiting Room:</strong> The user’s browser receives that 202 and thinks, <em>“Sweet, I’m in line!” </em>while the frontend then starts quietly polling a secondary endpoint (/status?req_id=xyz) every 5 seconds to check if their ticket is ready.</li></ul><p>By offloading the ingest to a queue, we took a catastrophic 3-second traffic spike and turned it into a perfectly flat, controllable stream of messages that our backend worker pods can consume at their own pace.</p><h3>Step 2: Inventory Allocation</h3><p>Alright, our worker pods are pulling users out of the Kafka queue. Now we have to check if there are any tickets left.</p><p>Your first instinct might be to query the database:</p><pre>SELECT tickets_left FROM inventory WHERE id = 1 FOR UPDATE.</pre><p><strong>DO NOT DO THIS.</strong></p><p>Running a row-level lock on a relational database millions of times a minute will cause queries to queue up until the database runs out of memory and crashes. PostgreSQL is an amazing piece of technology, but it is not built for millions of concurrent row mutations, instead<strong> Use Redis.</strong></p><p>We use Redis. Redis stores data entirely in RAM, but more importantly, <strong>Redis is single-threaded</strong>. It processes commands one by one, in perfect, sequential order.</p><ul><li>Before the sale starts, we load the inventory into Redis: SET tickets_left 50000.</li><li>As our worker pods pull a user from Kafka, they execute a Redis decrement command: DECR tickets_left.</li><li>Because Redis is single-threaded, it is mathematically impossible for two concurrent workers to grab the same ticket. There is no race condition.</li><li>If the number returned is &gt;= 0, the user gets a ticket! The worker <em>then</em> takes its time to write that beautiful, confirmed reservation into the PostgreSQL database.</li><li>If the number is &lt; 0, the worker returns a “Sold Out” status.</li></ul><p>The database is completely shielded. It only ever processes the 50,000 successful writes, while Redis happily absorbs the 4,950,000 rejections at lightning speed.</p><h3>Step 3: State Management</h3><p>We’ve successfully reserved a ticket. The user is on the checkout page, staring at a 10-minute countdown timer. But what if their credit card declines, or their laptop dies? We need to take that ticket back.</p><p>The lazy way to do this is a Cron Job: every 60 seconds, run a query like:</p><pre>SELECT * FROM reservations WHERE status=&#39;pending&#39; AND created_at &lt; NOW() - 10 minutes.</pre><p>This is a terrible idea. Running a massive table scan on your primary database every minute during a high-traffic event is a fantastic way to bring down production.</p><p>Instead of actively searching for expired carts, we use an event-driven approach.</p><ul><li>The exact millisecond a user is granted a reservation, our worker publishes a message into a <strong>Delay Queue</strong> (like an AWS SQS Delay Queue, or a RabbitMQ Delayed Message exchange).</li><li>The message payload is simple: {“order_id”: 12345, “action”: “check_payment”}.</li><li>We set the invisibility timer on this message to exactly <strong>10 minutes</strong>.</li><li>For 10 minutes, that message sits silently in the queue. The database is untouched.</li><li>Exactly 10 minutes later, the message pops out. A worker picks it up and does a single, primary-key lookup in the database: <em>“Did Order 12345 transition to PAID?”</em></li><li>If <strong>YES</strong>, the worker deletes the message and moves on.</li><li>If <strong>NO</strong>, the worker updates the database to CANCELLED, and sends an INCR tickets_left command back to Redis, throwing the ticket back into the pool for the next lucky person in the waiting room.</li></ul><h3><strong>Takeaway</strong></h3><p>When I finally understood this architecture, I stopped being mad about losing out on my concert tickets. I was honestly just impressed.</p><p>System design at a massive scale isn’t about writing the most perfectly optimized for loop in Java, Go, or even Rust. It is about understanding the mechanical limitations of your infrastructure and using different tools (CDNs, Queues, In-Memory Caches, Relational Databases) to protect each other’s blind spots.</p><blockquote>So, next time you are stuck in a virtual waiting room watching a little progress bar slowly fill up, don’t rage-quit. Just take a sip of your coffee and appreciate the fact that somewhere, an asynchronous message queue is working overtime to keep a PostgreSQL database from exploding. Happy Coding!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c87895331cfa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Distributed Transactions Without Losing Your Mind]]></title>
            <link>https://bagasdisini.medium.com/mastering-distributed-transactions-without-losing-your-mind-466f272b8cba?source=rss-20d596ba5555------2</link>
            <guid isPermaLink="false">https://medium.com/p/466f272b8cba</guid>
            <category><![CDATA[monolithic-architecture]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[microservice-architecture]]></category>
            <dc:creator><![CDATA[Muhammad Bagas Sudibyo]]></dc:creator>
            <pubDate>Mon, 14 Jul 2025 05:17:26 GMT</pubDate>
            <atom:updated>2025-07-15T13:22:54.836Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*v5KlKSqy9b8iTSSY.jpg" /><figcaption>Money Heist on <a href="https://www.netflix.com/id/title/80192098">Netflix</a></figcaption></figure><p>You’re part of a team planning an elaborate, multi-stage bank heist. You have a safecracker, a getaway driver, and a lookout — each a specialist in their field. For the heist to succeed, every single step must go off without a hitch. If the safecracker fumbles the combination, the getaway driver can’t just leave with an empty van, and the lookout can’t simply go home. The entire operation must be cleanly aborted. Everyone walks away, nothing is half-stolen, and no one gets caught. This “<strong>all-or-nothing</strong>” guarantee is what we call atomicity, and in the world of software, it’s the holy grail of transaction management.</p><p>In the old days of monolithic applications, this was relatively simple. A single, powerful “mastermind” — the database’s transaction manager — oversaw the entire operation. It could ensure that updating a user’s profile and their order history happened as one indivisible unit. But then we moved to microservices. We broke our monolith into a team of independent specialists, each with their own tools and their own private ledger — their own database. This “Database per Service” pattern gave us incredible benefits: services could be developed, deployed, and scaled independently. But it came at a cost. We lost our central mastermind. Our heist now involves coordinating specialists who can’t directly see each other’s work.</p><p>This is the fundamental challenge of distributed transactions. It’s not an accidental bug or an oversight; it’s a direct and deliberate trade-off we make when we choose the microservice architecture. The pain of managing data consistency across services is the price we pay for their autonomy and scalability. So, how do we pull off the heist without the whole thing falling apart?</p><h3>The Ghost of Transactions Past: Why Two-Phase Commit (2PC) Haunts Modern Architectures</h3><p>When faced with coordinating our distributed heist, the first and most obvious idea is to impose a rigid, top-down command structure. This is the world of the <strong>Two-Phase Commit (2PC) </strong>protocol, the ghost of transactions past that still lingers in many systems. Think of it as a game of “Mother, May I?” played with databases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cUwtE1mjsodZhz2W.png" /><figcaption>Two-Phase Commit Protocol on <a href="https://en.wikipedia.org/wiki/Two-phase_commit_protocol">Wikipedia</a></figcaption></figure><p>Here’s how this protocol works:</p><ul><li><strong>The Coordinator:</strong> A central service is designated as the transaction coordinator, the single authority managing the entire process.</li><li><strong>Phase 1: The Prepare Phase (The Vote):</strong> The coordinator sends a “prepare” message to all participating services (the “cohorts”). It’s asking, “Can you, right now, guarantee you can commit this change?” Each service checks if it can perform its part of the transaction, locks the necessary resources to prevent other operations from interfering, and votes “yes” or “no”.</li><li><strong>Phase 2: The Commit Phase (The Command):</strong> If the coordinator receives a unanimous “yes” from all participants, it broadcasts a “commit” command. All services then make their changes permanent. However, if even one service votes “no” or fails to respond within a timeout, the coordinator broadcasts a “rollback” command, and every service must undo its prepared changes.</li></ul><p>On paper, this sounds like it guarantees atomicity. And it does, but at a cost that modern, scalable systems can rarely afford to pay.</p><h4>Why 2PC Is a Ghost in the Modern Machine</h4><ul><li><strong>The Problem of Blocking:</strong> This is 2PC’s fatal flaw. Once a service votes “yes” in the prepare phase, it must lock its resources and wait for the coordinator’s final command. It is completely blocked. If the coordinator crashes during this waiting period, the service is left in limbo — it doesn’t know whether to commit or roll back. It’s stuck holding locks, unable to proceed or serve other requests, potentially for a very long time until the coordinator is manually recovered.</li><li><strong>The Performance Bottleneck:</strong> The entire distributed transaction moves at the speed of its slowest participant. All other services must wait for the laggard to cast its vote and then wait again for the final command. This synchronous, lock-step coordination kills performance and severely limits system throughput, especially in geo-distributed environments where network latency is a given.</li><li><strong>The Single Point of Failure:</strong> The coordinator is a massive liability. If it fails, the entire system can grind to a halt. One real-world e-commerce site reportedly lost 15% of its daily revenue when its 2PC coordinator crashed during a major sale. While the coordinator itself can be made fault-tolerant, this adds significant complexity.</li><li><strong>The Tight Coupling Dilemma:</strong> 2PC forces <em>temporal coupling</em> — services are bound together in time for the duration of the transaction. They lose their autonomy. This directly violates the core principle of microservices, which is to be loosely coupled and independent.</li></ul><p>The limitations of 2PC expose a fundamental conflict with a core principle of distributed systems: the CAP Theorem. The theorem states that a distributed system can only guarantee two out of three properties: <strong>Consistency (C), Availability (A), and Partition Tolerance (P)</strong>. Since network partitions (P) are an unavoidable reality, the real choice is between consistency and availability. 2PC’s blocking nature means that in the face of a partition, it prioritizes consistency by halting progress, thereby sacrificing availability. Many modern applications, however, are designed to be highly available — an e-commerce site would rather be available to accept an order even if some backend inventory processing is delayed. By its nature, 2PC is a “CP” system, while many microservice architectures are striving to be “AP” systems. Forcing a CP pattern onto an AP problem creates a deep architectural mismatch, which is why it so often feels like a painful and unnatural fit.</p><h3>Enter the Saga: A Story of Local Victories and Graceful Retreats</h3><p>If 2PC is a rigid, top-down command structure, the <strong>Saga pattern</strong> is a completely different philosophy. It’s not a technical protocol but a design pattern for managing long-running business processes. Instead of one giant, all-or-nothing transaction, a saga is a sequence of smaller, independent, local transactions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/0*UsJwcb8-O-LKzHsC" /><figcaption>Saga Pattern on <a href="https://commons.wikimedia.org/wiki/File:Saga_pattern-UML.png">Wikipedia</a></figcaption></figure><p>Imagine a multi-stage rocket launch. Each stage is a self-contained unit that fires, performs its function, and then triggers the next stage. The whole process is a story — a saga — of sequential successes. But what if a stage fails? The system doesn’t just freeze. Instead, a specific, pre-planned abort sequence is initiated — perhaps the escape tower fires to pull the capsule to safety. This is the essence of a saga: a series of local victories with a plan for a graceful retreat.</p><h4>The Core Components of a Saga</h4><ul><li><strong>Local Transactions:</strong> Each microservice involved in the saga performs its own atomic transaction against its own database. The Order Service creates an order and commits it. The Payment Service processes a payment and commits it. Each step is a complete, self-contained unit of work. This avoids the long-lived, cross-service locks that plague 2PC.</li><li><strong>Compensating Transactions:</strong> This is the “graceful retreat” mechanism. For every forward step in the saga, you must define a corresponding backward step to undo it. If the ProcessPayment step succeeds but the subsequent ShipOrder step fails, the saga invokes a RefundPayment compensating transaction. This isn&#39;t a technical database rollback; it&#39;s an explicit business action that reverses the effect of a previous action. Failure is no longer a generic exception; it&#39;s a business event like InventoryUnavailable that must be handled with specific business logic. This forces a critical collaboration between engineers and business stakeholders to define the &quot;unhappy paths,&quot; leading to more robust and realistic systems.</li><li><strong>Idempotency is Non-Negotiable:</strong> In a distributed system, messages can be delivered more than once due to retries after transient failures. Therefore, all saga steps — both the forward actions and the compensating actions — must be <em>idempotent</em>. This means an operation can be executed multiple times without changing the result beyond the initial execution. For example, a processPayment API should be designed so that calling it five times with the same transaction ID only results in one charge. This is often achieved by checking if a transaction ID has already been processed before executing the business logic.</li></ul><h3>Choosing Your Adventure: Orchestration vs. Choreography</h3><p>Once you decide to use a saga, you need to decide how to coordinate the flow of local transactions. There are two primary approaches, each with a distinct philosophy and its own set of trade-offs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9ea6rDKHGIq6wY9A.png" /><figcaption>Orchestration vs Choreography on <a href="https://solace.com/blog/microservices-choreography-vs-orchestration/">Solace</a></figcaption></figure><h4>Orchestration: The Conductor and the Orchestra</h4><p>In this model, a central service — the “Orchestrator” — acts as a conductor leading an orchestra. It knows the entire score of the business process and explicitly tells each participant service when to perform its part.</p><p><strong>How it Works:</strong> The orchestrator sends a command to the first service (e.g., “Reserve Inventory”). When that service completes and replies, the orchestrator sends a command to the next service (e.g., “Process Payment”). If any step fails, the orchestrator is responsible for commanding the necessary compensating transactions in reverse order.</p><p><strong>When to Use It:</strong></p><ul><li><strong>Complex Workflows:</strong> Orchestration is ideal for sagas with many steps, conditional branching (if-then-else logic), parallel execution paths, or complex error-handling requirements.</li><li><strong>Centralized Visibility:</strong> When you need a single, explicit, and easily observable definition of the entire business process, the orchestrator provides that “single source of truth.” This dramatically simplifies debugging and monitoring.</li><li><strong>Brownfield Development:</strong> If you’re trying to coordinate existing microservices into a new workflow, it’s often easier to introduce a new orchestrator than to modify each existing service to participate in a choreographed flow.</li></ul><p><strong>Potential Pitfalls:</strong></p><ul><li><strong>Risk of Over-Centralization:</strong> The orchestrator can become a “god object” that knows too much about all the other services, creating a new form of coupling and a potential development bottleneck.</li><li><strong>Single Point of Failure (Managed):</strong> While modern orchestration tools like AWS Step Functions or Temporal are highly available and solve the <em>operational</em> single point of failure problem, the orchestrator can still be an <em>architectural</em> single point of failure if all business process logic is centralized there.</li></ul><h4>Choreography: The Flash Mob</h4><p>In this model, there is no central conductor. The workflow emerges from the participants themselves, like a flash mob where each dancer knows to start their routine when the person next to them finishes.</p><p><strong>How it Works:</strong> Each service performs its local transaction and then publishes an event to a message broker. Other services subscribe to these events and react accordingly. For example, the Order Service publishes an OrderCreated event. The Payment Service listens for this event, processes the payment, and then publishes a PaymentProcessed event. The flow is decentralized and event-driven.</p><p><strong>When to Use It:</strong></p><ul><li><strong>Simple, Linear Workflows:</strong> Choreography works well for sagas with a small number of participants and a straightforward, linear sequence of steps.</li><li><strong>Maximum Decoupling:</strong> If the highest priority is to keep services loosely coupled and autonomous, choreography is the purest approach. Services only need to know about the events they care about, not the other services themselves.</li><li><strong>Event-Driven Domains:</strong> It’s a natural fit for systems that are already built around an event-driven architecture.</li></ul><p><strong>Potential Pitfalls:</strong></p><ul><li><strong>Lack of Visibility:</strong> The biggest challenge with choreography is understanding the end-to-end business process. The logic is scattered across multiple services, making it incredibly difficult to visualize, debug, or modify the overall flow.</li><li><strong>Cyclic Dependencies:</strong> Without a central controller, it’s possible to create dangerous cycles where an event from Service A triggers B, which triggers C, which in turn triggers A again, leading to an infinite loop.</li></ul><p>The choice between these two patterns often reflects a company’s organizational structure, a phenomenon known as Conway’s Law. Organizations with strong central architecture or platform teams may find orchestration a more natural fit, as that team can own the orchestrator. Conversely, organizations with highly autonomous, “you build it, you run it” teams may gravitate towards choreography, as it aligns with their decentralized philosophy. The best pattern is often the one that mirrors how your teams already communicate and collaborate.</p><h3>Sagas in the Wild: A Real-World E-commerce Checkout</h3><p>Let’s make this concrete by walking through a typical e-commerce order process:<strong> 1) Create Order, 2) Reserve Inventory, 3) Process Payment, and 4) Ship Order</strong>.</p><h4>The Unsung Hero: The Transactional Outbox Pattern</h4><p>Before we can even start the saga, we have to solve a critical problem: how does a service atomically update its own database <em>and</em> publish an event to a message broker? You can’t use a distributed transaction to span your database and your broker (like Kafka or RabbitMQ). This leads to the infamous “dual-write” problem:</p><ul><li>If you publish the event <em>before</em> committing the database transaction, a crash could leave you with a “phantom” event for a state change that never actually happened.</li><li>If you publish the event <em>after</em> committing, a crash between the commit and the publish could cause a missed event, silently breaking your saga.</li></ul><p>The solution is the <strong>Transactional Outbox pattern</strong>. Here’s how it works:</p><ul><li>Within a single, local database transaction, you write your business data (e.g., insert a new row in the orders table) AND you insert a record representing the event (e.g., an OrderCreated event message) into a special outbox table.</li><li>Because this happens in one transaction, it’s fully atomic. Both records are saved, or neither is.</li><li>A separate, simple, and reliable poller process constantly scans the outbox table for new event records.</li><li>When the poller finds an event, it publishes it to the message broker and then marks the event in the outbox table as “published.”</li></ul><p>This pattern guarantees that an event is published reliably <em>if and only if</em> the corresponding business transaction was successfully committed. It is the foundational piece that makes reliable, event-driven sagas possible, especially in choreographed systems.</p><h4>Orchestration Example (Python-esque Pseudocode)</h4><p>Using a workflow engine like Temporal, the logic is centralized and explicit.</p><pre># Using a Temporal-like SDK<br>class OrderWorkflow:<br>    def execute(self, order_details):<br>        # Define compensations in a Saga object<br>        saga = Saga()<br>        try:<br>            # Step 1: Reserve Inventory<br>            saga.add_compensation(activities.release_inventory, order_details.item_id)<br>            yield activities.reserve_inventory(order_details.item_id)<br><br>            # Step 2: Process Payment<br>            saga.add_compensation(activities.refund_payment, order_details.payment_id)<br>            yield activities.process_payment(order_details.payment_id, order_details.amount)<br><br>            # Step 3: Ship Order (this is a pivot transaction, no compensation)<br>            yield activities.ship_order(order_details.order_id)<br><br>            yield activities.update_order_status(order_details.order_id, &quot;COMPLETED&quot;)<br><br>        except Exception as e:<br>            # If anything fails, the orchestrator runs all compensations in reverse order<br>            yield saga.compensate()<br>            yield activities.update_order_status(order_details.order_id, &quot;FAILED&quot;)<br>            raise e</pre><h4>Choreography Example (Python-esque Pseudocode)</h4><p>Here, the logic is distributed across services.</p><pre># OrderService<br>class OrderService:<br>    def create_order(self, order_details):<br>        # Uses Transactional Outbox to save order and publish event<br>        db.save_order_and_outbox_event(<br>            order_details,<br>            event_type=&quot;OrderCreated&quot;,<br>            payload=order_details<br>        )<br><br># InventoryService<br>class InventoryService:<br>    @listens_to(&quot;OrderCreated&quot;)<br>    def handle_order_created(self, event):<br>        try:<br>            inventory = db.reserve_stock(event.item_id)<br>            db.publish_outbox_event(<br>                event_type=&quot;InventoryReserved&quot;,<br>                payload={&quot;order_id&quot;: event.order_id}<br>            )<br>        except InsufficientStockError:<br>            db.publish_outbox_event(<br>                event_type=&quot;InventoryReservationFailed&quot;,<br>                payload={&quot;order_id&quot;: event.order_id}<br>            )<br><br>    @listens_to(&quot;PaymentFailed&quot;)<br>    def handle_payment_failed(self, event):<br>        # Compensation logic<br>        db.release_stock(event.item_id)<br><br># PaymentService<br>class PaymentService:<br>    @listens_to(&quot;InventoryReserved&quot;)<br>    def handle_inventory_reserved(self, event):<br>        try:<br>            payment_id = payment_gateway.charge(event.amount)<br>            db.publish_outbox_event(<br>                event_type=&quot;PaymentProcessed&quot;,<br>                payload={&quot;order_id&quot;: event.order_id, &quot;payment_id&quot;: payment_id}<br>            )<br>        except PaymentGatewayError:<br>            db.publish_outbox_event(<br>                event_type=&quot;PaymentFailed&quot;,<br>                payload={&quot;order_id&quot;: event.order_id}<br>            )</pre><h3>Building for Failure: Testing, Optimizing, and Observing Your Sagas</h3><p>Sagas are elegant on a whiteboard but notoriously difficult to operate in production. Success hinges on treating failure not as an edge case, but as a primary concern. This requires a robust strategy for testing, observability, and performance optimization.</p><h4>Testing Your Saga: Beyond the Happy Path</h4><p>Simple unit tests aren’t enough. You need a multi-layered testing strategy that rigorously validates your failure modes.</p><ul><li><strong>Unit &amp; Component Tests:</strong> Test your local transaction logic and, just as importantly, your compensation logic in complete isolation. Ensure refundPayment actually works.</li><li><strong>Integration Tests:</strong> Test the seams between your services. For a choreographed saga, this means verifying that your service correctly consumes an upstream event and produces the correct downstream event. For an orchestrated saga, test that the orchestrator correctly invokes a service and handles its response. You can mock the message broker and other services for these tests.</li><li><strong>End-to-End (E2E) Tests:</strong> These are essential but should be used sparingly as they are slow and brittle. Focus on a few critical business scenarios: the full “happy path” success case, and one or two well-defined failure paths, such as a payment failure or an out-of-stock scenario, to ensure the entire compensation chain works as expected.</li></ul><h4>Playing with Fire: A Mini-Playbook for Chaos Engineering</h4><p>How can you be sure your compensations will actually run when a service goes down at 3 AM? You can’t just hope; you have to test it. Chaos Engineering is the practice of intentionally injecting failures into your system in a controlled environment to build confidence in its resilience.</p><p>Here’s a simple playbook for a saga:</p><ul><li><strong>Form a Hypothesis:</strong> “If the Payment Service experiences a 5-minute network outage during an order checkout, the saga will correctly trigger the releaseInventory and cancelOrder compensations, the order will terminate in a &#39;FAILED&#39; state, and the customer will see a clear error message, all within 90 seconds.&quot;</li><li><strong>Design the Experiment:</strong> In a staging environment that mirrors production, use a tool like Gremlin or custom scripting to block all network traffic to and from the Payment Service for a 5-minute window.</li><li><strong>Measure the Impact:</strong> While the experiment is running, trigger a new order. Monitor your system’s behavior. Did the orchestrator (or the relevant services in a choreographed flow) detect the failure via a timeout? Were the compensation events published and consumed? Check your logs and tracing dashboards to see the flow. Did the order’s final state in the database match your hypothesis? This process turns “I think it will work” into “I have proven it works”.</li></ul><h4>Observability: Your Saga’s GPS</h4><p>When a saga fails, you need to know what happened, where it happened, and why. Without excellent observability, you will be flying blind.</p><ul><li><strong>Distributed Tracing is Mandatory:</strong> This is the single most important tool for debugging sagas. A unique <strong>Correlation ID</strong> must be generated at the very start of the saga and propagated through the headers of every single command, event, and API call that is part of that transaction. Tools like Jaeger or Zipkin can then use this ID to stitch together a complete, end-to-end trace of a single saga instance across all microservices, showing you exactly where it failed.</li><li><strong>Structured Logging:</strong> Your logs are your narrative. Log every significant step of the saga: “SagaStarted,” “ExecutingStep: ProcessPayment,” “CompensationTriggered: RefundPayment.” Crucially, every log entry must include the Correlation ID, OrderID, and any other relevant business identifiers. This allows you to filter logs for a single failed transaction and reconstruct its story.</li><li><strong>Business-Level Metrics (The Dashboard):</strong> Traditional infrastructure metrics like CPU and memory are not enough. Your saga dashboard must tell a business story. Monitor these key metrics: <strong>Saga success rate vs. failure rate</strong>, <strong>average and p99 saga duration</strong>, and <strong>execution count for each specific step</strong> and, most importantly, each <strong>compensation action</strong>. A sudden spike in the refundPayment compensation count is a powerful early warning that something is wrong downstream, long before any infrastructure alarms go off.</li></ul><h4>Performance and Optimization</h4><ul><li><strong>Parallelize Steps:</strong> In an orchestrated saga, if two steps are independent (e.g., checking for fraud and verifying a shipping address), execute them in parallel to reduce overall latency.</li><li><strong>Choose the Right Messaging Technology:</strong> For very high-throughput systems, a partitioned, log-based broker like Apache Kafka may offer better performance than a traditional queue-based broker like RabbitMQ.</li><li><strong>Use Semantic Locking:</strong> To prevent race conditions where two sagas might try to modify the same resource concurrently, you can implement an application-level lock. For example, before processing a payment, an order’s status could be changed to PAYMENT_PENDING. If another process (like a cancellation request) tries to act on that order, it will see the pending status and can either wait or fail, preventing inconsistent data reads.</li></ul><h3>Further Reading</h3><p>Mastering distributed transactions is an ongoing journey. As you dive deeper, explore these foundational concepts and tools that are closely related to the Saga pattern:</p><ul><li>CAP Theorem.</li><li>Event Sourcing.</li><li>Idempotent Receiver / Message Consumer.</li><li>Workflow Engines (Orchestration Tools).</li></ul><h3>Conclusion: It’s Complicated, But Not Impossible</h3><p>Distributed transactions are one of the hardest problems in microservice architectures. The classic Two-Phase Commit protocol, while ensuring strong consistency, imposes blocking and performance penalties that are often unacceptable in modern, highly available systems. The Saga pattern offers a more resilient alternative, trading immediate consistency for eventual consistency by breaking down a business process into a series of local transactions with corresponding compensations.</p><p>The choice between the centralized control of Orchestration and the decentralized autonomy of Choreography is a critical design decision that depends on your workflow’s complexity and your team’s structure. But regardless of the approach, success with sagas is not a given. It demands a profound shift in mindset — one that embraces failure as a core part of the business process and invests heavily in the pillars of idempotency, robust testing, and deep observability.</p><blockquote>So go forth and build resilient systems. And if you find yourself debugging a failed compensating transaction at 3 AM, just remember: at least you’re not trying to get a quorum from a partitioned coordinator. Happy Coding!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=466f272b8cba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Queues, Streams, and the Art of Backpressure.]]></title>
            <link>https://bagasdisini.medium.com/queues-streams-and-the-art-of-backpressure-9981084ce5eb?source=rss-20d596ba5555------2</link>
            <guid isPermaLink="false">https://medium.com/p/9981084ce5eb</guid>
            <category><![CDATA[message-queue]]></category>
            <category><![CDATA[data-streaming]]></category>
            <category><![CDATA[stream]]></category>
            <category><![CDATA[backpressure]]></category>
            <category><![CDATA[queue]]></category>
            <dc:creator><![CDATA[Muhammad Bagas Sudibyo]]></dc:creator>
            <pubDate>Sat, 28 Jun 2025 03:48:16 GMT</pubDate>
            <atom:updated>2025-06-28T05:27:17.458Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*3cD3GRvyQ2_-3vDlwK8Rvw.png" /><figcaption>I Love Lucy: Factory Scene on <a href="https://www.youtube.com/watch?v=K3axU2b0dDk">YouTube</a></figcaption></figure><p>There’s a scene in the classic sitcom <em>I Love Lucy</em> that every software architect should be forced to watch. Lucy and Ethel are working at a chocolate factory, tasked with wrapping candies as they come down a conveyor belt. At first, it’s easy. The chocolates arrive at a manageable pace. But then the belt speeds up. And speeds up again. Soon, the two are overwhelmed, frantically stuffing chocolates into their mouths, hats, and blouses in a desperate, comical attempt to hide the evidence of their failure. The conveyor belt, oblivious to their struggle, just keeps on sending more.</p><p>This scene is the perfect, visceral metaphor for a fundamental challenge in distributed systems: the <strong>producer-consumer mismatch</strong>. In our world, the conveyor belt is a service generating data, events, or tasks. Lucy and Ethel are the downstream services meant to process them. And much like in the chocolate factory, the producer is often blissfully unaware of the consumer’s capacity. Without a way for the consumer to signal “Hey, slow down!” the result is chaos: dropped data, exhausted memory, cascading failures, and a system that eventually collapses under its own unmanaged load.</p><p>This is where we move from comedy to engineering. The resistance that Lucy and Ethel so desperately needed is what we call <strong>backpressure</strong>. The term itself is borrowed from the physical world of fluid dynamics, where it describes a force that opposes the desired flow of a fluid in a pipe. Too much backpressure in an engine can choke it, but a little bit of well-managed pressure can actually improve efficiency through a process called scavenging.</p><p>This duality is at the heart of our work. Backpressure in software isn’t just a failure state; it’s a necessary <strong>feedback mechanism</strong>, a form of communication that allows a system to find its natural rhythm. The absence of backpressure is not a feature; <strong>it’s a bug</strong>. It’s the design equivalent of a conveyor belt with no off-switch. Learning to understand, manage, and apply this pressure is not just a technical skill — it is an art. It’s the art of building systems that don’t just process data, but do so with balance, resilience, and grace.</p><p>To master this art, we first need to understand the rivers through which our data flows. These are the two great paradigms for asynchronous communication: <strong>message queues</strong> and <strong>data streams</strong>.</p><h3>The Two Great Rivers of Data</h3><p>At the core of any decoupled, scalable architecture lies the need for services to communicate without being tightly bound to one another. This asynchronous communication is typically facilitated by two distinct but often confused patterns: <strong>message queues</strong> and <strong>data streams</strong>. They are the channels we build, the rivers we carve through our systems. While both move data from one point to another, their underlying philosophies are fundamentally different. Choosing the right one is less about picking a technology and more about understanding the soul of the data you’re moving.</p><h4><strong>The Orderly Procession — Understanding Message Queues</strong></h4><p>Imagine a bank. Customers arrive and form a single-file line to be served by one of several tellers. Each customer represents a discrete task: a deposit, a withdrawal, a query. This is the essence of a message queue.</p><p>A message queue is a form of asynchronous, service-to-service communication designed to manage individual units of work. An application, the <strong>producer</strong>, sends a message — a self-contained package of data representing a task — to the queue. The queue, a temporary buffer, holds onto that message until another application, the <strong>consumer</strong>, is ready to process it.</p><p>Here are the key characteristics:</p><ul><li><strong>Communication Model:</strong> Typically <strong>point-to-point</strong>, or one-to-one. Even if multiple consumers are listening, each message is processed only once by a single consumer. This is often called the “competing consumers” pattern, perfect for distributing a workload.</li><li><strong>Data Consumption:</strong> Message queues operate on a principle of <strong>destructive reads</strong>. Once a consumer successfully processes a message and acknowledges it, the message is permanently removed from the queue. This ensures a task is performed exactly once.</li><li><strong>Data Retention:</strong> The data is <strong>transient</strong>. The queue’s job is to hold the task only as long as necessary to ensure reliable delivery.</li><li><strong>Core Philosophy:</strong> A message in a queue is an <strong>imperative command</strong>: “Do this task.” It’s a piece of work to be completed.</li></ul><p>Common examples of this pattern are implemented by technologies like RabbitMQ and Amazon SQS.</p><h4><strong>The Never-Ending Flow — Demystifying Data Streams</strong></h4><p>Now, shift your mental model from a bank queue to a river or a radio broadcast. A river flows continuously, and anyone can dip a bucket in to take some water without affecting the river itself. This is the world of data streams.</p><p>A data stream is a continuous, never-ending flow of immutable events ordered in time. A producer writes records to the stream, which is essentially a durable, append-only log.</p><p>Here are its defining traits:</p><ul><li><strong>Communication Model:</strong> A <strong>publish-subscribe (pub/sub)</strong> model, where a single event is broadcast to many interested consumers simultaneously.</li><li><strong>Data Consumption:</strong> Streams use <strong>non-destructive reads</strong>. When a consumer reads an event, the event is not removed. Instead, the consumer simply advances its own private cursor, or “offset.”</li><li><strong>Data Retention:</strong> The data is <strong>persistent</strong> for a configurable retention period (from hours to forever), acting as a replayable history of everything that has happened. Multiple, independent consumer groups can read from the same stream at their own pace.</li><li><strong>Core Philosophy:</strong> An event in a stream is a <strong>declarative fact</strong>: “This thing happened.” It’s a piece of information to be known.</li></ul><p>This makes streams the backbone of real-time analytics and event sourcing architectures. Technologies like Apache Kafka and Amazon Kinesis are the canonical examples of this pattern.</p><h3>A Tale of Two Systems — Choosing the Right Path</h3><p>The choice between a message queue and a data stream is a fundamental architectural decision. The core question to ask is: <strong>Is my data a job to be done, or a fact to be known?.</strong></p><p><strong>Use a Message Queue when:</strong></p><ul><li>You are handling discrete, <strong>individual</strong> tasks (e.g., sending an email, processing a payment, generating a report).</li><li>Each task should be processed <strong>exactly once</strong> by a single worker.</li><li>Your primary goal is to <strong>decouple services</strong> and reliably distribute a workload across a pool of consumers.</li><li>You don’t need to replay messages or have multiple, independent systems react to the same piece of data.</li></ul><p><strong>Use a Data Stream when:</strong></p><ul><li>You are capturing a <strong>continuous</strong> flow of events (e.g., user activity logs, IoT sensor data, financial transactions).</li><li>You need <strong>multiple, independent consumer applications</strong> to react to the same event stream for different purposes (e.g., analytics, monitoring, machine learning).</li><li>The ability to <strong>replay historical data</strong> is important for your architecture (e.g., for event sourcing or training new models).</li><li>You are building a real-time system that acts as a single source of truth for the entire organization.</li></ul><p>Ultimately, many modern systems use both. They might use a queue to manage a specific command and then publish an event to a stream once that command is successfully completed.</p><h3>Real-World Use Cases</h3><p>Let’s look at how major tech companies apply these concepts.</p><ul><li><strong>E-commerce Order Processing (Message Queues):</strong> When you place an order online, the system pushes an “Order Placed” message to a queue. Several services listen in: an inventory service updates stock, a payment service processes the charge, and a notification service sends your confirmation email. Each service works independently, ensuring that even if the payment gateway is slow, your order confirmation isn’t held up. This decoupling makes the system robust and scalable during huge sales events.</li><li><strong>Ride-Sharing like Uber (Data Streams):</strong> Uber relies heavily on Apache Kafka to manage the immense flow of real-time data. When you request a ride, a stream of events is generated: your location, driver locations, traffic data, and pricing information. Multiple microservices consume this stream simultaneously to match you with a driver, calculate your ETA, and set the price, all without direct, blocking calls between services.</li><li><strong>Content Streaming like Netflix &amp; Spotify (Queues and Streams):</strong> Netflix uses Amazon SQS queues to handle spikes in usage, like when a new show is released. Viewing activity events are buffered in queues, preventing services from crashing under the load. Spotify uses data streams to power its personalized experiences. Your listening history, skips, and playlist additions are all events in a stream. This data feeds algorithms that create personalized playlists like “Discover Weekly” and provide artists with detailed analytics about their audience.</li></ul><h3>A Touch of Code: Producers and Consumers</h3><p>To make this more concrete, let’s look at simplified code examples.</p><h4>RabbitMQ Producer &amp; Consumer (Node.js)</h4><p>A producer sends a task to a queue.</p><pre>// producer.js<br>const amqp = require(&#39;amqplib&#39;);<br><br>async function sendTask() {<br>  const connection = await amqp.connect(&#39;amqp://localhost&#39;);<br>  const channel = await connection.createChannel();<br>  const queue = &#39;task_queue&#39;;<br>  const message = &#39;Process this image!&#39;;<br><br>  await channel.assertQueue(queue, { durable: true });<br>  channel.sendToQueue(queue, Buffer.from(message), { persistent: true });<br>  console.log(`[x] Sent &#39;${message}&#39;`);<br>  <br>  setTimeout(() =&gt; {<br>    connection.close();<br>    process.exit(0);<br>  }, 500);<br>}<br><br>sendTask();</pre><p>A consumer picks up the task from the queue to process it.</p><pre>// consumer.js<br>const amqp = require(&#39;amqplib&#39;);<br><br>async function receiveTask() {<br>  const connection = await amqp.connect(&#39;amqp://localhost&#39;);<br>  const channel = await connection.createChannel();<br>  const queue = &#39;task_queue&#39;;<br><br>  await channel.assertQueue(queue, { durable: true });<br>  console.log(`[*] Waiting for messages in ${queue}. To exit press CTRL+C`);<br><br>  channel.consume(queue, (msg) =&gt; {<br>    console.log(`[x] Received ${msg.content.toString()}`);<br>    // Acknowledge the message was received and processed<br>    channel.ack(msg);<br>  }, { noAck: false });<br>}<br><br>receiveTask();</pre><h4>Kafka Producer &amp; Consumer (Python)</h4><p>A producer sends an event to a Kafka topic.</p><pre># producer.py<br>from kafka import KafkaProducer<br>import json<br><br>producer = KafkaProducer(bootstrap_servers=&#39;localhost:9092&#39;,<br>                         value_serializer=lambda v: json.dumps(v).encode(&#39;utf-8&#39;))<br><br>event = {&#39;user_id&#39;: &#39;123&#39;, &#39;action&#39;: &#39;clicked_play&#39;}<br>producer.send(&#39;user-activity&#39;, event)<br>producer.flush() # Ensure all messages are sent<br><br>print(f&quot;Sent event: {event}&quot;)</pre><p>A consumer reads the event from the topic.</p><pre># consumer.py<br>from kafka import KafkaConsumer<br>import json<br><br>consumer = KafkaConsumer(&#39;user-activity&#39;,<br>                         bootstrap_servers=&#39;localhost:9092&#39;,<br>                         auto_offset_reset=&#39;earliest&#39;,<br>                         group_id=&#39;analytics-group&#39;,<br>                         value_deserializer=lambda m: json.loads(m.decode(&#39;utf-8&#39;)))<br><br>for message in consumer:<br>    print(f&quot;Received event: {message.value}&quot;)</pre><h3>The Gentle Pushback — The Art of Backpressure</h3><p>Whether you choose a queue or a stream, you will eventually face the “I Love Lucy” problem. This is where we must master the art of backpressure. Backpressure is a <strong>feedback mechanism</strong> that allows a system to self-regulate, ensuring stability in the face of unpredictable load. Ignoring it is a recipe for disaster.</p><p>Here are the primary strategies for applying it:</p><ul><li><strong>Buffering:</strong> The simplest approach is to place a buffer (like a queue) between services to absorb temporary spikes. However, an <strong>unbounded buffer</strong> is dangerous; if the producer is consistently faster, the buffer will grow until it exhausts memory. Always use a <strong>bounded buffer</strong> with a fixed capacity.</li><li><strong>Throttling / Rate Limiting:</strong> This involves explicitly restricting the rate at which the producer can send requests. This is often done at the API gateway level to protect the entire system, using algorithms like the <a href="https://en.wikipedia.org/wiki/Token_bucket">Token Bucket</a> or <a href="https://en.wikipedia.org/wiki/Leaky_bucket">Leaky Bucket</a>.</li><li><strong>Reactive Backpressure:</strong> This is a cooperative model where the consumer explicitly signals its capacity to the producer. The consumer requests a certain number of items, and the producer is obligated not to send more until requested. This creates a self-regulating system where flow is dictated by the consumer’s real-time processing speed.</li><li><strong>Load Shedding:</strong> When all else fails, the system must deliberately drop or reject requests to protect its stability. This is a planned, graceful degradation of service. For example, an e-commerce site might drop “view product” requests to prioritize “complete checkout” requests during a massive traffic spike. This is often implemented with a <strong>Circuit Breaker</strong> pattern, which temporarily stops traffic to a failing service to allow it to recover.</li></ul><h3>Testing and Optimization</h3><p>Designing a resilient system is one thing; ensuring it performs under pressure is another. Testing and continuous optimization are not afterthoughts — they are core to the process.</p><h4>Monitoring is Key</h4><p>You can’t optimize what you can’t measure. Before tuning, establish a robust monitoring pipeline.</p><p><strong>Key Metrics:</strong> For any queue or stream-based system, you must track:</p><ul><li><strong>Queue Length / Consumer Lag:</strong> How many messages are waiting? Is the lag growing over time? This is the most direct indicator of a consumer bottleneck.</li><li><strong>Message Rates:</strong> Track the rate of published and consumed messages to understand the flow.</li><li><strong>Resource Utilization:</strong> Monitor CPU, memory, and disk I/O on your brokers and consumers. High CPU on a consumer might indicate inefficient processing logic, while high disk I/O on a broker could point to a need for faster storage (like SSDs).</li></ul><p><strong>Monitoring Tools:</strong> The combination of <strong>Prometheus</strong> for metrics collection and <strong>Grafana</strong> for visualization is a powerful, open-source standard for monitoring systems like RabbitMQ and Kafka. Other popular commercial tools include Datadog, New Relic, and Sematext, which offer comprehensive dashboards and alerting.</p><h4>Performance Tuning</h4><p>Once you have visibility, you can start tuning. Optimization is a balancing act between throughput, latency, and durability.</p><p><strong>Tune the Producer:</strong></p><ul><li><strong>Batching:</strong> Group smaller messages into larger batches (batch.size in Kafka) to reduce network overhead and improve throughput. This often comes at the cost of slightly higher latency, as the producer waits to fill the batch (linger.ms in Kafka).</li><li><strong>Compression:</strong> Enable message compression (snappy or lz4 are common choices) to reduce data size and network load, at the cost of some CPU overhead on both the producer and consumer.</li></ul><p><strong>Tune the Consumer:</strong></p><ul><li><strong>Parallelism:</strong> The easiest way to increase consumption speed is to scale out. For Kafka, increase the number of consumers in a consumer group (up to the number of partitions in the topic). For RabbitMQ, add more competing consumers to the queue.</li><li><strong>Fetch Size:</strong> Tune how much data a consumer requests at once (fetch.min.bytes and max.poll.records in Kafka). Fetching larger batches can improve throughput but may increase memory usage on the consumer.</li></ul><p><strong>Tune the Broker:</strong></p><ul><li><strong>Hardware:</strong> Ensure your brokers have sufficient resources. Use SSDs for storage, as they dramatically improve I/O-heavy operations.</li><li><strong>Partitions (Kafka):</strong> The number of partitions in a topic is the upper limit for consumer parallelism. Choose a number that allows for future scaling.</li></ul><h3>Finding the System’s Natural Rhythm</h3><p>The journey from a simple conveyor belt to a resilient, self-regulating system is a journey of increasing sophistication. It begins with the fundamental choice between the orderly procession of a queue and the never-ending flow of a stream — a choice rooted in the very purpose of your data. But regardless of the path chosen, we inevitably arrive at the challenge of managing flow.</p><p>Backpressure is not the problem; it is the solution. It is the language our systems use to negotiate their limits and find a sustainable pace. Mastering this art is about layering defenses: using buffers as shock absorbers, rate limits as gatekeepers, reactive protocols as a nervous system, and load shedding as a last-resort survival instinct.</p><p>Building great software is not about chasing the highest possible throughput at all costs. It is about finding the sweet spot between speed and stability, about building systems that adapt gracefully to stress rather than shattering under it. It is about creating a predictable, reliable rhythm that serves both our users and the engineers who must live with our creations. By embracing the gentle pushback, we can design systems that don’t just work, but endure.</p><h3>Further Reading</h3><p>To dive deeper, explore these concepts and resources.</p><p><strong>Key Concepts:</strong> Event Sourcing, <a href="https://en.wikipedia.org/wiki/Circuit_breaker_design_pattern">Circuit Breaker Pattern</a>, <a href="https://en.wikipedia.org/wiki/Reactive_Streams">Reactive Streams</a>, Idempotent Consumers, <a href="https://en.wikipedia.org/wiki/Dead_letter_queue">Dead Letter Queues (DLQs)</a>.</p><p><strong>Essential Books:</strong></p><ul><li><em>Designing Data-Intensive Applications</em> by Martin Kleppmann</li><li><em>Kafka: The Definitive Guide</em> by Neha Narkhede, Gwen Shapira, &amp; Todd Palino</li><li><em>Enterprise Integration Patterns</em> by Gregor Hohpe &amp; Bobby Woolf</li><li><em>Building Microservices</em> by Sam Newman</li></ul><blockquote>Building robust backend systems is an art form. It’s about understanding the flow of data, anticipating the points of friction, and designing systems that can gracefully handle the pressures of the real world. So go forth, build resilient systems, and may your queues never overflow. Happy coding!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9981084ce5eb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>