<?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 Hugo Vantighem on Medium]]></title>
        <description><![CDATA[Stories by Hugo Vantighem on Medium]]></description>
        <link>https://medium.com/@hugo.vantighem?source=rss-a4b7db4e2fc8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*UAa710xRR8LpaRvp</url>
            <title>Stories by Hugo Vantighem on Medium</title>
            <link>https://medium.com/@hugo.vantighem?source=rss-a4b7db4e2fc8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 05:40:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hugo.vantighem/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[The Day I Stopped Arguing About Choreography vs Orchestration]]></title>
            <link>https://levelup.gitconnected.com/the-day-i-stopped-arguing-about-choreography-vs-orchestration-9a976b1ae32c?source=rss-a4b7db4e2fc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a976b1ae32c</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Hugo Vantighem]]></dc:creator>
            <pubDate>Tue, 28 Jul 2026 01:55:39 GMT</pubDate>
            <atom:updated>2026-07-28T01:55:39.168Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>“The danger is that it’s very easy to make nicely decoupled systems with event notification, without realizing that you’re losing sight of that larger-scale flow, and thus set yourself up for trouble in future years.”</blockquote><blockquote><em>Martin Fowler, </em><a href="https://martinfowler.com/articles/201701-event-driven.html">What do you mean by “Event-Driven?”</a><em> (2017)</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jNxBXZ4L0ncB6a7ArdsXLA.png" /><figcaption>Generated by the author using Gemini</figcaption></figure><p>Let me say the quiet part out loud: more event-driven systems than anyone admits aren’t decoupled by design. They’re decoupled by avoidance.</p><p>Few teams actually sit in a room, weigh choreography against orchestration, and pick choreography on the merits. In my experience, the deciding factor is usually far more practical than architectural: nobody wants to build and own an orchestrator. And honestly, I get it. I’ve built the home-grown one: the tidy state machine that grows, release by release, into a God Service every request waits on. I’ve reached for Temporal when I got tired of maintaining my own. I know what orchestration costs. So when a team reaches for pure events instead, I don’t blame them.</p><p>But it usually goes the same way. The happy path ships, and it’s gorgeous: services react to events, nobody’s coupled to anybody, adding a consumer is free. Then the first real failure lands. Payment fails after inventory’s already reserved and the “thanks for your order” email is already gone. And the part nobody wanted to build, the compensation, the “who undoes what,” has no owner. It was never designed. It’s smeared across five services that each did their job perfectly.</p><p>The danger Fowler named up top has been chewed over a hundred times since, by Hohpe, by Chris Richardson, by every conference talk on the subject. I’m not here to relitigate it. I’ve stood in both camps long enough to be tired of the tribalism anyway. So instead of planting a flag in one, I tried to reconcile them. Which meant dropping the question everyone argues about, “choreography or orchestration?”, for a better one:</p><p><strong>Where do we actually need coordination?</strong></p><p>Once I looked, the answer was almost embarrassing:</p><ul><li>The happy path needs almost none.</li><li>The failure path needs almost all of it.</li></ul><p>That reconciliation is the whole article: choreograph the ordinary, orchestrate the exceptions. When you take the orchestrator off the happy path, four things lose their home:</p><ul><li><strong>Visibility:</strong> one place that knows where every process stands.</li><li><strong>An explicit state machine:</strong> the flow written down, not implied.</li><li><strong>Explicit compensation:</strong> a readable answer to “what do we undo?”</li><li><strong>One place to reason</strong> about the process as a whole.</li></ul><p>The rest of this is about giving those four a home again, without putting a coordinator back on the critical path. One admission up front, so you read the rest fairly: in most systems I’d still reach for a real workflow engine. This is what I found when I asked what the leaner, reconciled version would even look like.</p><h3>The happy path was never the hard part</h3><p>Start with pure choreography, because on the nominal path it genuinely shines.</p><pre>OrderCreated ──▶ Payment ──▶ PaymentSucceeded ──▶ Shipping ──▶ Shipped</pre><p>Each service subscribes to the events it cares about, does its work, and publishes what happened. Order doesn&#39;t know Payment exists. Payment doesn&#39;t know about Shipping. Adding a consumer is free:</p><pre>OrderCreated ──┬──▶ Fraud check<br>               ├──▶ Analytics<br>               └──▶ Recommendations</pre><p>No producer changes. Nobody redeploys. With durable queues, retries, and idempotent handlers, the system just converges. This is choreography at its best, and it’s a real best: low coupling, easy extension, natural resilience.</p><p>For the path where everything goes right, it’s hard to beat. The trouble is that the path where everything goes right is the part you were never worried about.</p><h3>Then the happy path ends</h3><p>Let the flow grow the way real flows do:</p><pre>OrderCreated<br>   ├─▶ PaymentRequested<br>   ├─▶ InventoryReserved<br>   ├─▶ FraudChecked<br>   ├─▶ CustomerNotified<br>   └─▶ ShippingStarted</pre><p>Now inject reality. Payment fails, but inventory is already reserved, the customer already got a “thanks for your order” email, and shipping has begun pulling the item. Five services each did exactly their job. The system as a whole is now in a state no one designed and no one owns.</p><p>So: who decides what to undo?</p><p>In pure choreography, the answer isn’t quite “nobody.” In practice you wire up reactions: Inventory listens for PaymentFailed, Notification listens for OrderCancelled. The problem isn&#39;t that no one reacts. It&#39;s that responsibility for the <em>whole</em> is now distributed, implicit, and harder to reason about with every service you add. No single participant holds the process. It&#39;s smeared across all of them. Compensations, timeouts, stuck flows, partial failures: the entire category of &quot;it didn&#39;t go as planned&quot; has no home you can point at.</p><p>That’s the real weakness, and it’s worth saying plainly: <strong>choreography is excellent at making things happen, and terrible at owning what happens next.</strong> The failure itself is rarely hidden. PaymentFailed fires an event; a poisoned message lands in a dead-letter queue; the logs have it. What&#39;s missing is an owner. That DLQ entry just sits there, and unwinding the rest of the order, releasing the inventory, cancelling, refunding, telling the customer, is nobody&#39;s job in particular. Every service handled its own piece correctly. No one is responsible for the whole. An unhandled dead-letter queue isn&#39;t a rare edge case, and it isn&#39;t recovery. It&#39;s just where ownership goes to die.</p><h3>Orchestration fixes that, and files the bill in the wrong place</h3><p>The classic answer is to give the process an owner.</p><pre>Order Workflow<br>  1. Create order<br>  2. Reserve inventory<br>  3. Charge payment<br>  4. Notify customer<br>  5. Complete</pre><p>Now one component knows where you are, what’s next, and what to do when a step fails. Visibility is excellent. Compensation is explicit. You can read the workflow top to bottom.</p><p>But look at what you paid. Every step now routes through the orchestrator. It couples to the shape of the workflow: add a step, touch the orchestrator. It drifts toward being a God Service that knows everything and that everything waits on. And here’s the part that actually matters:</p><p>You pay that coupling on <strong>every single request</strong>, including the overwhelming majority that would have sailed through choreography untouched. You put a coordinator on the critical path to solve a problem that shows up on a small fraction of executions.</p><p>The failure handling is worth having. Putting a coordinator on the critical path of every request to get it, including the overwhelming majority that never needed it, is the mistake.</p><h3>Coordinate where the coordination actually is</h3><p>We already know the shape: the happy path needs almost no coordination, the failure path needs almost all of it. So don’t put the coordinator on the path that doesn’t need one. Keep the happy path choreographed: decoupled, event-driven, autonomous. Then add a component that sits <em>off to the side</em>, watches the event stream, and stays completely out of the way until the flow leaves the rails.</p><pre>Order ─────▶ event ─┐<br>Payment ───▶ event ─┼──▶  (the event stream)<br>Shipping ──▶ event ─┘<br>                         │  observes<br>                         ▼<br>                  Process Manager<br>                         │  acts only on deviation<br>                         ▼<br>              compensate · retry · escalate</pre><p>On the nominal path, the process manager is passive. It reads events, keeps its picture of each flow current, and emits nothing: no commands, no interference. The moment something fails (a failure event, a message rotting in a dead-letter queue), it acts: triggers compensations, drives a retry policy, or escalates to a human.</p><p>Here’s the distinction that makes it work: <strong>business services own their own step. The process manager owns the flow between them.</strong> Every other participant sees only its own slice, reacts, and moves on. The process manager is the one component that holds the process as a whole, and so the only one that can decide what the whole should do when a step fails.</p><pre>Normal:                     Deviated:<br>  OrderCreated                OrderCreated<br>  PaymentSucceeded            PaymentFailedRetryable<br>  OrderCompleted              retry ×3 → timeout<br>  → process mgr idle          → process mgr: compensate, cancel, page an operator</pre><p>I’m not trying to orchestrate success. Success already has a perfectly good coordination mechanism: events. The proposal was never to replace choreography. It’s to stop asking it to solve the one problem it was never built to solve. I’m orchestrating <em>recovery</em>, and nothing else.</p><p>Take compensation, the messiest of the four. In pure choreography it scatters across everyone:</p><pre>PaymentFailed<br>   ├─▶ Inventory listens    → release stock<br>   ├─▶ Order listens        → cancel the order<br>   └─▶ Notification listens → tell the customer</pre><p>To understand what happens when a payment fails, you reconstruct it in your head from four separate subscriptions. With a process manager, the same recovery is one readable sequence:</p><pre>PaymentFailed ──▶ Process Manager<br>                    ├─▶ CompensateInventory<br>                    ├─▶ CancelOrder<br>                    └─▶ NotifyCustomer</pre><p>Even someone who prefers choreography can admit the second one is easier to read, and easier to get right. That’s one of the four benefits back, and the happy path never moved.</p><p>And no, this isn’t a new pattern. It has several old names, and I’ll get to them in a minute. The idea worth keeping is the placement, not the label.</p><h3>Recovery belongs to the workflow, not the service</h3><p>There’s a deeper point under that readability win, and it’s the part that actually convinced me.</p><p>The process manager is not holding a global table of PaymentFailedFinal → RefundPayment. That would be brittle, enormous, and exactly the God Service everyone rightly fears. It owns <strong>one workflow at a time</strong>. In Checkout, a final payment failure means: release the stock, cancel the order, maybe issue a credit note instead of a cash refund. In Subscription Renewal, the <em>same event</em> means almost the opposite: keep the subscription alive through a grace period, send a reminder, cancel nothing yet. Same event, same Payment service, completely different recovery. The recovery was never a property of the payment. It was a property of the process.</p><p>Which is a principle worth putting on the wall:</p><blockquote><strong><em>Services own business capabilities. Workflows own business intent. Recovery belongs to intent, not to capability.</em></strong></blockquote><p>The Payment service knows <em>how</em> to authorize, capture, and refund. It has no idea <em>whether</em>, in this business context, a refund is even the right move, or whether to wait, retry, or issue credit instead. That was never Payment’s call. It belongs to the workflow.</p><p>And here’s the misread to head off, because it’s the one that turns people against the idea: <strong>I’m not moving business logic into the process manager.</strong> Payment still owns <em>how</em> to refund. The process manager owns exactly one new thing, the policy that only exists once a process has left its expected path: given that <em>this</em> checkout deviated <em>here</em>, <em>if</em>, <em>when</em>, and <em>why</em> to compensate. Never <em>how</em>. That single, narrow responsibility is the whole reason this doesn’t collapse into a God Service. It centralizes the business reasoning that only appears off the happy path, and nothing else.</p><h3>This has a name: several, actually</h3><p>None of this is new, and an experienced reader is already typing that in the comments. What I’ve built is a <strong>Process Manager</strong> in Gregor Hohpe’s sense: observe events, track state, issue commands when a decision is needed. With one deliberate twist. The textbook process manager actively drives the workflow from step to step; this one stays passive while the happy path runs itself, and only picks up the baton when a step fails. Which is exactly where the <strong>supervision tree</strong> sits in Erlang and Akka: the workers work, and something off to the side stays quiet until one of them fails. It’s also the recovery half of the <strong>Saga</strong> conversation.</p><p>Call it a Process Manager, a saga coordinator, whatever your stack already calls it. You could build it on Temporal, on a home-grown state machine, or on another engine entirely. The label and the implementation were never the point. The point is one sentence, and if I had to throw the rest of this away, I’d keep it:</p><blockquote><strong><em>Workflow execution and workflow reasoning don’t have to live in the same component.</em></strong></blockquote><p>Execution, the doing, stays choreographed, spread across autonomous services. Reasoning, what should have happened and what to do when it didn’t, gets exactly one home, off the critical path. Most orchestration fuses the two onto the happy path. Pulling them apart is the whole move.</p><h3>What the process manager actually needs</h3><p>Two things, and both come with a catch worth being honest about.</p><p><strong>It needs a view.</strong> A process manager is only as good as the view it reasons from. The services shouldn’t expose their internals, so you build a projection from their events: an eventually consistent read model of where each process stands.</p><pre>{<br>  &quot;orderId&quot;: &quot;123&quot;,<br>  &quot;orderStatus&quot;: &quot;CREATED&quot;,<br>  &quot;paymentStatus&quot;: &quot;FAILED_RETRYABLE&quot;,<br>  &quot;retryCount&quot;: 3,<br>  &quot;nextAction&quot;: &quot;CANCEL&quot;<br>}</pre><p>That projection is your observability surface, your decision input, and your entry point for human intervention. Useful, and dangerous for the same reason: it lags. A process manager that reads payment failed and fires CANCEL can kill an order a late retry just completed. So the discipline is fixed: compensate <strong>idempotently</strong>, tolerate a stale view, reconcile rather than assume, and guard the executing services with <strong>optimistic locking</strong> so a stale CANCEL loses to a PaymentSucceeded that landed a second late. (Publish through a <strong>transactional outbox</strong> and the projection stops missing events, too.) An eventually consistent projection is exactly the kind of guarantee that isn&#39;t what it looks like: the assumption you inherit without noticing.</p><p><strong>It needs to know the shape of the flow.</strong> To unwind a broken process correctly, the process manager has to know what the process was: which steps ran, in what order, and what compensates what. That model is real, and it has to live somewhere. Which is the honest catch: the workflow knowledge doesn’t vanish. It <strong>moves</strong>, out of an active orchestrator on the critical path and into a passive monitor beside it.</p><p>Be honest about that trade: you still have one place that knows the whole flow. The win isn’t that the knowledge disappeared. It’s that the thing holding it no longer sits between your services and no longer slows down the 99% of executions that were always going to be fine.</p><blockquote><strong><em>The knowledge doesn’t vanish. It just moves off the critical path.</em></strong></blockquote><p>Put together, the whole thing fits on one picture:</p><pre>Happy path — choreographed, autonomous:<br>  Order ──▶ Payment ──▶ Shipping ──▶ ...<br>     │         │          │<br>     └──────── events ─────┘<br>                 │  observes everything<br>                 ▼<br>         Workflow Projection      (state of every in-flight process)<br>                 │  anomalies · timeouts<br>                 ▼<br>        Process Manager<br>                 │  acts only on deviation<br>                 ▼<br>         compensate · retry · escalate</pre><h3>The failure path is coupled, on purpose</h3><p>One more thing not to oversell. When the process manager issues compensate payment, it is now coupled to Payment. It sends commands. It knows names.</p><p>You do get a dial here, if the coupling bothers you. The process manager can issue a direct command (CompensateInventory), or publish a high-level intent (OrderCancellationRequested) and let the services react to it the way they react to anything else. The first buys control and a single readable recovery sequence. The second buys back autonomy, at the cost of the one-place readability you came for. On the failure path I usually want the control, but it&#39;s a choice you make per workflow, not a property of the pattern.</p><p>The decoupling you preserved lives entirely on the happy path. The failure path deliberately trades autonomy for control, because control is precisely what you want when things are going wrong. That’s not a leak in the design; it’s the design. Just don’t stand up and claim the whole system is decoupled. Half of it is, on purpose, and the other half is coupled, on purpose.</p><h3>When you shouldn’t do this</h3><p>This is a specific shape, not a default. Skip it when:</p><ul><li><strong>The complexity is in the happy path itself.</strong> If your nominal flow has real sequencing, approval gates, or human-in-the-loop steps, a genuine orchestrator (or a workflow engine like Temporal) is simpler. Own the flow outright and stop pretending it’s choreographable.</li><li><strong>The flow is short.</strong> Two steps and a retry don’t need a process manager. You need a queue.</li><li><strong>You can’t stomach two coordination models.</strong> Choreography <em>plus</em> a process manager means two mental models in one system. That’s a real tax on everyone who reads the code later. Only pay it when the happy path is genuinely simple and the failure handling is genuinely gnarly, which, to be fair, is the exact shape of a lot of event-driven systems.</li></ul><p>And the question you’ll get asked in every review: <em>why not just Temporal?</em> It’s the right question, and most of the time it has the boring answer: just use Temporal. A workflow engine hands you orchestration, durability, and visibility out of the box. And, above all, a workflow that is <strong>defined</strong>. Written down. Authoritative. You don’t infer where a process is; you ask the engine and it <em>knows</em>.</p><p>The hybrid can’t quite promise that, and it’s worth being honest about the gap. In Temporal, the <strong>workflow is the source of truth</strong>: reality is whatever the workflow says it is. In this hybrid, the <strong>event log is the source of truth</strong>, and the workflow is a <em>projection</em>, reconstructed from events and from what you believe the flow is supposed to be. That’s an <strong>inferred</strong> workflow, not a defined one. For monitoring, for auditing, for answering “where is this process,” a defined workflow beats an inferred one every time. (An inferred workflow is a pile of assumptions about what should happen, and you already know how that story ends.)</p><p>So no, I wouldn’t reach for this by default. In most systems I’d want the real engine: precisely for the monitoring, for a flow that’s actually defined instead of imagined, and for one place to manage behavior and compensation. The hybrid earns its keep only when happy-path autonomy is genuinely worth giving those up. Knowing when that’s true is the actual skill.</p><h3>Workflow knowledge never disappears</h3><p>I used to frame it as a fight: choreography <em>versus</em> orchestration, pick your tribe. That framing is the actual mistake. So I stopped trying to win the argument and tried to reconcile it. I didn’t escape orchestration. I stopped paying for it on the 99% of executions that never needed it, and put it exactly where it earns its keep: off the happy path, on the failures.</p><p>Choreography doesn’t eliminate coordination. It only hides where it happens, and waits for the first failure to remind you it was load-bearing all along.</p><p>And to be clear about what this is not: it isn’t a claim that orchestration beats choreography. The claim is narrower, and harder to dodge. In any non-trivial system, workflow knowledge ends up living somewhere: in Temporal, in a process manager, in a pile of event handlers, or in the heads of the three people who remember how it works. That somewhere is a design decision. Pretending it doesn’t exist is also a decision, just a worse one.</p><p>So the real question was never “should we orchestrate or choreograph?” It was always: where does workflow knowledge live, and did you choose that, or did production choose it for you?</p><blockquote><strong><em>Workflow knowledge never disappears. You don’t get to delete it. You only get to decide where it lives.</em></strong></blockquote><blockquote>About the author</blockquote><blockquote>I’m currently building <strong>Stratos </strong><a href="https://get-stratos.io/">https://get-stratos.io</a>, a set of tools focused on architectural correctness and distributed systems.</blockquote><blockquote>Feedback is always welcome.</blockquote><blockquote><strong>Brain</strong> — AI-assisted architectural risk reviews for existing codebases.</blockquote><blockquote><strong>Atome</strong> — A persistence platform with native serializability, idempotency and CQRS.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a976b1ae32c" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/the-day-i-stopped-arguing-about-choreography-vs-orchestration-9a976b1ae32c">The Day I Stopped Arguing About Choreography vs Orchestration</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Bug Wasn’t in the Code…]]></title>
            <link>https://levelup.gitconnected.com/the-bug-wasnt-in-the-code-ea1fa92c96e1?source=rss-a4b7db4e2fc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea1fa92c96e1</guid>
            <category><![CDATA[technical-debt]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Hugo Vantighem]]></dc:creator>
            <pubDate>Fri, 24 Jul 2026 15:00:26 GMT</pubDate>
            <atom:updated>2026-07-24T15:00:26.944Z</atom:updated>
            <content:encoded><![CDATA[<p>Some of the hardest production bugs to diagnose aren’t introduced by accident. They’re accepted on purpose, sometimes before a single line of code is written.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CUAcj0EwNuNZ5-I00Nj5gg.png" /><figcaption>Generated by the author using Claude Code</figcaption></figure><p>We accept them with our eyes open. <em>It won’t happen often.</em> <em>YAGNI.</em> <em>Let’s keep it simple.</em> <em>The deadline is Friday.</em> So we take the trade-off: last-write-wins is fine here, the read model can lag, the dual write rarely tears. And most of the time that’s the right call, YAGNI included. The trade-off buys something real, and refusing every one of them is its own kind of failure.</p><p>A trade-off doesn’t only cost you something today. It quietly removes a guarantee (<em>this number is always current</em>, <em>this write always wins</em>), and everything built afterward assumes the guarantee is still there. The person who made the call knew better. The person who inherits the code doesn’t. They write code that is completely correct, on top of a premise that stopped being true. And that is how correct code builds a catastrophic system.</p><p>Here’s the whole idea in one line:</p><blockquote><strong><em>Every trade-off removes a guarantee. Every removed guarantee quietly becomes an assumption. And forgotten assumptions are where technical debt actually lives.</em></strong></blockquote><p>Make the guarantee visible, and the system stays honest. Leave it in someone’s head, and it quietly expires.</p><h3>The decision that was never wrong</h3><p>Here’s how it happens. Not through incompetence. Through perfectly reasonable people doing perfectly reasonable work.</p><p>Service A manages user accounts. The real ledger lives elsewhere; for good reasons (latency, throughput, a deadline), the team exposes balance as an <strong>eventually consistent copy</strong>. In plain terms: they knowingly accept that balance will sometimes be wrong. It can lag the source of truth by seconds, longer under load; read at the wrong moment, it simply isn&#39;t current yet. That&#39;s a perfectly rational trade-off. Under their constraints, I&#39;d probably have made the same call. They discuss it, they write the ADR. Nothing here is a mistake.</p><p>Then time passes: six months, a reorg, a couple of team changes. The ADR is three git repos away from anyone’s memory.</p><p>Then Service B arrives. And honestly, I’ve <em>been</em> Service B. You open a service, you see a field called balance, and you never once stop to ask whether it&#39;s authoritative. Why would you? Nobody tells you otherwise. So a new developer needs that balance for billing, spending limits, and fraud scoring, opens the schema, and finds:</p><pre>User.balance</pre><p>balance is the balance, the true business state. So they build on it: bonus calculations, invoice totals, a fraud rule that flags accounts moving faster than their balance should allow. Every line they write is correct. Every test passes.</p><p>But balance could already be stale, because of A&#39;s trade-off. The fraud engine is now reasoning about a number that was never guaranteed to be current.</p><p>And that is exactly why it stays hidden. The missing guarantee only bites in the edge case: the stale read, the concurrent write, the retry that fires twice. The happy path behaves exactly as everyone expects, every day, for months. So the one place the flaw can surface is the rare path nobody exercises, and the last place anyone thinks to look, because we all reason from the behavior we see, and the behavior we see is fine.</p><p>Walk the bug back and you’ll find something uncomfortable. The defect isn’t in B. B’s code is flawless. <strong>The bug was never in the code at all</strong>. It was in a guarantee that had quietly been given up, and that nobody remembered was gone. The knowledge that should have traveled with that field died somewhere between the ADR and the schema.</p><blockquote><strong><em>Every trade-off creates two costs: the one you accept today, and the assumptions someone else will unknowingly inherit tomorrow. The second one is usually the expensive one.</em></strong></blockquote><h3>The technical debt that isn’t in the code</h3><p>I used to think technical debt was ugly code. These days I think ugly code is often the <em>least</em> dangerous debt a system carries: you can see it, you flinch at it, you clean it up. This is debt too. It just isn’t in the code at all, which is exactly why we never point at it.</p><p>The debt we usually talk about is in the code: you can see it, measure it, schedule the refactor. I’ve argued before that <a href="https://blog.stackademic.com/every-line-of-code-is-technical-debt-f726467fe4ab">every line of it is already a liability</a>. This kind is different. It lives in what people <em>believe</em> about the code. And beliefs aren’t in version control.</p><p>Call it <strong>assumption debt</strong>: the accumulated gap between the guarantees a system actually provides and the guarantees everyone building on it thinks it provides.</p><p>That’s the entire failure mode. It doesn’t require a single bad line of code. It only requires a forgotten one.</p><p>It’s the quieter cousin of <a href="https://blog.stackademic.com/weve-never-had-the-problem-is-luck-not-engineering-55ebfc717ef0">telling yourself “we’ve never had the problem”</a>: there, you remember the risk and bet against it; here, nobody remembers there was a bet to make.</p><h3>The same story, five times</h3><p>Once you see the pattern, it’s everywhere, and it’s always the same shape. Someone consciously traded a guarantee away. Someone else, later, never knew it was gone.</p><ul><li><strong>The cache.</strong> First knew: this cache is invalidated eventually, so it can be stale. Second assumed: the cache <em>is</em> the truth. Reads it to make a decision, and acts on a value that changed minutes ago.</li><li><strong>The connection limit.</strong> First knew: max_connections = 2000 is safe <em>because PgBouncer sits in front, pooling everything down.</em> Then PgBouncer gets removed in a cleanup. Second sees 2000, reads it as a normal setting, never asks why. Traffic climbs and the cluster falls over. The compromise survived; the reason for it didn&#39;t.</li><li><strong>The dual write.</strong> First knew: the database and Kafka can diverge on a network blip. Second assumed: the topic always reflects the database. Builds a read model on the topic. Silent, permanent drift.</li><li><strong>Last write wins.</strong> First knew: concurrent writes can clobber each other. Second assumed: the stored value is the truth. Builds billing on it.</li></ul><p>Four different technologies. Four identical stories. In every case the first developer was right, the second developer was right, and the system was broken, because the guarantee the first one traded away never reached the second.</p><p>And if you want to object that none of these are “technical debt”: that eventual consistency is a design choice, that a cache is a pattern, not a mistake. You’re right. On their own, they’re decisions, often good ones. They turn into debt at one exact moment: when the guarantee each one gave up is forgotten, and someone builds on a promise the system quietly stopped making.</p><h3>Architecture is the guarantees, not just the code</h3><p>This is the part I want to leave you with, because it reframes what architecture even is.</p><p>An architecture is more than its code. The code is the visible residue. The architecture is the set of invariants, guarantees, and assumptions the code depends on to be correct. “This field is authoritative.” “This operation is idempotent.” “These two stores are consistent.” “This read reflects the last write.” Those aren’t lines you can grep for. They’re promises the system makes. Or quietly doesn’t.</p><p>When those promises are explicit and enforced, the architecture is real. When they’re implicit, living only in the head of whoever made the call, they have a half-life. People leave. Context evaporates. The ADR gets buried.</p><p>Here’s the cleanest way I know to put it: <strong>a trade-off is a guarantee you decided to stop making.</strong> Eventual consistency? You gave up read-your-writes. Read Committed? You gave up repeatable reads. A dual write? You gave up atomicity. None of those are mistakes. They’re guarantees you traded, on purpose, for something you needed more. The trouble starts only when the <em>giving-up</em> goes silent, and the next person keeps building as if the guarantee were still there.</p><blockquote><em>Code expresses behavior. Assumptions decide whether that behavior is correct.</em></blockquote><blockquote><em>The code survives. The assumptions don’t.</em></blockquote><p>That asymmetry is the whole problem. The artifact that survives is the one that carries the least context. The knowledge that matters is the one that decays.</p><h3>I once tried to leave the scar. They asked me to remove it.</h3><p>This stopped being theory for me on one specific service.</p><p>It needed to be idempotent. I argued for putting the idempotency record in the same transaction as the write: one atomic unit, actually idempotent. The team decided otherwise: two separate transactions, <em>it’ll never fail in between.</em> A reasonable call under a deadline. I disagreed, but I shipped it.</p><p>What I did do was leave a comment right there in the code: <em>this is not idempotent if the second write fails. Expect duplicates in cases X, Y, Z.</em> A scar. A small, ugly reminder that a guarantee had been traded away.</p><p>I was asked to remove it. The reason was almost too on-the-nose: <em>it makes it look like we did it wrong.</em></p><p>But deleting the comment doesn’t make the service idempotent. It just makes the missing guarantee invisible. We weren’t fixing the design. We were fixing the <em>appearance</em> of the design. The comment never made the system less correct; it made it more honest, and honesty was the part that got cut. On paper, and in everyone’s head, this was now “the idempotent service.”</p><p>Months later the SREs came asking why one service kept double-processing calls from another, <em>even though it has idempotency.</em> It didn’t. It never had. We’d all just forgotten, because the one line of code that still remembered had been deleted for looking bad.</p><p>The bug wasn’t hard because idempotency is hard. It was hard because we had deliberately removed the only thing that still knew the truth.</p><h3>A trade-off should leave a scar</h3><p>So what do you actually do? Not “write more docs.” Documentation is just another assumption in a file nobody opens. An ADR rots exactly as fast as the memory it was meant to replace.</p><p>What’s worked for me is blunter than documentation: <strong>when a guarantee changes, let the code change with it.</strong> A trade-off that matters can live in the <em>shape</em> of the code. If a balance is an eventually consistent copy, maybe it shouldn’t be a plain balance int64 that reads like gospel. It could be an EventuallyConsistentBalance, or come back from GetCachedBalance(), something nobody mistakes for the source of truth. If idempotency is best-effort, you could call it BestEffortIdempotency instead of IdempotencyService. Then the guarantee you gave up shows up every time someone types the name, and you can&#39;t forget what the code keeps saying out loud.</p><p>The guarantees that tend to survive are the ones the system won’t let you ignore. A few ways I’ve seen that work, all of them moving the guarantee out of prose and into a place a future developer collides with whether they read the history or not:</p><ul><li><strong>Encode the invariant where it’s enforced</strong>, not where it’s described. A balance that isn’t authoritative shouldn’t be a plain int64 named balance that reads like gospel. It should be a type, an API, or a validation that makes its uncertainty part of its contract.</li><li><strong>Push the assumption into an executable artifact: something that runs, not something you read.</strong> A CHECK or UNIQUE constraint, a NOT NULL, a version column with optimistic locking, a state machine that refuses illegal transitions, an outbox that makes &quot;the database and the broker agree&quot; structural instead of hopeful. Prose you can skip. A constraint you can&#39;t.</li><li><strong>Make the guarantee ride with the data.</strong> If a read model is eventually consistent, the thing you hand people should say so at the point of use: a staleness stamp, a type that isn’t named like the source of truth, a method that forces the question.</li><li><strong>Fail loudly at the boundary</strong> the moment someone builds on a premise that no longer holds, instead of returning a plausible-looking wrong number.</li></ul><p>This is the quiet thesis behind a lot of what I build: an invariant that lives only in a document is a decoration. An invariant the system enforces is architecture. The difference is whether the next developer <em>can</em> forget it.</p><h3>The debt that accumulates faster</h3><p>We say technical debt piles up because we postpone work. Fair. But another kind piles up faster, and we barely name it.</p><p>Forgotten assumptions.</p><p>Every shortcut, every consciously accepted inconsistency, every “we’ll fix it later” becomes part of the architecture the moment it ships, a premise the next person inherits without knowing they inherited anything. If the developers who come after don’t know those assumptions exist, they’ll extend the system as if they weren’t there, and do it flawlessly.</p><p>That’s the part that should scare you. This failure mode doesn’t punish carelessness. It punishes competence built on a premise no one wrote down. It’s how a hundred perfectly reasonable decisions compound into a system nobody can safely change.</p><p>The compromises you remember rarely break your architecture. The ones you forgot you made are the ones that do.</p><p>Trade-offs don’t age badly. Forgotten trade-offs do. So when a trade-off matters, make it leave a mark: not an ADR nobody opens, but a scar in the code itself, where the next person can’t walk past it.</p><p>Good architecture doesn’t hide its compromises. It leaves scars where the guarantees were traded away.</p><blockquote>About the author</blockquote><blockquote>I’m currently building <strong>Stratos </strong><a href="https://get-stratos.io/">https://get-stratos.io</a>, a set of tools focused on architectural correctness and distributed systems.</blockquote><blockquote>Feedback is always welcome.</blockquote><blockquote><strong>Brain</strong> — AI-assisted architectural risk reviews for existing codebases.</blockquote><blockquote><strong>Atome</strong> — A persistence platform with native serializability, idempotency and CQRS.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea1fa92c96e1" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/the-bug-wasnt-in-the-code-ea1fa92c96e1">The Bug Wasn’t in the Code…</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Was a Good Developer for Five Years. Then I Opened an Architecture Book.]]></title>
            <link>https://levelup.gitconnected.com/i-was-a-good-developer-for-five-years-then-i-opened-an-architecture-book-ddef5abd22b6?source=rss-a4b7db4e2fc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/ddef5abd22b6</guid>
            <category><![CDATA[careers]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Hugo Vantighem]]></dc:creator>
            <pubDate>Fri, 10 Jul 2026 16:18:09 GMT</pubDate>
            <atom:updated>2026-07-11T08:02:00.768Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j9_cEbSnXmWvajVfXf0wHA.jpeg" /></figure><blockquote><em>“Unknown unknowns are the bane of software architecture.”</em></blockquote><ul><li>Mark Richards &amp; Neal Ford, <em>Fundamentals of Software Architecture</em></li></ul><p>For the first years of my career, I was proud of what I shipped. I did what I was asked. I followed the “best practices” of one company after another, to the letter. My features passed the tests, my code went to production. To my managers and to me, I was a good developer.</p><p>Then I started opening system architecture books. The real ones.</p><p>And it was a slap. Reading those pages, I looked in the rear-view mirror and saw something I didn’t want to see. For one year, three years, five years, I had been carrying architectural blind spots I didn’t even know existed.</p><p>The silent architecture mistakes. The partial fixes that create worse problems than they solve. The shaky dual writes that corrupt data in the background. I don’t know these because I observe them in other people’s systems today. I know them because I committed most of them myself.</p><p>And none of it was sloppy work that slipped past the process. It passed review. Pull requests read line by line and approved by senior engineers and tech leads — the people whose whole job is to catch exactly this. Every one of those flaws shipped with a green checkmark and someone’s name on the approval. Not because they were careless, but because they couldn’t see it either. The blind spot wasn’t mine alone. It was the whole team’s.</p><p>Here’s the concrete version. I put getters and setters on everything, because every Java codebase around me did. I treated rich domain models as academic theory and shipped anemic ones instead — all the business logic piled into one fat service, a Transaction Script in everything but name. I trusted PostgreSQL’s default isolation level without understanding which anomalies it actually prevented. I added retries with no backoff, no jitter, sometimes no idempotency. Every one of those choices felt reasonable at the time. That’s exactly what made them dangerous.</p><p>Take those retries. I was proud of them — clean, defensive, the kind of code that sails through review. It took me years to see the obvious: without idempotency or backoff, a retry loop doesn’t soften an outage. It amplifies it.</p><h3>The mirage of “company practice” and hype</h3><p>When you start out, you assume that if a practice is standard inside a company, especially a big-name tech company, it must be correct. You copy, you paste, you apply the existing patterns. The feature ships, “it works,” and your brain signs off.</p><p>Nobody ever sat me down and explained aggregate boundaries, write skew, idempotency, or retry storms. So I copied what worked around me. Most developers do. And a team can run for years on a flawed pattern, simply because the conditions that would trigger the failure never line up. That isn’t engineering. That’s luck.</p><p>It’s a mirage. What we take for standards of excellence are often just compromises made by teams under time pressure, normalized by the years.</p><p>It gets worse, because we’re wired for hype. A shiny new tool shows up, a trendy framework, a seductive architecture pattern. We look at one side of the coin only: the promises, the speed of setup, the immediate wins. We roll it out everywhere, delighted with ourselves. And it’s only a year or two later, when the system is under load and things start drifting out of sync, that reality hits. We find the side effects far too late.</p><p>The day you dive into distributed systems theory, you realize how many assumptions you’d been making without ever noticing. You start seeing them everywhere. And that’s where the real learning begins — a process that never ends, which is exactly what makes it as exciting as it is humbling.</p><h3>Every solution is tomorrow’s problem</h3><p>Software engineering isn’t a linear science where you solve a problem once and move on. It’s a chain reaction.</p><p>The more your skills grow, the harder the problems you take on. But the more problems you solve, the more new ones you uncover. Why? Because every solution to a technical problem carries its own trade-offs.</p><p>The trap is that those trade-offs don’t show up right away. They wait quietly for the system to grow, for load to climb, or for some use case nobody imagined to surface three years later. Architecture is the art of choosing, today, which problems you agree to deal with tomorrow.</p><h3>What drives me now: the knowledge quadrant</h3><p>To make sense of that shift, I lean on a model any reader of <em>Building Evolutionary Architecture</em> will recognize. Map what you know against the complexity of the system, and it splits into three tiers.</p><p><strong>Things you know.</strong> Your comfort zone. The stacks you’ve mastered, your everyday code.</p><p><strong>Things you know you don’t know.</strong> You know it exists, you just haven’t mastered it yet. You know what Raft consensus or Paxos is, even if you’ve never had to implement one. You can go read up when the day comes.</p><p><strong>Things you don’t know you don’t know.</strong> The real danger zone. A total blind spot. The hard problems and the network or concurrency edge cases you don’t even suspect can exist.</p><p>That third tier is what drives me now. As a junior, my world stopped at the first two. Opening the architecture books made me feel the size of the third. And that’s what makes large-scale production so unnerving: knowing there are failure modes you don’t even know exist.</p><p>That third tier is also where most of my own mistakes came from. I wasn’t deliberately choosing bad solutions — I didn’t know the problem existed. You can’t weigh the trade-offs of idempotency if you’ve never heard the word. You can’t reason about write skew if nobody has told you it’s a thing. You can’t defend an aggregate boundary you don’t know is there.</p><p>The scary part was never making the mistakes. It was not knowing they were mistakes.</p><h3>My new lens: choose your problems</h3><p>Today, I still watch people walk head-first into the exact traps I fell into — myself included, more often than I’d like to admit. Same reason as always: you don’t know what you don’t know. But my own approach has flipped completely.</p><p>When I hit a new tool, a new pattern, a new architecture, I don’t let it dazzle me anymore. My decision runs in two strict steps.</p><p>First, I skim the upside. If it solves the exact problem I have today, fine, it’s worth a look.</p><p>Then I jump straight to the only step that actually matters: the trade-offs. This is how I shrink that third tier. I go digging through the docs, the post-mortems, the theory, for the part nobody puts on the landing page. What is this going to break? How does it behave when the network fails? What happens when the message broker goes down? What does it really cost to maintain?</p><p>Take one concrete case. Early on, I’d have seen a retry library and thought: great, more reliability. Now the first questions are different — what happens if the operation isn’t idempotent? If ten thousand clients retry in the same instant? If the dependency is already drowning? The feature didn’t change. The questions did.</p><p>These days I don’t choose a technology for its promises. I choose it for the problems it introduces — the ones I’m willing to live with. If I know the pain points up front and I’m confident I can handle them, I sign off. Not before.</p><h3>Being wrong is the only real way to learn</h3><p>I haven’t lived through every crisis yet. I’ve never had to handle a real database split-brain live, in the middle of the night, and I know my “things I don’t know I don’t know” tier is still enormous. Production throws anomalies far more complex than any theory can anticipate.</p><p>But I stopped being afraid of getting it wrong.</p><p>Finding out that the code you wrote six months ago was flawed isn’t a failure. It’s proof you’ve grown. A developer who looks at their code from two years ago and still finds it perfect is a developer who learned nothing in 24 months.</p><p>Looking back, I wasn’t a bad developer. I was a developer working inside the limits of what I knew.</p><p>Technique you learn from books. Resilience you earn by studying your own mistakes. The books didn’t make me an architect. They just taught me to stop assuming I could already see the whole map.</p><blockquote>About the author</blockquote><blockquote>I’m currently building <strong>Stratos </strong><a href="https://get-stratos.io/?source=user_about----------------------a4b7db4e2fc8----------------------">https://get-stratos.io</a>, a set of tools focused on architectural correctness and distributed systems.</blockquote><blockquote>Feedback is always welcome.</blockquote><blockquote><strong>Brain</strong> — AI-assisted architectural risk reviews for existing codebases.</blockquote><blockquote><strong>Atome</strong> — A persistence platform with native serializability, idempotency and CQRS.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ddef5abd22b6" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/i-was-a-good-developer-for-five-years-then-i-opened-an-architecture-book-ddef5abd22b6">I Was a Good Developer for Five Years. Then I Opened an Architecture Book.</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The DDD Pattern I Wish I’d Learned Years Ago: Hide the Type, Not the Fields]]></title>
            <link>https://levelup.gitconnected.com/the-ddd-pattern-i-wish-id-learned-years-ago-hide-the-type-not-the-fields-3867a4a76083?source=rss-a4b7db4e2fc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/3867a4a76083</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <dc:creator><![CDATA[Hugo Vantighem]]></dc:creator>
            <pubDate>Wed, 08 Jul 2026 17:25:22 GMT</pubDate>
            <atom:updated>2026-07-23T06:11:54.290Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kibYsZNLAP9ATYeCACDgRg.png" /><figcaption>Image generated by the author using ChatGPT</figcaption></figure><p><em>That time I felt completely dumb (and why I loved it).</em></p><blockquote><em>DDD encapsulation </em><strong><em>without a duplicate persistence model</em></strong><em>: a domain interface hiding a serializer-native state type, in </em><strong><em>Go</em></strong><em> and </em><strong><em>Java 17+</em></strong><em>. In both, the aggregate persists to a human-readable JSON file exactly as it lives in memory (no translation layer in between).</em></blockquote><p>For years, I followed the Clean Architecture and DDD playbook to the letter. Private fields on my domain models to protect invariants. Public structs with serialization tags for the database. And between them, thousands of lines of mappers (ToDomain(), ToData(), toEntity(), fromEntity()) shuttling data across a border I had drawn myself.</p><p>Then one afternoon I asked a dumb question: why am I doing this to myself? The answer was sitting in plain sight, in language features I used every day. I felt stupid for not seeing it sooner. I also felt great, because the fix deletes code instead of adding it.</p><p>The insight is small, and it works against any store:</p><blockquote><strong><em>Encapsulation comes from hiding the implementation type, not from hiding every field from the serializer.</em></strong></blockquote><p>Hide the type behind an interface and its fields can be visible to the serializer without ever being visible to the app. I’ll show it in <strong>Go</strong> and <strong>Java 17+</strong>. The examples use plain JSON files, but the idea holds against any database.</p><h3>The self-inflicted wound</h3><p>DDD tells you, correctly, to protect an aggregate’s invariants. Nobody should set balance to a negative number, so you don&#39;t expose balance. You expose deposit() and withdraw(). To do that, you hide the state.</p><p>But the moment you hide the state, your serializer can’t see it either. Go’s encoding/json only marshals exported fields. Jackson needs a visible serialization path. So the standard workaround is a second model:</p><ol><li>A <strong>domain model</strong> with hidden state and behaviour.</li><li>A <strong>data model</strong> (a DTO, or a JPA entity) that mirrors it with public, serializer-friendly fields.</li><li><strong>Mappers</strong> in both directions.</li><li>For nested value objects: more mappers, all the way down.</li></ol><p>Now every aggregate exists twice, and you keep the two copies in sync by hand forever. MapStruct exists because this got painful enough that we built tooling to generate the busywork. But the best way to win at busywork is to not have any.</p><p>One scope note before we go further, because it’s the whole difference between a defensible claim and an indefensible one. Think of three layers:</p><pre>API DTO          — shapes what clients see   (often earns its place)<br>   ↕<br>Domain aggregate — behaviour and invariants  (always)<br>   ↕<br>Persistence DTO  — exists only to be serialized</pre><p>This article deletes the <strong>bottom</strong> one: the persistence model that mirrors the aggregate field-for-field and earns its keep nowhere but the marshaller. It says nothing about the <strong>API DTO</strong> at your system’s edge. If your wire contract has its own versioning, redaction, or consumer-specific shape, that boundary is doing real work (keep it). We’re removing the copy <em>below</em> the aggregate, not the one <em>above</em> it.</p><h3>Where this fits (it works against any store)</h3><p>This isn’t a document-database trick. The pattern works against anything: relational, document, event store, plain files. What changes is <em>where the boundary lands</em>, not whether the pattern applies.</p><p>A quick nod to Vaughn Vernon: an aggregate is a consistency boundary, usually modified and persisted as a whole. Document storage fits that naturally, because you can store the aggregate without chopping it across tables. That makes it the <em>best</em> case here, not the only one:</p><ul><li><strong>Document / JSON store</strong> — the in-memory aggregate, the serialized form, and the stored form are the same shape. The translation layer disappears, and the repository collapses to roughly:</li></ul><pre>Save(aggregate)  -&gt;  json.Marshal(aggregate)  -&gt;  store the bytes</pre><ul><li><strong>Relational store: </strong>you still turn the aggregate into rows and columns. That impedance mismatch doesn’t vanish. But you keep the part that matters: one domain model. walletState / WalletState can be JPA-annotated or mapped over JDBC directly, taking you from Wallet · WalletEntity · WalletDTO · WalletMapper down to Wallet · WalletState.</li></ul><p>So the payoff scales with the store. With documents, it’s <em>no mapping code</em>. With relational, it’s <em>no duplicate domain model</em>. Both are worth having. The rest of this article uses the document case because it shows the idea at its cleanest, but nothing about the core technique depends on it.</p><h3>The inversion, in one diagram</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wckUOT8-UNBWMH9zY9hwjA.png" /><figcaption>Image generated by the author using ChatGPT</figcaption></figure><p>The move: don’t make the <em>struct</em> private and then fight the serializer. Make the struct’s <strong>fields</strong> visible to the serializer, then hide the <strong>struct itself</strong> behind a domain <strong>interface</strong> that only exposes business methods. Encapsulation lives at the package boundary. Serialization stays native.</p><h3>“But the fields are public, that’s not encapsulated”</h3><p>That was my reflex too. But encapsulation was never “fields are private.” It’s controlling who can touch the state. Hide the <em>type</em>, and its fields can be visible to the serializer without being visible to the app.</p><p>The catch, and I won’t pretend it away: code inside the domain package can still reach in and mutate the state struct directly. But that’s true of every aggregate (a package can always touch its own fields) and here it’s one small package you own. I’ll take that trade.</p><h3>The Go Way</h3><p>Go has a feature almost nobody exploits on purpose: a type can be <strong>unexported while its fields are exported</strong>. walletState (lowercase) can&#39;t be named, built, or mutated outside its package. But WalletID and TotalBalance (uppercase) are fully visible to encoding/json.</p><pre>package domain// The only type the rest of the application ever sees.<br><br>type Wallet interface {<br>    ID() string<br>    Balance() int64<br>    Deposit(amount int64) error<br>    Withdraw(amount int64) error<br>}<br>// Unexported type → no one outside this package can build or mutate it.<br>// Exported fields → encoding/json serializes it with zero mapping code.<br>type walletState struct {<br>    WalletID     string `json:&quot;id&quot;`<br>    TotalBalance int64  `json:&quot;total_balance&quot;`<br>}<br>func (w *walletState) ID() string    { return w.WalletID }<br>func (w *walletState) Balance() int64 { return w.TotalBalance }<br>func (w *walletState) Deposit(amount int64) error {<br>    if amount &lt;= 0 {<br>        return ErrNonPositiveAmount<br>    }<br>    w.TotalBalance += amount<br>    return nil<br>}</pre><p>This is where Go’s <strong>structural typing</strong> earns its keep. No implements Wallet to wire up, no factory framework, no annotations. *walletState satisfies Wallet because it has the methods, full stop. The interface and the implementation don&#39;t even need to know about each other.</p><p>The repository marshals straight off the interface. encoding/json reflects over the hidden struct&#39;s exported fields:</p><pre>func (r *FileRepository) Save(w domain.Wallet) error {<br>    blob, err := json.Marshal(w) // no DTO, no mapper<br>    if err != nil {<br>        return err<br>    }<br>    return r.put(w.ID(), blob)<br>}</pre><h3>“But you can’t Unmarshal into an interface”: half true</h3><p>This is the objection Go reviewers always raise, and it’s worth getting exactly right. You can’t unmarshal into a <strong>nil</strong> interface (Go has no concrete type to allocate). But you <em>can</em> unmarshal into an interface that <strong>already holds a pointer</strong>: encoding/json follows that hidden *walletState by reflection. So a one-line factory replaces any hand-rolled &quot;hydrate&quot; step:</p><pre>// Hands back an interface backed by a real (hidden) pointer.<br>func NewEmptyWallet() Wallet { return &amp;walletState{} }<br>func (r *FileRepository) Load(id string) (domain.Wallet, error) {<br>    blob := r.read(id)<br>    w := domain.NewEmptyWallet()   // interface over *walletState<br>    err := json.Unmarshal(blob, w) // fills the hidden struct directly<br>    return w, err<br>}</pre><p>And no, this factory isn’t a mapper in disguise. It translates nothing and copies no fields. Its only job is to hand the standard JSON decoder a concrete instance, hidden behind the interface, to write into. The decoding is still done by encoding/json, not by hand.</p><p>The repository never names the concrete type, and Load is a plain encoding/json call. The one thing you must not quietly drop is invariant checking on load: a naive Unmarshal will happily accept an empty id or a negative balance. The fix is to implement json.Unmarshaler and validate on decode, so the guarantee rides along with every Unmarshal:</p><pre>func (w *walletState) UnmarshalJSON(data []byte) error {<br>    type alias walletState // alias drops the methods → no infinite recursion<br>    var a alias<br>    if err := json.Unmarshal(data, &amp;a); err != nil {<br>        return err<br>    }<br>    *w = walletState(a)<br>    return w.validate() // corrupt row → error, never a live aggregate<br>}</pre><p>That’s the whole cost of the pattern: a one-line factory plus a standard UnmarshalJSON, instead of two mirrored structs and two mappers.</p><h3>The Java 17+ Way</h3><p>Java has no “unexported type,” but it has something close: <strong>package-private visibility</strong>. The implementation stays invisible to the rest of the app while a small door in the same package can still reach it.</p><pre>// All the application and infrastructure layers ever see.<br>public interface Wallet {<br>    String id();<br>    long balance();<br>    void deposit(long amount);<br>    void withdraw(long amount);<br>}<br>// Package-private: nothing outside this package can construct it, downcast to<br>// it, or touch its fields. Encapsulation enforced by the compiler, not by<br>// convention.<br>final class WalletState implements Wallet {<br>    @JsonProperty(&quot;id&quot;)<br>    private final String id;<br>    @JsonProperty(&quot;total_balance&quot;)<br>    private long totalBalance;<br>    @JsonCreator<br>    WalletState(@JsonProperty(&quot;id&quot;) String id,<br>                @JsonProperty(&quot;total_balance&quot;) long totalBalance) {<br>        this.id = id;<br>        this.totalBalance = totalBalance;<br>    }<br>    @Override public String id()      { return id; }<br>    @Override public long   balance() { return totalBalance; }<br>    @Override<br>    public void deposit(long amount) {<br>        if (amount &lt;= 0) throw new IllegalArgumentException(&quot;amount must be positive&quot;);<br>        totalBalance += amount;<br>    }<br>    // withdraw(), validate() ...<br>}</pre><p>Two details do the heavy lifting:</p><ul><li><strong>@JsonProperty on a <em>private</em> field is enough.</strong> The annotation makes Jackson read and write that field by reflection, whatever its visibility. No public getters, no setters, no Lombok. The accessors that would normally punch a hole in your encapsulation just don&#39;t exist.</li><li><strong>id() / </strong><strong>balance() aren&#39;t JavaBean getters</strong> (getX/isX), so Jackson never mistakes them for properties. No duplicate fields, no accidental leaks.</li></ul><p>(Why a final class and not a record? A record is immutable, so it can&#39;t model an aggregate that mutates in place like deposit(). Records fit only if each operation returns a new instance: a valid design, just a different one.)</p><h3>The serialization door (and why Java needs one where Go doesn’t)</h3><p>Here’s a real language difference. In Go you can json.Unmarshal straight into an interface that already holds a pointer. <strong>Java can&#39;t.</strong> Tell Jackson mapper.readValue(json, Wallet.class) and it throws; it can&#39;t instantiate an interface and has no idea which concrete class you meant. So Java <em>needs</em> a small door (a package-private Wallets factory) that names the hidden class exactly once, on the inside: create() builds and validates; toJson() writes the annotated fields straight off the Wallet interface (Jackson uses the runtime type); fromJson() rebuilds via readValue(data, WalletState.class) and re-validates. The repository never imports the concrete class; it calls Wallets.toJson / Wallets.fromJson and moves on.</p><h3>Keeping it proper DDD: the repository port</h3><p>One thing the snippets above skipped: where the repository <em>contract</em> lives. In DDD / hexagonal architecture the repository is a <strong>port owned by the domain, </strong>the domain says what it needs, infrastructure provides the adapter (Dependency Inversion). So both implementations put a WalletRepository interface in the domain, speaking only in Wallet:</p><pre>// Go — domain package<br>type WalletRepository interface {<br>    Save(w Wallet) error<br>    Load(id string) (Wallet, error)<br>    List() ([]Wallet, error)<br>}</pre><pre>// Java — domain package<br>public interface WalletRepository {<br>    void save(Wallet wallet);<br>    Optional&lt;Wallet&gt; load(String id);<br>    List&lt;Wallet&gt; list();<br>}</pre><p>The file store is just one adapter (FileRepository / FileWalletRepository). The application depends on the interface and names the concrete store exactly once, at construction. Notice the layering inside the adapter: its private read/write helpers keep rows as <strong>raw bytes</strong>, so a single-key save never has to decode or re-validate the other rows. Only the public, domain-typed List hydrates them into aggregates. Raw bytes are a storage detail. The port is where everything becomes Wallet again.</p><h3>The real benefit isn’t performance</h3><p>Dropping the mapper layer might cut a few allocations and some object copying. That’s not why you do it. In most workloads (de)serialization dominates the cost anyway, so don’t expect a benchmark to light up. Treat any speedup as a bonus, not the goal.</p><p>What actually changed for me was the number of concepts I had to carry. Count what you juggle to model one aggregate.</p><p>Before, in the relational-by-habit version:</p><pre>Wallet           — the domain model<br>WalletEntity     — the persistence model<br>WalletDTO        — the serialization model<br>WalletMapper     — domain ↔ entity<br>WalletDtoMapper  — domain ↔ dto</pre><p>After:</p><pre>Wallet           — the interface (behaviour)<br>walletState      — the hidden state (serialized natively)</pre><p>Before a DDD purist objects that walletState is just the persistence model wearing a disguise: it isn&#39;t. It&#39;s the aggregate itself, the object that runs Deposit and guards the invariants. A persistence model is a <em>second</em> representation you map <em>to and from</em>. Here there&#39;s nothing to map, because there&#39;s only one object; it just happens to serialize itself. That&#39;s the whole difference between two models and one.</p><p>You didn’t just delete lines of code. You deleted <strong>ideas</strong>. And architectural complexity isn’t measured in lines, it’s how many things you have to understand before you can safely change a feature. Every model in the “before” list is one more thing to keep in sync, one more place to edit when the aggregate grows a field, one more concept a new teammate has to learn. The “after” list is two, and one of them is invisible to the rest of the app.</p><p>That’s the real win: less to sync, less to hold in your head, fewer places to touch when the aggregate changes. Lower maintenance cost and lower cognitive load, a far more honest claim than a latency number.</p><h3>When NOT to do this</h3><p>Be straight about the edges, or you’ll get burned:</p><ul><li><strong>Heavy ORM / JPA with framework constraints.</strong> Hibernate wants a no-arg constructor, non-final classes for proxying, and its own access rules, all of which can fight a hidden, final state type. You can often still annotate a single model (keeping “no duplicate”), but if the framework forces a separate entity, take it. The win there is one domain model, not zero mapping.</li><li><strong>External contract ≠ domain model: keep your presentation DTO.</strong> This is the boundary the pattern does <em>not</em> touch. The moment a client depends on your API, your aggregate can’t change shape freely: rename a field, split an entity, drop a property, and you’ve shipped a breaking change to consumers you don’t control. A dedicated presentation DTO is what absorbs that — it lets the domain evolve while the wire contract stays stable (and the reverse: versioning, redaction, consumer-specific views). That DTO is doing real work; keep it. The pattern here removes the <em>persistence</em> model below the aggregate, never the presentation model above it.</li><li><strong>The serialized shape is now part of your domain package.</strong> Renaming a field is a storage migration, not a free refactor. That’s true of any persistence format, just don’t pretend the coupling vanished.</li></ul><h3>Takeaway</h3><p>The insight is small: encapsulation comes from hiding the implementation type, not from hiding every field from the serializer. Once you see it, the duplicate model stops being the default answer. Encapsulation and native serialization were never actually in conflict. Put a behaviour-only <strong>interface</strong> in front, keep a serializer-friendly <strong>state type</strong> behind it, and hide that type at the <strong>package boundary</strong>. Whatever store you use takes it from there.</p><p>That’s the part that still bugs me. I spent years treating the duplicate persistence model as the unavoidable price of encapsulation. It wasn’t. The aggregate could always have been its own serialized form. I just never thought to hide the <em>type</em> instead of the fields. Fewer files, sure. But mostly fewer things to carry around in my head.</p><p>This isn’t the only way to model an aggregate. It’s simply a different trade-off: a little more coupling to persistence in exchange for fewer concepts, fewer files, and less code to maintain.</p><p>Try it on one aggregate. Then go delete some mappers.</p><blockquote><strong>About the author</strong></blockquote><blockquote>I’m currently building <strong>Stratos </strong><a href="https://get-stratos.io/?source=user_about----------------------a4b7db4e2fc8----------------------">https://get-stratos.io</a>, a set of tools focused on architectural correctness and distributed systems.</blockquote><blockquote>Feedback is always welcome.</blockquote><blockquote><strong>Brain</strong> — AI-assisted architectural risk reviews for existing codebases.</blockquote><blockquote><strong>Atome</strong> — A persistence platform with native serializability, idempotency and CQRS.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3867a4a76083" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/the-ddd-pattern-i-wish-id-learned-years-ago-hide-the-type-not-the-fields-3867a4a76083">The DDD Pattern I Wish I’d Learned Years Ago: Hide the Type, Not the Fields</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MongoDB Snapshot Isolation vs PostgreSQL Repeatable Read: The Difference Everyone Gets Wrong.]]></title>
            <link>https://blog.stackademic.com/mongodb-snapshot-isolation-vs-postgresql-repeatable-read-the-difference-everyone-gets-wrong-fb8479a28353?source=rss-a4b7db4e2fc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb8479a28353</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Hugo Vantighem]]></dc:creator>
            <pubDate>Mon, 06 Jul 2026 09:31:17 GMT</pubDate>
            <atom:updated>2026-07-11T08:03:16.046Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NZxfMaRAw5Ey5v3VolksOw.png" /><figcaption>Image generated by the author using ChatGPT</figcaption></figure><p><em>The eternal “which one is the real isolation level” debate, settled with traces. For everything that actually bites you in production, the two are identical. The one real difference is a level neither name even mentions.</em></p><p>Every few weeks, someone reopens the same fight. MongoDB Snapshot Isolation versus PostgreSQL REPEATABLE READ, which one is the <em>serious</em> database? I’ve sat through this argument more times than I can count, and here’s the part nobody in it wants to hear: for everything that actually hurts you in production, the two are twins. There’s exactly one real difference, and it’s nowhere near where people keep pointing.</p><p>Worse, half the room is quoting the wrong isolation level without knowing it. So let me show it with traces. Confident opinions are cheap here. Traces aren’t.</p><blockquote><strong><em>On versions.</em></strong><em> None of this is bleeding-edge. It’s each engine’s </em>defined<em>, stable behavior:</em></blockquote><ul><li><strong>PostgreSQL</strong> — REPEATABLE READ and SERIALIZABLE (SSI) semantics hold across every supported release, <strong>9.1 through 18</strong>.</li><li><strong>MongoDB</strong> — snapshot isolation and the WriteConflict behavior are unchanged from <strong>4.0</strong> (replica sets) and <strong>4.2</strong> (sharded clusters) through <strong>8.x</strong>. Before 4.0, no multi-document transactions at all.</li></ul><h3>1. Same foundation: one MVCC snapshot</h3><p>Both engines take a consistent point-in-time snapshot and serve every read from it. Other transactions can commit all they want. You won’t see a thing until you open a new transaction.</p><pre>account.balance = 100</pre><pre>  T1 begin (snapshot S0)<br>  T1 read balance → 100<br>                              T2: balance = 200, COMMIT<br>  T1 read balance → 100        ← still S0, unmoved</pre><p>Same behavior on both. No dirty reads, no non-repeatable reads, and the part that surprises people: <strong>no phantoms either</strong>. PostgreSQL REPEATABLE READ is actually <em>stronger</em> than the ANSI spec, which still permits phantoms. MongoDB’s snapshot does the same. For read consistency, <strong>Mongo SI and Postgres RR are the same thing</strong>. Full stop.</p><h3>2. The myth: “Postgres RR just lets the last write win.”</h3><p>This one gets repeated everywhere, and it’s flat wrong. Two transactions write the <strong>same</strong> row at the same time:</p><pre>account.balance = 100</pre><pre>  T1 read 100        T2 read 100<br>  T1 write 90        T2 write 80</pre><p>What actually happens:</p><ul><li><strong>PostgreSQL REPEATABLE READ</strong> — <strong>first-updater-wins.</strong> The second writer blocks until the first commits, then aborts with ERROR: could not serialize access due to concurrent update (SQLSTATE 40001). You retry. <strong>No silent lost update.</strong></li><li><strong>MongoDB Snapshot Isolation</strong> — the second writer hits a WriteConflict and the transaction aborts on the spot. You retry. <strong>No silent lost update.</strong></li></ul><p>Same-object collision, and <strong>both engines kill one side.</strong> The mechanism is what differs. Postgres blocks then errors, Mongo fails fast. The result is identical: somebody retries.</p><blockquote><em>The “last write wins, silent lost update” story is </em><strong><em>READ COMMITTED</em></strong><em>, Postgres’ default level. It is not REPEATABLE READ. If you’ve ever watched a lost update happen on Postgres, you were almost certainly at READ COMMITTED. People see that, then label it RR. It isn’t.</em></blockquote><p><em>Verdict: same-object write conflict, both abort. Not a difference.</em></p><h3>Mental model</h3><blockquote><em>Snapshot isolation gives you a consistent </em>view<em> and kills collisions on the </em>same<em> object, on both engines. It does not understand invariants that span objects.</em></blockquote><p>That second sentence is the whole story. Here’s where it bites.</p><h3>3. Where both fail identically: cross-object write skew</h3><p>Now, a business invariant that spans rows: <em>the total seats across all teams must stay ≤ 100.</em></p><pre>Team A = 50, Team B = 40   →   Σ = 90   (cap 100)</pre><pre>  Tx A: read Σ=90 → +8 to Team A → 98 ≤ 100 ✅ → COMMIT<br>  Tx B: read Σ=90 → +8 to Team B → 98 ≤ 100 ✅ → COMMIT<br>        └─ each read its OWN snapshot; the two writes hit DIFFERENT<br>           objects → no conflict for either engine to catch.</pre><pre>  Σ = 58 + 48 = 106   &gt;   100   ❌</pre><p>Run this on <strong>Postgres REPEATABLE READ</strong> or <strong>Mongo SI,</strong> and you get the same broken total on both. Neither engine sees the conflict, because the conflict isn’t on any single object. It lives in a rule that exists only in your head. Snapshot isolation, whatever the vendor calls it, protects rows and reads. It does not protect your invariants.</p><p><em>Verdict: cross-object write skew, both vulnerable. Still no difference.</em></p><h3>4. The one real difference, and it’s a level up</h3><p>So far, twins. The split only shows up when you climb one rung past snapshot isolation.</p><ul><li><strong>PostgreSQL has </strong><strong>SERIALIZABLE</strong> (Serializable Snapshot Isolation, SSI). It tracks read/write dependencies between transactions and <em>detects</em> the write skew from the seats example above, then aborts one transaction with a serialization error. Flip one setting and the engine catches the anomaly for you.</li><li><strong>MongoDB has no serializable level at all.</strong> Its strongest isolation is the snapshot you already saw. To stop cross-document write skew, you build it yourself: materialize the invariant into a single document, force every writer to touch it, and the invisible skew becomes a WriteConflict the engine <em>can</em> see.</li></ul><p>That’s the real headline. Forget “SI vs RR.” The honest version is <strong>“Postgres can promote to SERIALIZABLE, Mongo can’t.”</strong></p><h3>The honest comparison</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_D19kZBMxWZheONyMDwJXA.png" /><figcaption>Screenshot by the author</figcaption></figure><h3>The takeaway</h3><blockquote><em>Up to snapshot isolation, twins. The one real difference is the rung above it: Postgres lets you promote to </em><em>SERIALIZABLE and have the engine catch the cross-object skew for you. On MongoDB, that&#39;s on you.</em></blockquote><p>And if “make the engine catch a cross-document invariant” is your actual problem, then materializing the conflict, paying the retry tax that comes with it, and eventually designing the race out entirely, that’s its own rabbit hole.</p><blockquote><strong>About the author</strong></blockquote><blockquote>I’m currently building <strong>Stratos </strong><a href="https://get-stratos.io/?source=user_about----------------------a4b7db4e2fc8----------------------">https://get-stratos.io</a>, a set of tools focused on architectural correctness and distributed systems.</blockquote><blockquote>Feedback is always welcome.</blockquote><blockquote><strong>Brain</strong> — AI-assisted architectural risk reviews for existing codebases.</blockquote><blockquote><strong>Atome</strong> — A persistence platform with native serializability, idempotency and CQRS.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb8479a28353" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/mongodb-snapshot-isolation-vs-postgresql-repeatable-read-the-difference-everyone-gets-wrong-fb8479a28353">MongoDB Snapshot Isolation vs PostgreSQL Repeatable Read: The Difference Everyone Gets Wrong.</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“We’ve Never Had the Problem” Is Luck, Not Engineering.]]></title>
            <link>https://blog.stackademic.com/weve-never-had-the-problem-is-luck-not-engineering-55ebfc717ef0?source=rss-a4b7db4e2fc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/55ebfc717ef0</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[technical-debt]]></category>
            <dc:creator><![CDATA[Hugo Vantighem]]></dc:creator>
            <pubDate>Wed, 24 Jun 2026 07:23:45 GMT</pubDate>
            <atom:updated>2026-07-11T08:04:15.952Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0uKIyDUeWyhl8gsZlR9aNg.png" /><figcaption>Image generated by the author using ChatGPT</figcaption></figure><p>A few years back, I watched a team hunt a bug where a handful of customers were being charged twice. Not always. Maybe one payment in a thousand. The code had retries. The payment endpoint wasn’t idempotent. It had shipped two years earlier, and nobody had touched it since — because it had never caused a problem. Then it did, and someone had to sit down and work out which charges were real and which ones the system had invented.</p><p>That’s the trap. A totally broken system is the easy case: it doesn’t work, everyone knows it, you fix it. The architecture that quietly works 99% of the time is the one that takes you down. They sleep in silence, hidden in the gaps between what the system actually does and what people think it does.</p><p>Point at a design flaw and you’ll hear the boomerang:</p><blockquote><em>“It’s been in prod for three years, and we’ve never had the problem. Why would we rewrite it?”</em></blockquote><p>It reassures managers, it closes debates, and it feels like control. It’s also one of the biggest perspective mistakes in our field.</p><h3>The 99% trap</h3><p>When a system is fully broken, it’s simple: it doesn’t work, so you repair it. But when a shaky pattern handles 99% of requests without flinching, it earns a false legitimacy. People start trusting it blindly.</p><p>That’s when the trap closes. The remaining 1% doesn’t arrive as clean crashes. It arrives as subtle anomalies, intermittent bugs nobody can reproduce. And because “the system runs,” those design errors are the last thing the team will suspect during an incident. You blame the network, a flaky snapshot, bad luck. Meanwhile, the real cause has been sitting in the design since day one.</p><p>At scale, 1% failure on millions of requests a day isn’t a marginal anomaly. It’s a bug factory running around the clock.</p><p>And these are the most dangerous errors you can ship, because you only see them too late. A clean crash pages you in seconds. The 99% pattern says nothing. By the time the 1% finally surfaces, the corruption is already days or weeks deep, long after the code that caused it shipped clean.</p><h3>A partial fix is worse than no fix</h3><p>Why do these 1% bugs happen? Because teams design short-term fixes without understanding the problem as a whole. And in distributed systems, a partial solution is far more dangerous than no solution at all.</p><p>Don’t solve a problem, and the system fails immediately. Clean, visible. Half-solve it, and you hide the immediate failure to manufacture a delayed catastrophe.</p><p>I’m not lecturing from the outside. For years, I wrote code exactly like this, the way the companies around me did, until a stack of architecture books showed me how wrong I’d been. Of the three traps below, I’ve shipped two myself. Split-brain, I was lucky enough to only read about.</p><p><strong>1. Retries without idempotency.</strong> A network call fails. With no retry, the action fails, the client knows it, end of the story. So you add automatic retries to “make it reliable.” Fine. But if your endpoints aren’t strictly idempotent, the retry runs the action more than once in the background: double charge, stock decremented twice. You hid a surface network error and injected data corruption underneath.</p><p><strong>2. The dual write.</strong> You need to write to a database and publish a message to Kafka. You make both calls back-to-back. It works 99% of the time. Then one day, the second call fails on a microsecond network blip, and your two systems are out of sync forever. Skipping a real Transactional Outbox because “it almost never fails” is a choice to corrupt your data.</p><p><strong>3. Split-brain.</strong> One PostgreSQL instance, it goes down, the service stops. That’s downtime, but your data stays clean. Configure a multi-node cluster halfway, without understanding the fine print of consensus, and you risk split-brain: two nodes both believe they’re the primary and accept conflicting writes. The system didn’t stop. Your database became a landfill.</p><h3>Reconciliation day</h3><p>This is where “we’ve never had the problem” turns into a tragedy. When the bug is silent and masked by a partial fix, you don’t catch it minutes later. You discover the effects weeks or months on, usually because an accounting report doesn’t add up, or a customer complains about wild inconsistencies on their account.</p><p>And then you meet hell on earth: manual reconciliation.</p><p>Writing throwaway scripts in a crisis room, trying to cross-reference partial application logs, asynchronous database states, and broker events to guess what the “true” valid data was three weeks ago. It’s psychologically exhausting, technically dangerous, and it costs the company a fortune.</p><p>Losing all your data to a hard crash is bad, but if you restore yesterday’s backup, you know where you stand. Surgically repairing a live, corrupted database because a design was thought through halfway is the worst scenario in tech.</p><h3>Don’t confuse luck with engineering</h3><p>Saying “we’ve never had the problem” isn’t a statement about your architecture. It’s a statement about your luck so far.</p><p>Because sooner or later reality exercises the edge case. The network blips, the node partitions, the retry fires twice. The question isn’t whether that moment comes — it’s whether you discover it in a controlled test, or three weeks too late in a crisis room, guessing which charges were real and which ones the system invented.</p><p>That’s the difference between luck and engineering. Don’t mistake a healthy system for one quietly bleeding at 1%.</p><blockquote><strong>About the author</strong></blockquote><blockquote>I’m currently building <strong>Stratos </strong><a href="https://get-stratos.io/?source=user_about----------------------a4b7db4e2fc8----------------------">https://get-stratos.io</a>, a set of tools focused on architectural correctness and distributed systems.</blockquote><blockquote>Feedback is always welcome.</blockquote><blockquote><strong>Brain</strong> — AI-assisted architectural risk reviews for existing codebases.</blockquote><blockquote><strong>Atome</strong> — A persistence platform with native serializability, idempotency and CQRS.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55ebfc717ef0" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/weve-never-had-the-problem-is-luck-not-engineering-55ebfc717ef0">“We’ve Never Had the Problem” Is Luck, Not Engineering.</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Every Line of Code Is Technical Debt]]></title>
            <link>https://blog.stackademic.com/every-line-of-code-is-technical-debt-f726467fe4ab?source=rss-a4b7db4e2fc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/f726467fe4ab</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[technical-debt]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Hugo Vantighem]]></dc:creator>
            <pubDate>Tue, 09 Jun 2026 12:43:32 GMT</pubDate>
            <atom:updated>2026-07-11T08:04:40.778Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2NYa55aMgB04FifqgZNcxw.png" /><figcaption>Image generated by the author using ChatGPT</figcaption></figure><p>Every line of code is technical debt. Even the line you’re proud of. Even the one that’s perfectly correct.</p><p>I don’t mean that the way it sounds.</p><p>When developers hear “technical debt,” they hear <em>bad code</em>. Somebody was lazy, or found a workaround. So the second the phrase comes out, the conversation stops being about the idea and turns into who screwed up.</p><p>That’s not what I’m saying. I use “debt” the way an accountant means it, not the way a code reviewer means it. The word I actually want is <strong>liability</strong>: something you owe, not something you did wrong.</p><h3>Code was never the point</h3><p>Think about what software is for. Almost any business process we put into software could be done by hand. Slower, with people and paper and a lot of patience, but it could. Software isn’t magic. It’s a trade. We write code to buy speed, and that trade is the whole reason any of us have jobs.</p><p>But it’s a trade. The code was never the point. It’s what you pay to go fast. And once you start seeing code as the price instead of the prize, you can’t un-see it: a price is a liability, not a trophy.</p><h3>A liability, not an accusation</h3><p>Watch how a company books a machine it just bought. Nobody files it under “mistake.” It’s an asset; it makes money. But it isn’t free. It gets maintained, serviced, insured, and eventually scrapped. It sits on the books as something that earns and something that costs, at the same time.</p><p>Code is the same. So instead of “this is technical debt,” meaning someone messed up, the honest version is:</p><blockquote><em>Every line of code is a liability. Some are worth having.</em></blockquote><p>That one swap kills the whole fight. You stop arguing about whether the code is good. You agree that it costs, always, even at its best, and then you ask the only question that matters: Is it worth it?</p><h3>Even “perfect” code costs</h3><p>Take the “best” function ever written. Clean, correct, nothing to fix:</p><pre>func add(a, b int) int {<br>    return a + b<br>}</pre><p>Still not free. Someone, someday, has to read it, test it, secure it, document it, migrate it, and keep it compatible. The cost is tiny. It’s also not zero. And “tiny, times a huge number of lines” is exactly how a codebase turns into something nobody on the team fully understands anymore. The bill doesn’t come from the bad code. It comes from all of it.</p><h3>Most of it is debt worth taking</h3><p>One distinction keeps me honest here. What people usually mean by “technical debt” is accidental complexity: the code beyond what the problem needed, the layers and detours that snuck in over time. That’s real, and that’s the part you actually want to pay down.</p><p>My point is broader and a lot calmer. Even the necessary code is a liability. The business logic you couldn’t ship without is still something you’re carrying now. That’s kind of the deal with computing: you take the liability on, on purpose, because the speed is worth it. Good trade. I’d make it every day. But it still goes on the books. Necessary debt is debt, and pretending the load-bearing code is free because it’s justified is how you quietly stop counting it at all.</p><h3>AI turned this from philosophy into strategy</h3><p>For most of software’s history, we built on one assumption: writing the code was the hard part.</p><p>And fair enough. Producing code took skilled people and real time, so that’s what we optimized for. Frameworks, scaffolding, generators, almost all of it pointed at making more code, faster.</p><p>That assumption just broke. When a model spits out 1,000 lines in thirty seconds, writing isn’t the bottleneck anymore. And here’s the thing: writing was never the expensive part. Owning the code was, the whole time. The real cost is living with those lines for the next five years. Every review, every migration, every new hire trying to make sense of them, every 3 a.m. page. What collapsed was the cost of taking the liability on. The liability itself didn’t budge.</p><p>Which makes the oldest line in software suddenly matter:</p><blockquote><em>The easiest code to maintain is the code that doesn’t exist.</em></blockquote><p>For years, that was just a nice thing to nod at before going back to writing code. Now it’s an edge. Your competitor can ask a model for 100,000 lines this afternoon. Easy. What’s not easy is that they then get to understand, secure, and evolve those lines for years. The generating was free. The owning is the bill, and it comes due no matter who, or what, wrote it.</p><h3>The biggest win: delete the step</h3><p>That’s a much bigger deal than it sounds</p><p>Optimization makes a step faster. Simplification deletes the step. And the real wins almost always come from the second kind:</p><ul><li>Not a better mapper. <strong>No mapper.</strong></li><li>Not a better ORM. <strong>No ORM</strong>, where you never needed one to begin with.</li><li>Not a better process. <strong>No process</strong>, where it wasn’t earning its keep.</li></ul><p>The big jumps almost never come from doing the pointless thing faster. They come from noticing it was pointless and refusing to carry it in the first place.</p><h3>So what’s the question</h3><p>None of this means write no code, or treat every abstraction like a suspect. It means change the default question.</p><p>Not “is this code good?” Though, sure, it should be.</p><p>The question is “Is this liability worth carrying?”</p><p>Every line you add is something you’ll hold onto. Some are absolutely worth it: the ones that encode real business value, the asset side of the ledger. Some aren’t.</p><p>The AI era makes writing nearly free, and owning costs exactly what it always did, the skill that compounds isn’t writing more of it.</p><p>It’s knowing what not to keep.</p><blockquote><strong>About the author</strong></blockquote><blockquote>I’m currently building <strong>Stratos </strong><a href="https://get-stratos.io/?source=user_about----------------------a4b7db4e2fc8----------------------">https://get-stratos.io</a>, a set of tools focused on architectural correctness and distributed systems.</blockquote><blockquote>Feedback is always welcome.</blockquote><blockquote><strong>Brain</strong> — AI-assisted architectural risk reviews for existing codebases.</blockquote><blockquote><strong>Atome</strong> — A persistence platform with native serializability, idempotency and CQRS.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f726467fe4ab" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/every-line-of-code-is-technical-debt-f726467fe4ab">Every Line of Code Is Technical Debt</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When “it works in prod” becomes worse than “it works on my laptop”]]></title>
            <link>https://levelup.gitconnected.com/when-it-works-in-prod-becomes-worse-than-it-works-on-my-laptop-c922eeb1103e?source=rss-a4b7db4e2fc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/c922eeb1103e</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[organizational-culture]]></category>
            <dc:creator><![CDATA[Hugo Vantighem]]></dc:creator>
            <pubDate>Mon, 01 Jun 2026 11:40:48 GMT</pubDate>
            <atom:updated>2026-07-22T15:09:17.812Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ouEdINWActOTfHX3svxA7A.png" /><figcaption>Generated by the author using ChatGPT</figcaption></figure><p>Every engineering team accumulates technical debt. That’s normal.</p><p>The dangerous moment isn’t when the debt appears. It’s when everyone agrees it’s there — and decides to keep building on top of it anyway.</p><p>I’ve seen that shift happen in almost every engineering team I’ve worked with. It doesn’t announce itself. It arrives quietly, dressed as pragmatism. And by the time you notice it, it’s already become the default way the team operates.</p><p>It starts with a gap in knowledge. And that’s completely fine.</p><h3>The first error is innocent</h3><p>Making design or architecture mistakes isn’t a problem. We all do the best we can with the knowledge we have at the time. That’s not a failure — it’s how engineers grow. You learn by building, and sometimes you build something wrong before you know what right looks like.</p><p>The first bad design decision is usually just that: a knowledge gap. Nobody in the room knew better. They shipped with what they had.</p><h3>Then someone learns something</h3><p>Time passes. The team gains experience. Someone reads the right book, works through a gnarly bug, or joins from a company that had solved this exact problem already. The gap closes.</p><p>And with it comes the moment that defines a team’s culture.</p><p>That person — maybe you — points to the design flaw. Not to criticize, not to reopen old wounds, but because they can see it clearly now and want the team to move forward. They bring the argument. They show why it matters.</p><p>And here’s where things split.</p><h3>Two possible answers</h3><p><strong>The first answer</strong> is a technical discussion. Maybe the team agrees immediately. Maybe they push back, challenge the framing, propose a different fix. Maybe they decide the cost of changing is too high right now and park it for later. Any of that is fine. The conversation is alive. The team is reasoning together about its own code.</p><p><strong>The second answer</strong> is: <em>“Yeah but it already works like this in prod. Why change it?”</em></p><p>The conversation stops. The technical debate is over before it started. And something quietly shifts.</p><h3>The real tipping point</h3><p>When that second answer happens, the error hasn’t disappeared. It’s now fully visible — known, understood, and acknowledged by everyone in the room. But instead of becoming a problem to solve, it becomes a fact to live with.</p><p>Known.<br>Understood.<br>Accepted.<br>Normalized.</p><p>That’s the tipping point. Not the original mistake — that was just a knowledge gap. The tipping point is the moment the team decides, consciously, that a known flaw is the way things are.</p><p>We’ve moved from “we didn’t know better” to “we know, and we’re choosing not to act.” Those are fundamentally different things. The first is human. The second is a choice about what kind of team you want to be.</p><h3>The shield protects everything — including what it shouldn’t</h3><p>The pattern is corrosive because “it works in prod” gets used across the entire spectrum — and the severity of what it’s shielding rarely changes the answer.</p><p>Sometimes it’s a structural decision that’s now load-bearing: real cost, real risk, the resistance is at least understandable. The mistake is using the phrase to close the conversation rather than as a factor in a real discussion about when and how to address it.</p><p>But then there’s the case that should never be shielded.</p><p>Design flaws with real business risk attached. A service that writes to two stores. Someone points out the write isn’t atomic — a crash between the two leaves them permanently out of sync. The answer comes back: <em>“We’ve been running it for two years.”</em> Not because the concern is wrong. Because it hasn’t exploded yet.</p><p>A data model that creates silent desync under concurrent load. A sequence that can leave the database in a half-committed state on crash. An architecture that, under the right conditions — a spike, a timeout, a race — loses data.</p><p>It works in prod. <em>For now.</em> Because the conditions that trigger it haven’t aligned yet — or because they have, quietly, and nobody noticed.</p><p>At this level, “it works in prod” isn’t pragmatism. It’s a decision to accept an unquantified risk indefinitely, on behalf of users who don’t know they’re carrying it.</p><blockquote><em>The system isn’t stable.</em></blockquote><blockquote><em>It’s stable </em>so far<em>.</em></blockquote><p>The team knows the difference.</p><h3>How it compounds</h3><p>What makes this dangerous isn’t any single decision. It’s what comes after.</p><p>Because the next feature gets built on top of the flaw. Then the next one. Each decision taken in isolation is defensible — you’re adapting to what exists. But you’re also adding weight to a foundation that everyone now knows is wrong.</p><p>And when the cost of fixing finally becomes impossible to ignore, the same logic applies again: <em>“It would cost too much to redo now.”</em></p><p>A new trade-off. Based on the previous one. Which was itself based on the one before.</p><p>This is how absurd architectures are born — not from one catastrophic decision, but from a temporary shortcut that got normalized, then depended upon, then treated as untouchable. Accidental complexity doesn’t arrive all at once. It compounds, layer by layer, until it becomes the team’s technical culture.</p><h3>Why “it works in prod” is more dangerous than “it works on my laptop”</h3><p>Every developer knows what “it works on my laptop” means: the work isn’t finished. Nobody treats it as a conclusion — everyone understands it as the beginning of the real work.</p><p>“It works in production” carries the opposite social weight. It sounds like evidence. It carries the authority of real users, real load, real money. And it gets used for exactly the same purpose — to stop the conversation.</p><p>The difference is that one is obviously incomplete. The other gets mistaken for proof.</p><p>That’s what makes it more dangerous. Something that breaks locally is obviously broken. Something that works in production has inertia on its side — real users depend on it, changing it carries risk, the system resists being touched. That inertia is real. But the moment it becomes a reason to close a technical conversation rather than inform one, the phrase has shifted from a statement about stability to a shield against growth.</p><h3>What you lose — and who you lose</h3><p>The real cost isn’t code quality. That’s the surface.</p><p>What you lose is the team’s ability to reason honestly about its own system. The questions that are supposed to stay open get closed by precedent. And once the culture of closing them is established, it applies to the next problem too. And the one after.</p><p>When “it works in prod” becomes the team’s default posture, you can map it exactly onto what “it works on my laptop” reveals about an individual developer: someone who has stopped asking whether it’s right, and started asking only whether it’s currently not broken. At the individual level, that’s a conversation. At the team level, it’s a culture.</p><p>The tell is simple: watch what happens when someone raises a known problem. Does the team ask <em>“how do we address this?”</em> or <em>“why are we even talking about this?”</em> The first compounds knowledge. The second compounds debt — and has decided that’s fine.</p><p>The engineers who care most are also the ones most likely to leave when the answer is always a wall. Not because of the debt itself. Because of what the wall says about the team.</p><h3>The only thing that’s not negotiable</h3><p>Every team carries debt they can’t pay down immediately. Every team makes trade-offs under pressure. That’s not the failure.</p><p>The failure is letting the conversation die.</p><p>The technique is learnable. You can hire your way out of a knowledge gap, train your way out of a skill gap, refactor your way out of a design gap. None of those require the team to be perfect — just willing.</p><p>The willingness to keep questioning, to hear “we built this wrong” as useful information rather than a threat — that’s not a technical skill. It can’t be reviewed, tested, or measured. But it’s what determines whether a team compounds its knowledge or just compounds its debt.</p><p>Every team accumulates debt. The difference is whether it remains a conscious trade-off or becomes an unquestionable fact.</p><p>The day a team stops discussing known flaws isn’t the day the architecture fails.</p><p>It’s the day learning stops.</p><blockquote><strong>About the author</strong></blockquote><blockquote>I’m currently building <strong>Stratos </strong><a href="https://get-stratos.io/?source=user_about----------------------a4b7db4e2fc8----------------------">https://get-stratos.io</a>, a set of tools focused on architectural correctness and distributed systems.</blockquote><blockquote>Feedback is always welcome.</blockquote><blockquote><strong>Brain</strong> — AI-assisted architectural risk reviews for existing codebases.</blockquote><blockquote><strong>Atome</strong> — A persistence platform with native serializability, idempotency and CQRS.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c922eeb1103e" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/when-it-works-in-prod-becomes-worse-than-it-works-on-my-laptop-c922eeb1103e">When “it works in prod” becomes worse than “it works on my laptop”</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Read-Modify-Write isolation in NoSQL: the distributed-lock hell.]]></title>
            <link>https://levelup.gitconnected.com/read-modify-write-isolation-in-nosql-the-distributed-lock-hell-05dbe3e08072?source=rss-a4b7db4e2fc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/05dbe3e08072</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[nosql]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Hugo Vantighem]]></dc:creator>
            <pubDate>Sun, 31 May 2026 10:54:54 GMT</pubDate>
            <atom:updated>2026-07-20T14:30:20.163Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SCu14kESrsxfQWC_K10d-Q.png" /></figure><p>In <a href="https://medium.com/@hugo.vantighem/read-modify-write-is-where-nosql-concurrency-bugs-begin-c0cafb4c7c0a">part 1</a>, the single-document case was easy. In <a href="https://medium.com/@hugo.vantighem/read-modify-write-isolation-in-nosql-part-2-when-the-invariant-spans-multiple-aggregates-330e448ecf3d">part 2</a>, two documents brought Write Skew, and we saw that even a native ACID transaction — snapshot isolation — lets it through.</p><p>So teams reach for the reflex fix: a <strong>distributed lock</strong> — Redis-based, often a Redlock-style implementation. Acquire a lock on a key, do your Read → Modify → Write, release. On paper, you’ve finally serialized the critical section — operationally, at least. In practice, you’ve stepped on three mines.</p><h3>1. Network latency</h3><p>Every guarded transaction now makes extra round-trips to Redis — before <em>and</em> after hitting your NoSQL store.</p><p>You’ve doubled your coordination surface and taken a hard dependency on a second system being up, reachable, and fast on the hot path of every write.</p><p>The “fast” database is now gated by the lock service. And the coupling bites harder than the average latency suggests: every Redis tail-latency spike becomes <em>your</em> write-latency spike — your p99 inherits Redis’s p99 — and if Redis fails over mid-transaction, the lock you think you’re holding can effectively vanish on the new primary, dropping you straight into the corruption case below.</p><h3>2. Deadlock</h3><p>You can dodge deadlock entirely with a single coarse lock — but then every writer serializes on it, and you’ve thrown away the very concurrency you reached for NoSQL to get.</p><p>So to keep throughput you go fine-grained, one lock per resource — and the moment an invariant touches more than one key (across this series, it always does), deadlock is back on the table:</p><ul><li>Transaction A locks key X, then needs Y.</li><li>Transaction B locks Y, then needs X.</li><li>Both block until timeout or intervention.</li></ul><p>The textbook cure — <em>real</em> deadlock detection, maintaining a wait-for graph across every lock holder and breaking cycles as they form — is a distributed-systems project in its own right: not something you bolt onto a cache you reached for precisely to <em>save</em> engineering time.</p><p>So nobody builds it.</p><p>Instead teams impose a standing discipline: <em>always acquire locks in the same canonical order</em> — sort the keys by document ID, lock them in that order, in every code path, every time, forever.</p><p>One writer that grabs them out of order — a refactor, a new feature, a teammate who never got the memo — and the deadlock is back. That convention, plus the hopeful timeouts bolted on for when it slips, is the exact accidental complexity you adopted NoSQL to escape.</p><p>The cognitive load you tried to delete just came back wearing a Redis sticker.</p><h3>3. The TTL dilemma</h3><p>A distributed lock needs a TTL, or a crashed holder blocks everyone forever.</p><p>But the moment you set one, you’ve broken the one guarantee that mattered: <strong>you lose any coordination between the lease and the real execution time.</strong></p><p>The lock expires on a wall clock; your transaction finishes whenever it finishes — GC pause, slow disk, a network hiccup — and those two clocks have no idea the other exists.</p><p>So there is no safe value:</p><ul><li><strong>TTL too short</strong> → the lock expires <em>mid-transaction</em>. A second writer walks in, and you get exactly the corruption the lock was supposed to prevent — now with a false sense of safety.</li><li><strong>TTL too long</strong> → a crashed pod blocks the resource until expiry, and your throughput tanks under the very contention you were trying to handle.</li></ul><p>No TTL value alone can guarantee correctness across all operating conditions.</p><p>No single value is correct across all loads — because correctness constraints and throughput constraints are in direct tension, and the TTL is the single knob you’re forced to trade them off against.</p><p>This is the heart of the well-known Kleppmann-vs-Redlock debate: a lock that can <em>expire on its own</em> is not a sound mutual-exclusion primitive when you need it for correctness, only for efficiency.</p><p>Using it to protect an invariant means betting your data integrity on a timeout.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*gl0nmh0agJYrNOc3.png" /></figure><h3>So are we doomed?</h3><p>Are we really condemned to choose between the latency and deadlocks of locks, and the silent corruption of going without?</p><p>No. There is a fourth path — <strong>still within NoSQL, with no distributed lock and no external coordination service</strong> — that delivers strict isolation against inter-document Write Skew.</p><p>An approach where either everything commits, or everything rolls back, with the invariant intact. It doesn’t make the contention disappear — nothing does — it just stops bolting a Redis layer on top to manage it, and collapses the coordination back into the database itself.</p><p>That trade is the whole point, and I’ll lay it out honestly.</p><p>I laid out the full mechanics — the pure-NoSQL pattern almost nobody reaches for — in the next article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=05dbe3e08072" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/read-modify-write-isolation-in-nosql-the-distributed-lock-hell-05dbe3e08072">Read-Modify-Write isolation in NoSQL: the distributed-lock hell.</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Read-Modify-Write isolation in NoSQL, part 2: When the invariant spans multiple aggregates.]]></title>
            <link>https://levelup.gitconnected.com/read-modify-write-isolation-in-nosql-part-2-when-the-invariant-spans-multiple-aggregates-330e448ecf3d?source=rss-a4b7db4e2fc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/330e448ecf3d</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[ddd]]></category>
            <category><![CDATA[nosql]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Hugo Vantighem]]></dc:creator>
            <pubDate>Wed, 27 May 2026 06:11:26 GMT</pubDate>
            <atom:updated>2026-07-15T14:12:57.098Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Z_Ti-X3j9MVIATbyFvkEQ.png" /></figure><p>In <a href="https://medium.com/@hugo.vantighem/read-modify-write-is-where-nosql-concurrency-bugs-begin-c0cafb4c7c0a">part 1</a> we saw the single-document case, where optimistic locking saves you with a simple version field. Now we cross the line that breaks that comfort.</p><p>Let me make it concrete. Your product sells <strong>seats</strong>, and an organization buys a license capped at <strong>100 seats</strong>. Those seats are spread across many <strong>Teams</strong>, and each Team is its own aggregate with its own lifecycle. You can’t stuff the list of all teams into one document: it grows unbounded and violates every aggregate-design instinct you have.</p><p>So your invariant is a <strong>sum across aggregates</strong>:</p><blockquote><em>The sum of </em><em>seats over all Team aggregates must never exceed 100.</em></blockquote><p>To enforce that on every “add seats to a team” operation, the honest move is to read the current state across <strong>every</strong> Team and sum it — a fan-out that scans N Team documents and gets slower as the org grows. Painful, yes. But surely reading the <em>real, current</em> teams inside a transaction is at least <strong>correct</strong>? That intuition is the trap.</p><p>Now the operation is a textbook Read → Modify → Write — but watch <em>what</em> each step touches. You <strong>read and sum the Team documents</strong> as your guard, confirm there’s room, then <strong>write the 8 seats onto one Team aggregate</strong> (Team Alpha, Team Beta — each its own document). The check reads a <em>set</em> of documents; the mutation lands on <em>one</em> of them. And that&#39;s where it gets dangerous.</p><h3>The anomaly: Write Skew</h3><p>Two requests run concurrently. The teams currently sum to <strong>90</strong>.</p><pre>guard: Σ seats over all Team docs = 90   (max 100)</pre><pre>  Tx A   reads all teams → Σ = 90 → 90+8 ≤ 100 ✅ → writes Team Alpha (+8) → COMMIT<br>  Tx B   reads all teams → Σ = 90 → 90+8 ≤ 100 ✅ → writes Team Beta  (+8) → COMMIT<br>         └─ each reads its OWN snapshot — neither sees the other&#39;s in-flight<br>            write. Two DIFFERENT Team docs → no write-write conflict to abort.</pre><pre>  Σ seats across Team aggregates = 106   &gt;   license cap 100<br>  Nothing collided, nothing was overwritten.<br>  The invariant dies between the documents. That&#39;s Write Skew.</pre><p>Each transaction read a valid state and made a locally correct decision — yet the real total is now 106, and you&#39;ve oversold a 100-seat license. The subtle part the trace makes visible: the damage isn&#39;t an overwrite. It lives <em>between</em> the documents, because both transactions validated against a 90 that didn&#39;t yet include the other&#39;s write.</p><p>This is <strong>Write Skew</strong>, and it’s exactly where naive optimistic locking gives up. You’d put a version on the Team document — but Alpha and Beta were never contended; they&#39;re different documents. The contended truth is the <em>seat invariant itself</em>.</p><blockquote><strong><em>💡 Lost update vs. Write Skew — the line this whole series turns on.</em></strong><em><br>Part 1’s bug was an </em>overwrite<em>: two writes hit the </em><strong><em>same</em></strong><em> document, one erased the other, and the stored value itself came out wrong (10 instead of 11). This is the opposite. Nothing is overwritten — the two writes land on </em><strong><em>different</em></strong><em> documents, both commit cleanly, and every document stays internally consistent. The invariant breaks in the </em>gap between<em> them. Same Read → Modify → Write race, a strictly nastier failure: there’s no torn document for a code review, a unit test, or the database to catch.</em></blockquote><h3>A precise word on isolation levels</h3><p>Wrap the whole thing in a native MongoDB multi-document transaction (≥ 4.0 on replica sets, 4.2+ on sharded clusters) and you get <strong>snapshot isolation</strong>: every transaction sees a consistent point-in-time snapshot of the database. That genuinely eliminates the classic ANSI read anomalies — <strong>dirty reads</strong>, <strong>non-repeatable reads</strong>, and even <strong>phantoms</strong> (the snapshot is frozen, so rows born after it are simply invisible) — plus single-document lost updates.</p><p>What it does <strong>not</strong> give you, on its own, is full <strong>serializability</strong> — so it can’t stop Write Skew. The subtle part most people miss: your clean snapshot isn’t enough, because the <em>concurrent</em> transaction is reading its <strong>own</strong> snapshot — stale relative to yours — and writing based on it. Two consistent snapshots, two valid decisions, one broken invariant.</p><p>Here’s the mental key most devs skip: <strong>the invariant is never encoded as a write conflict.</strong> WiredTiger (MongoDB’s storage engine) only aborts a transaction when two of them write the <em>same</em> document. Tx A wrote Team Alpha, Tx B wrote Team Beta — different documents, so there&#39;s nothing for WiredTiger to abort. The constraint lives in your head and your validation check, not in the data the engine is watching for conflicts. Snapshot isolation protects the bytes; it can&#39;t protect a rule it was never told about.</p><p>So the fix — whatever you reach for — has to do the one thing the engine never did for you: <strong>make the invariant part of what it watches for conflicts.</strong> And here’s the uncomfortable preview of everything that follows: <em>every</em> way of doing that ends up serializing these writes somehow, and every one sends you a bill.</p><pre>the rule    Σ(team.seats) ≤ 100              ← the engine never watches this</pre><pre>the move    materialize it into one doc every writer must also touch:<br>            license = { usedSeats: 90, maxSeats: 100 }<br>            → the invisible skew becomes a write-write conflict it CAN catch<br>              (doing it right — and what it costs — is the rest of this series)</pre><h3>The pattern underneath</h3><p>Strip it back and the lesson is one sentence. Write skew isn’t a flaw in transactions, and MongoDB isn’t “wrong.” <strong>Write skew is what happens when an invariant never becomes part of the database’s conflict-detection model</strong> — a mismatch between the <em>scope you validate</em> (all the Team docs) and the <em>scope the engine watches for conflicts</em> (the one doc you write). The same read scope ≠ write scope gap from the guard above, all the way up.</p><p>Hold that sentence — it’s the lens for everything that follows. Every cure from here is just a different answer to one question: <em>how do I drag the invariant into something that serializes these writes?</em> And not one of them is free.</p><h3>Where this leads</h3><p>So we reach for the reflex everyone tries first: a distributed lock. Freeze the world around the read and the write with Redis, and on paper you’re finally serializable. In practice it’s a minefield — latency, deadlocks, and a TTL dilemma with no good answer.</p><p>That’s where things get ugly. Part 3.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=330e448ecf3d" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/read-modify-write-isolation-in-nosql-part-2-when-the-invariant-spans-multiple-aggregates-330e448ecf3d">Read-Modify-Write isolation in NoSQL, part 2: When the invariant spans multiple aggregates.</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>