<?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 Vinicius Rossado on Medium]]></title>
        <description><![CDATA[Stories by Vinicius Rossado on Medium]]></description>
        <link>https://medium.com/@viniciusrossado?source=rss-63114b03eecf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*A735sAR8uv5KW-4zKg0FEg.png</url>
            <title>Stories by Vinicius Rossado on Medium</title>
            <link>https://medium.com/@viniciusrossado?source=rss-63114b03eecf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 16:09:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@viniciusrossado/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[What Does a Missing Fact Mean? A Developer’s First Tour of RDF, SKOS, OWL, SHACL, and SPARQL]]></title>
            <link>https://medium.com/@viniciusrossado/what-does-a-missing-fact-mean-a-developers-first-tour-of-rdf-skos-owl-shacl-and-sparql-80659187e86b?source=rss-63114b03eecf------2</link>
            <guid isPermaLink="false">https://medium.com/p/80659187e86b</guid>
            <category><![CDATA[sparql]]></category>
            <category><![CDATA[knowledge-graph]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[semanticweb]]></category>
            <category><![CDATA[rdf]]></category>
            <dc:creator><![CDATA[Vinicius Rossado]]></dc:creator>
            <pubDate>Sat, 05 Sep 2026 15:24:03 GMT</pubDate>
            <atom:updated>2026-09-05T15:24:03.016Z</atom:updated>
            <content:encoded><![CDATA[<p>I have a Turtle file on my laptop with 38,776 triples describing every country on Earth — ISO codes, capitals, populations, currencies, neighbours, spoken languages. It’s GeoNames’ public country table converted to RDF: exactly the kind of reference data every company eventually ends up maintaining a worse version of.</p><p>It says there are 252 countries. It gives a capital city for 246 of them.</p><p>Six countries have no capital in the file. Not null, not an empty string — the fact is simply <em>not there</em>. And here&#39;s the thing that makes this stack worth learning: those six absences do not all mean the same thing.</p><ul><li><strong>Antarctica</strong> has no capital because it has no government.</li><li><strong>Bouvet Island</strong> and <strong>Heard Island and McDonald Islands</strong> have no capital because nobody lives there.</li><li><strong>Tokelau</strong> genuinely has no single capital — its three atolls take turns hosting the government.</li><li><strong>Bonaire, Saint Eustatius and Saba</strong> is one row standing in for three separate islands.</li><li><strong>United States Minor Outlying Islands</strong> is a bookkeeping bucket, not a place.</li></ul><p>One of those is “doesn’t exist”. One is “exists but is unnameable”. One is “the model is wrong”. And RDF stores all six identically: as nothing at all.</p><p>The Semantic Web stack — RDF, SKOS, OWL, SHACL, SPARQL — is older, more boring, and more production-ready than its academic reputation suggests. It powers Wikidata, Google’s Knowledge Graph lineage, most national libraries, and a growing pile of enterprise knowledge graphs. But it’s confusing from the outside, because five technologies seem to overlap.</p><p>Here’s the secret that untangles all of them. Each tool is an answer to that same deceptively simple question:</p><blockquote><strong><em>What does a missing fact mean?</em></strong></blockquote><ul><li>To <strong>OWL</strong>, a missing fact is <em>unknown</em> — it might still be true.</li><li>To <strong>SHACL</strong>, a missing fact is a <em>violation</em> — if a rule required it.</li><li>To <strong>SPARQL</strong>, a missing fact simply <em>doesn’t come back</em>.</li><li>To <strong>SKOS</strong>, the question barely applies — it’s organizing words, not policing facts.</li></ul><p>Hold on to that question. Everything below is built on it, using one running example: that country dataset. Every count, query result, and quirk in this article came out of actually running it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fh1cuWZOMKz0KQnObDWSdA.png" /><figcaption>Five technologies, one question: what does a missing fact mean?</figcaption></figure><h3>Everything is a triple: RDF</h3><p>RDF (Resource Description Framework) is a data model with exactly one structure: the <strong>triple</strong>. Every fact has three parts, always in this order:</p><ul><li><strong>Subject</strong> — the thing you’re describing. An IRI (a URI — think “global primary key”) or a blank node.</li><li><strong>Predicate</strong> — the relationship or attribute. Always an IRI.</li><li><strong>Object</strong> — the value. An IRI, a <strong>literal</strong> (string, number, date), or a blank node.</li></ul><p>That’s the whole model. No tables, no columns, no documents. A “row” with ten attributes is just ten triples that share a subject.</p><p>The standard human-friendly syntax is <strong>Turtle</strong>. Here is Denmark, copied straight out of the file:</p><pre>@prefix rdf:  &lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&gt; .<br>@prefix xsd:  &lt;http://www.w3.org/2001/XMLSchema#&gt; .<br>@prefix skos: &lt;http://www.w3.org/2004/02/skos/core#&gt; .<br>@prefix :     &lt;http://example.com/demo/&gt; .<br> <br>:Country\/DK a :Country ;<br>    :iso_3166-1_alpha-2_code &#39;DK&#39;^^xsd:string ;<br>    :iso_3166-1_alpha-3_code &#39;DNK&#39;^^xsd:string ;<br>    :country_name            &#39;Denmark&#39;^^xsd:string ;<br>    skos:prefLabel           &#39;Denmark&#39;@en ;<br>    :area_in_sq_km           &#39;43094&#39;^^xsd:double ;<br>    :population              &#39;5797446&#39;^^xsd:integer .<br> <br>:Country\/DK :capital          &#39;Copenhagen&#39;^^xsd:string .<br>:Country\/DK :part_of_continent :Continent\/EU .<br>:Country\/DK :uses_currency     :Currency\/DKK .</pre><p>Reading guide: @prefix declares shorthand for long IRIs. The a is an abbreviation for rdf:type (&quot;is a&quot;). The semicolon means &quot;same subject, next predicate&quot;. Every statement ends with a period. And yes — \/ is a legal escape inside a Turtle local name; :Country\/DK resolves to the IRI http://example.com/demo/Country/DK. It looks alarming and is completely fine.</p><p>Two things make this more than a quirky serialization format:</p><p><strong>The graph emerges by itself.</strong> :Continent\/EU is the <em>object</em> of one triple and, elsewhere in the file, the <em>subject</em> of its own:</p><pre>:Continent\/EU a :Continent ;<br>    :continent_code &#39;EU&#39;^^xsd:string ;<br>    :continent_name &#39;Europe&#39;^^xsd:string ;<br>    skos:prefLabel  &#39;Europe&#39;@en .</pre><p>Chain enough triples and you have a graph — no foreign keys, no join tables, no schema migration to add an attribute. A new fact is just a new triple.</p><p><strong>Identity is global.</strong> Because subjects and predicates are IRIs, two datasets that both mention :Currency\/EUR are talking about the same node. In this file, dozens of countries point at that one currency resource; add a second dataset with exchange rates keyed on the same IRI and merging is <em>set union</em>. Try that with two SQL databases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7DyDCUjo0eSYuuTQuEC7QQ.png" /><figcaption>Denmark as triples: :Continent/EU is an object here and a subject elsewhere.</figcaption></figure><h4>Three details beginners trip on</h4><p><strong>1. Literals with language tags are different literals.</strong> Look at the Denmark block again — the string “Denmark” appears twice:</p><pre>:country_name  &#39;Denmark&#39;^^xsd:string ;   # a plain string<br>skos:prefLabel &#39;Denmark&#39;@en ;            # rdf:langString — NOT equal</pre><p>Those are two different RDF terms. A query filtering on the untagged string will not match the tagged one, even though they look identical on screen. (SPARQL workaround later.)</p><p>While we’re here: since RDF 1.1, a plain literal &#39;Denmark&#39; already <em>is</em> an xsd:string. Writing &#39;Denmark&#39;^^xsd:string is redundant noise — and this file does it on more than seventeen thousand literals, because it was generated by a converter that didn&#39;t know. Real datasets are full of this. It&#39;s harmless, but it&#39;s a tell.</p><p><strong>2. Objects can be blank nodes.</strong> A blank node is a resource with no IRI — structure that doesn’t deserve a global name. This isn’t an academic corner case: OWL restrictions and RDF lists live entirely in blank nodes. But beware: a blank node’s identity is <em>local to the document</em>. Re-sending the same INSERT DATA block mints brand-new blank nodes every time — duplicating structure instead of being idempotent. If you&#39;ll ever need to reference or update the thing, give it an IRI. (Which, as we&#39;re about to see, is exactly what this dataset does.)</p><p><strong>3. There is no “null”.</strong> Antarctica doesn’t have a :capital of null. The triple simply doesn&#39;t exist. Which brings us back to the central question: what does that absence <em>mean</em>? RDF itself refuses to answer. The rest of the stack is different answers.</p><p>And the flip side, which is worse. Five countries in this file have :population &#39;0&#39;^^xsd:integer. Four of them — Antarctica, Bouvet Island, Heard Island, the US Minor Outlying Islands — are genuinely uninhabited. The fifth is <strong>Eritrea</strong>, a country of roughly three million people.</p><p>Somewhere upstream, “we don’t have this number” was written down as 0. That&#39;s the entire lesson of this article, inverted: an absent triple would have preserved the distinction between <em>unknown</em> and <em>zero</em>. Encoding the unknown as a value destroyed it, and no tool downstream can get it back.</p><h3>Attaching facts to a relationship</h3><p>Here’s a question everyone asks in week one: a triple has three slots, so where do I put an attribute <em>of the relationship itself</em>?</p><p>This dataset needs exactly that. Denmark speaks Danish, English, and Faroese — but not equally, and the file wants to record the ranking. “Denmark → speaks → Danish” has nowhere to hang a rank. So it does this:</p><pre>:Country_Language\/DK_lang_1 a :Country_Language ;<br>    :spoken_in      :Country\/DK ;<br>    :language_value :Language\/dan ;<br>    :rank           &#39;1&#39;^^xsd:integer .<br> <br>:Country_Language\/DK_lang_2 a :Country_Language ;<br>    :spoken_in      :Country\/DK ;<br>    :language_value :Language\/eng ;<br>    :rank           &#39;2&#39;^^xsd:integer .</pre><p>The relationship got promoted to a node. This is the <strong>n-ary relation</strong> pattern (sometimes “qualified relation”), and it’s the standard RDF answer to edge properties. Wikidata does the same thing under the name “statements with qualifiers”.</p><p>Two practical notes. First, the intermediate node has a real IRI rather than being a blank node — which is why re-running the import is idempotent, and why you can point at DK_lang_2 to correct it later. Second, this is the honest cost of RDF&#39;s three-slot model, and it&#39;s the sharpest difference from labeled property graphs like Neo4j, where an edge just carries a {rank: 2} map. Which model you want depends on whether you value the uniformity or resent the extra hop. (That comparison is the next post in this series.)</p><h3>Schema and data: TBox and ABox</h3><p>Before the interesting tools, one piece of vocabulary you’ll see everywhere. Ontology people split a graph in two:</p><ul><li><strong>TBox</strong> (terminological): the definitions — classes, properties, hierarchies. :Country rdfs:subClassOf :Place. The schema.</li><li><strong>ABox</strong> (assertional): the data — individuals and their facts. :Country\/DK a :Country. The rows.</li></ul><p>A reasoner classifies the ABox <em>using</em> the TBox. Which also explains a classic beginner surprise, in both directions.</p><p>Download a famous published ontology, run SELECT ?s WHERE { ?s a ?class }, and you get back owl:Class and owl:ObjectProperty instead of any actual things — most published &quot;ontologies&quot; are pure TBox. No instances, only definitions.</p><p>Our country file is the exact opposite: 38,776 triples of pure ABox. It declares :Country, :Continent, :Currency, and :Language as types and never once says what they <em>are</em>. There is no rdfs: prefix in the file at all. No subClassOf, no domain, no range, no cardinality — nothing a reasoner could use.</p><p>That’s not a criticism; it’s the normal starting state of exported data, and it’s a useful thing to recognize. Everything from here on is the TBox we’re going to add on top.</p><p>In practice teams keep the two in separate graphs: the TBox versioned like code (pull requests, review, CI), the ABox flowing in through ingestion pipelines.</p><h3>Organizing words: SKOS and thesauri</h3><p>Now the most underrated member of the family. Long before ontologies, librarians had already solved “how do we index the world” with <strong>thesauri</strong>: controlled vocabularies where each concept has preferred and alternative labels, broader and narrower concepts, and “see also” links. SKOS (Simple Knowledge Organization System) is that tradition, standardized as RDF.</p><p>Our file has a foot in the door already — it puts skos:prefLabel on every country, continent, currency, and language. That&#39;s it, though: 8,014 prefLabels, zero altLabel, zero broader. It imported the namespace and used one property. Also very normal.</p><p>So let’s build the part it’s missing. The key mental shift first: a SKOS concept is <strong>not a class</strong>. region:Scandinavia doesn&#39;t define what a Scandinavian country <em>is</em>, or which properties its instances must have. It&#39;s an entry in an indexing vocabulary — a shared, hierarchical set of tags with real semantics.</p><pre>@prefix skos:   &lt;http://www.w3.org/2004/02/skos/core#&gt; .<br>@prefix region: &lt;https://example.org/regions/&gt; .<br> <br>region:scheme a skos:ConceptScheme ;<br>    skos:prefLabel     &quot;World regions&quot;@en ;<br>    skos:hasTopConcept region:Europe .<br> <br>region:Europe a skos:Concept ;<br>    skos:prefLabel &quot;Europe&quot;@en ;<br>    skos:prefLabel &quot;Europa&quot;@pt ;<br>    skos:inScheme  region:scheme .<br> <br>region:NorthernEurope a skos:Concept ;<br>    skos:prefLabel &quot;Northern Europe&quot;@en ;<br>    skos:altLabel  &quot;the Nordics&quot;@en , &quot;Norden&quot;@en ;<br>    skos:broader   region:Europe ;<br>    skos:inScheme  region:scheme .<br> <br>region:Scandinavia a skos:Concept ;<br>    skos:prefLabel &quot;Scandinavia&quot;@en ;<br>    skos:broader   region:NorthernEurope ;<br>    skos:related   region:Baltics ;<br>    skos:inScheme  region:scheme .</pre><p>The core vocabulary is small and battle-tested:</p><ul><li>skos:prefLabel — the one display label, <strong>one per language</strong> (note the English and Portuguese labels above — that&#39;s fine; two English prefLabels would not be).</li><li>skos:altLabel — synonyms, abbreviations, spelling variants. This is what makes search work: a user typing &quot;the Nordics&quot; finds &quot;Northern Europe&quot;, and — the example every dataset needs — someone typing &quot;Holland&quot; finds the Netherlands.</li><li>skos:broader / skos:narrower — the hierarchy. Scandinavia has the broader concept Northern Europe. (Direction trips everyone: broader points <em>up</em>, from specific to general.)</li><li>skos:related — associative, non-hierarchical &quot;see also&quot;.</li><li>skos:exactMatch / skos:closeMatch — mapping <em>between</em> vocabularies. This is the one that pays for itself: link region:Europe to the equivalent concept in the UN M49 scheme, or in a partner&#39;s region taxonomy, and integration becomes data instead of a mapping table in someone&#39;s utils.py.</li></ul><p>Then tag the countries with dct:spatial:</p><pre>@prefix dct: &lt;http://purl.org/dc/terms/&gt; .<br> <br>:Country\/DK dct:spatial region:Scandinavia .<br>:Country\/NO dct:spatial region:Scandinavia .<br>:Country\/FI dct:spatial region:NorthernEurope .</pre><p>Notice what we did <em>not</em> do: we didn’t say :Country\/DK a region:Scandinavia. Denmark is an instance of :Country. Scandinavia is a tag, not a type. Keeping that line clean is most of what &quot;using SKOS correctly&quot; means.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QhHXQFdPmWJIoksToK_x4w.png" /><figcaption>A regions thesaurus: prefLabel, altLabel, and the broader ladder.</figcaption></figure><h4>SKOS was designed to not need a reasoner</h4><p>Here’s a design decision worth understanding, because it teaches you how the whole stack thinks.</p><p>skos:broader is deliberately <strong>not</strong> a transitive property. Scandinavia is broader&#39;d to Northern Europe, Northern Europe to Europe — but SKOS does not force &quot;Scandinavia broader Europe&quot; into existence. A separate property, skos:broaderTransitive, exists to represent the closure when you want it. Why? So that thesauri work under plain SPARQL, with no inference engine running. As we&#39;ll see, a one-character property path (skos:broader+) gives you the transitive closure at query time anyway.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MY_QNr-8DNNbMR__dNJnRg.png" /><figcaption>Materialize the closure with a reasoner, or walk it at query time with skos:broader+.</figcaption></figure><p>It is worth knowing exactly how this fails, because it does not fail loudly. I ran the three-concept chain above through Jena’s reasoners:</p><ul><li><strong>no reasoner</strong>: nothing</li><li><strong>RDFS</strong>: NorthernEurope — <strong>one hop only</strong></li><li><strong>OWL (</strong><strong>OWLFBRuleReasoner)</strong>: NorthernEurope, Europe</li><li><strong>skos:broader+, no reasoner</strong>: NorthernEurope, Europe</li></ul><p>The RDFS reasoner applies the rdfs:subPropertyOf axiom (broader is a sub-property of broaderTransitive) but not the owl:TransitiveProperty one. So you switch inference on, see broaderTransitive triples appear, conclude it worked — and the deep hierarchy is quietly missing. A half-working reasoner is a much worse bug than one that does nothing, and the one-character property path gets the right answer without either.</p><p>Same story for data quality: the SKOS spec defines integrity conditions — a concept’s prefLabel, altLabel, and hiddenLabel must be pairwise disjoint (S13); one prefLabel per language (S14); related must not overlap with broaderTransitive (S27); mapping properties like exactMatch disjoint with broadMatch and relatedMatch (S46). Some of these — S14&#39;s one-per-language cardinality is the canonical example — <strong>can&#39;t be expressed in OWL at all</strong>, and even the ones that can are conditions to <em>check</em> against your data, not axioms a reasoner uses to <em>deduce</em> new facts. That&#39;s why every serious SKOS validator (qSKOS is the classic) is built on SPARQL queries — a perfect preview of the OWL-vs-SHACL split coming next.</p><p>If your problem is “organize tags/categories/regions with synonyms, hierarchy, and multilingual labels” — you don’t need an ontology. You need SKOS, and you’ll be in the company of every library and museum on the planet.</p><h3>Inferring what you didn’t say: OWL and ontologies</h3><p>An <strong>ontology</strong> goes further than a vocabulary: it defines what things <em>are</em> and what follows logically from your facts. OWL (Web Ontology Language) is RDF plus logic — you assert axioms, and a <strong>reasoner</strong> deduces new triples you never wrote.</p><p>Remember our file has no TBox at all. Here’s a small one:</p><pre>@prefix rdfs: &lt;http://www.w3.org/2000/01/rdf-schema#&gt; .<br>@prefix owl:  &lt;http://www.w3.org/2002/07/owl#&gt; .<br> <br>:Country   rdfs:subClassOf :Place .<br>:Continent rdfs:subClassOf :Place .<br> <br>:has_country_neighbour a owl:SymmetricProperty .<br> <br>:has_language_entry owl:inverseOf :spoken_in .</pre><p>Run a reasoner over the data with those three axioms and it materializes triples nobody wrote:</p><ul><li>:Country\/DK a :Place and :Continent\/EU a :Place — from the subclass axioms. Ask for &quot;all places&quot; and both show up.</li><li>Because :spoken_in now has an inverse, you can navigate from Denmark <em>to</em> its language entries, not just from the entries to Denmark. The file only ever asserted one direction.</li></ul><p>That’s the pitch: model the rules once, and the graph enriches itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ncog9RTPuk8En58LRoR7Nw.png" /><figcaption>Two axioms, two triples nobody wrote.</figcaption></figure><p>The symmetry axiom is the interesting one. This dataset asserts both directions by hand — Portugal has Spain as a neighbour, and Spain separately has Portugal. Declaring owl:SymmetricProperty means you only need to <em>store</em> one direction and still get both when you query. That&#39;s real: the file carries 654 directed neighbour statements, 99% of them reciprocated — so roughly half are redundant, and the eight that <em>aren&#39;t</em> reciprocated are almost certainly bugs a symmetric property would have papered over.</p><p>More useful building blocks: owl:TransitiveProperty (containment chains propagate) and owl:sameAs (two IRIs denote one thing — the backbone of linked-data integration, and how you&#39;d merge this file&#39;s :Country\/DK with Wikidata&#39;s wd:Q35).</p><h4>The open-world assumption, and how it bites</h4><p>OWL evaluates everything under the <strong>Open World Assumption (OWA)</strong>: the graph is a collection of things <em>known so far</em>, never a complete description. A missing fact is not false — it’s unknown.</p><p>For inference, that’s exactly right. For validation, it’s a trap, and it’s the number-one conceptual error of everyone arriving from databases. Watch what happens when you try to use OWL to enforce our opening observation — that a country ought to have a capital:</p><pre># &quot;Every country has exactly one capital&quot;<br>:Country rdfs:subClassOf [<br>    a owl:Restriction ;<br>    owl:onProperty  :capital ;<br>    owl:cardinality &quot;1&quot;^^xsd:nonNegativeInteger<br>] .<br> <br>:Country\/AQ a :Country ;<br>    :country_name &#39;Antarctica&#39;^^xsd:string .</pre><p>Antarctica has no capital. Surely the reasoner complains about the six missing ones?</p><p>It does something far stranger: <strong>it concludes they exist.</strong> Under the open world, a cardinality restriction is not a check on your data — it’s an <em>assertion about the world</em>. You said every country has exactly one capital; Antarctica is a country; therefore Antarctica has a capital you simply haven’t named yet. The reasoner invents an anonymous city and moves on, perfectly satisfied.</p><p>No error. No warning. Your “validation” is silently founding settlements in Antarctica.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U9Z1S7HFohZpO8CtbvgKdA.png" /><figcaption>Same rule, opposite behaviour: OWL invents the capital, SHACL reports six violations.</figcaption></figure><p>Could OWL <em>ever</em> complain here? Only from the other direction: give one country <strong>two</strong> capitals, explicitly declare them distinct (owl:AllDifferent), and now the max side of the cardinality is violated and the ontology becomes inconsistent. You need that explicit distinctness because OWL also has <strong>no Unique Name Assumption</strong>: two different IRIs might denote the same individual. Given a max-cardinality of 1 and two IRIs as values, a reasoner&#39;s preferred move isn&#39;t to raise an error — it&#39;s to conclude the two IRIs are owl:sameAs each other.</p><p>(With two <em>literal</em> values — say two different capital strings on a functional property — you do get an inconsistency, because literals are distinct by value. But even then the diagnosis is “your ontology is inconsistent”, not “Antarctica failed validation”.)</p><p>The takeaway is not “OWL is broken”. The takeaway is: <strong>OWL answers ‘what else is true?’, and no ontology axiom will ever answer ‘is this data acceptable?’</strong> For that question, the stack has a different tool.</p><p>One practical warning before we get there: the reasoners embedded in triplestores (Jena/Fuseki’s built-ins, for example) implement RDFS and rule-based fragments of OWL — incompletely, by design. The classic “classification by restriction” magic from the Protégé Pizza tutorial requires a full OWL DL reasoner (HermiT, Pellet/Openllet, Konclude). If you flip on the default reasoner in Fuseki and nothing happens, that’s why.</p><h3>Validating what’s actually there: SHACL</h3><p>SHACL (Shapes Constraint Language) is the answer to the question OWL refuses to answer. It evaluates your graph under the <strong>Closed World Assumption</strong>: the data in front of me is all there is, and I will judge it as it stands. Think “JSON Schema for graphs” — you declare <strong>shapes</strong>, run a validator, and get a structured report.</p><pre>@prefix sh: &lt;http://www.w3.org/ns/shacl#&gt; .<br> <br>:CountryShape a sh:NodeShape ;<br>    sh:targetClass :Country ;<br>    sh:property [<br>        sh:path     :country_name ;<br>        sh:minCount 1 ;<br>        sh:maxCount 1 ;<br>        sh:datatype xsd:string ;<br>    ] ;<br>    sh:property [<br>        sh:path     :iso_3166-1_alpha-2_code ;<br>        sh:minCount 1 ;<br>        sh:maxCount 1 ;<br>        sh:pattern  &quot;^[A-Z]{2}$&quot; ;<br>    ] ;<br>    sh:property [<br>        sh:path     :capital ;<br>        sh:minCount 1 ;<br>        sh:message  &quot;Every country needs a capital&quot; ;<br>    ] ;<br>    sh:property [<br>        sh:path         :part_of_continent ;<br>        sh:minCount     1 ;<br>        sh:class        :Continent ;<br>    ] .</pre><p>Validate our file against that and you get what you wanted all along:</p><pre>[] a sh:ValidationReport ;<br>   sh:conforms false ;<br>   sh:result [<br>       a sh:ValidationResult ;<br>       sh:resultSeverity sh:Violation ;<br>       sh:focusNode      :Country\/AQ ;<br>       sh:resultPath     :capital ;<br>       sh:resultMessage  &quot;Every country needs a capital&quot; ;<br>   ] .<br>   # ... and five more</pre><p>Six actual errors, pointing at six actual nodes, with your own message. Wire the validator into your ingestion pipeline (every mainstream RDF library ships one — Jena, pySHACL, dotNetRDF, TopBraid), fail the batch on sh:conforms false, and corrupt data dies at the door.</p><p>One precision worth keeping: under SHACL, absence alone is not a violation. A missing fact violates <strong>only if some constraint required it</strong> — sh:minCount 1 and it&#39;s not there, sh:datatype xsd:integer and it&#39;s a string. The closed world doesn&#39;t mean &quot;everything must be present&quot;; it means &quot;I judge exactly what&#39;s present, no benefit of the doubt&quot;.</p><h4>And the one it still won’t catch</h4><p>Now go back to Eritrea. Add the obvious population constraint:</p><pre>sh:property [<br>        sh:path         :population ;<br>        sh:minCount     1 ;<br>        sh:datatype     xsd:integer ;<br>        sh:minInclusive 0 ;<br>    ] ;</pre><p>Eritrea passes. The value is present, it’s an integer, it’s ≥ 0. Every structural check is green and the number is off by three million.</p><p>Constraint languages check <em>shape</em>, not <em>truth</em>. SHACL will happily tell you a field is missing, malformed, or out of range — it cannot tell you that a plausible value is wrong. The only way to reach this one is a constraint that encodes domain knowledge, e.g. “a country with a capital city and three land neighbours does not have zero inhabitants” — expressible as sh:sparql, but you have to think of it first.</p><p>That’s the honest boundary of validation, and it’s worth internalizing before you promise anyone that a schema makes data correct.</p><h3>Asking questions: SPARQL</h3><p>SPARQL is the query language over all of the above, and it’s the piece that will feel most familiar. Instead of tables and JOINs, you write <strong>triple patterns with variables</strong>, and the engine returns every binding that matches.</p><p>Here’s the query this whole article started with — the one that found our six countries:</p><pre>PREFIX : &lt;http://example.com/demo/&gt;<br> <br>SELECT ?name WHERE {<br>    ?c a :Country ;<br>       :country_name ?name .<br>    FILTER NOT EXISTS { ?c :capital ?capital }<br>}<br>ORDER BY ?name</pre><p>FILTER NOT EXISTS is how you ask about absence — the closest thing SPARQL has to IS NULL, except it&#39;s asking &quot;no such triple&quot; rather than &quot;a column holding null&quot;.</p><p>Joins are implicit: use the same variable in two patterns and they must bind to the same value. The rest maps onto SQL instincts — FILTER for conditions, OPTIONAL as LEFT JOIN, UNION for alternatives, and full aggregation:</p><pre>PREFIX : &lt;http://example.com/demo/&gt;<br> <br>SELECT ?continent (COUNT(?c) AS ?countries) (SUM(?pop) AS ?people)<br>WHERE {<br>    ?c a :Country ;<br>       :population ?pop ;<br>       :part_of_continent ?cont .<br>    ?cont :continent_name ?continent .<br>}<br>GROUP BY ?continent<br>HAVING (COUNT(?c) &gt; 10)<br>ORDER BY DESC(?people)</pre><p>And the thesaurus payoff, tying SKOS back in:</p><pre>PREFIX :       &lt;http://example.com/demo/&gt;<br>PREFIX dct:    &lt;http://purl.org/dc/terms/&gt;<br>PREFIX skos:   &lt;http://www.w3.org/2004/02/skos/core#&gt;<br>PREFIX region: &lt;https://example.org/regions/&gt;<br> <br>SELECT ?name WHERE {<br>    ?c a :Country ;<br>       :country_name ?name ;<br>       dct:spatial ?r .<br>    ?r skos:broader* region:Europe .<br>}</pre><p>skos:broader<em> is a </em><strong><em>property path</em></strong><em> — &quot;zero or more </em><em>broader hops&quot;. The query returns countries tagged </em>Europe<em> or tagged with </em><strong><em>any concept anywhere below it</em></strong><em> (Northern Europe, Scandinavia, and whatever sub-regions you add next year), with no reasoner, no recursive CTE, no application-side loop. One character, </em>.</p><p>Property paths are the best power-to-syntax ratio in the language:</p><ul><li>:has_country_neighbour/:country_neighbour_value — chain: hop through the n-ary node straight to the neighbouring country</li><li>skos:broader+ — one or more hops (strict ancestors)</li><li>^:spoken_in — inverse: from a country to its language entries, without needing that owl:inverseOf axiom at all</li><li>(skos:broader|^skos:narrower)+ — climb the hierarchy even if some sources only asserted the narrower direction</li><li>a/rdfs:subClassOf<em> — instances of a class </em>or any subclass*: most of what people want RDFS inference for, at query time</li></ul><p>That third one is worth a pause. Half the reasons people reach for a reasoner evaporate when they discover property paths.</p><h4>The three gotchas that cost real hours</h4><p><strong>1. The language-tag mismatch.</strong> Remember Denmark carrying “Denmark” twice. Query FILTER(?label = &quot;Denmark&quot;) against skos:prefLabel and you get zero rows, because the tagged and untagged literals are different RDF terms. Compare the string form instead — FILTER(STR(?label) = &quot;Denmark&quot;) — and check the language separately with LANG(?label) when it matters.</p><p><strong>2. The default-graph trap.</strong> A SPARQL endpoint doesn’t store “a graph” — it stores a <strong>dataset</strong>: one default graph plus any number of <strong>named graphs</strong> (the standard way to partition TBox/ABox, sources, tenants, versions). The rule nobody tells you: a pattern written outside a GRAPH clause is evaluated <strong>only against the default graph</strong>. Load this file into a named graph and SELECT * WHERE { ?s ?p ?o } is a perfectly correct query that returns zero rows. No error — it&#39;s just pointing at an empty room. The fix:</p><pre>SELECT ?s ?p ?o WHERE {<br>    GRAPH ?g { ?s ?p ?o }<br>}</pre><p>(Corollary: GRAPH ?g { A . B } requires A and B to hold in the <em>same</em> graph. To join across graphs, give each part its own graph variable. And some stores can make the default graph the union of everything — unionDefaultGraph in Jena — which makes the naive query work.)</p><p><strong>3. Aggregates always return a row.</strong> COUNT over a pattern that matches nothing returns <em>one row containing 0</em> — not zero rows. Combine with gotcha #2 and you get the classic afternoon-long debugging session: &quot;my 38,000-triple dataset is empty?!&quot; No — your query is counting an empty default graph, and the 0 looks exactly like an answer.</p><p>Which, if you’ve been paying attention, is the same failure as Eritrea’s population. A zero that means “nothing was there” is indistinguishable from a zero that means zero.</p><h3>The one-table summary</h3><p>Back to the question we started with. The entire stack, in four rows:</p><ul><li><strong>You want to deduce structure you didn’t assert</strong> → OWL + reasoner. A missing fact is <em>unknown — it may exist</em> (and cardinality will happily conclude it does).</li><li><strong>You want to check that data obeys rules</strong> → SHACL. A missing fact is a <em>violation, if a constraint required it</em> — and a wrong-but-plausible value is still nobody’s problem.</li><li><strong>You want to ask what’s there</strong> → SPARQL. A missing fact <em>just doesn’t come back</em> (watch the lonely 0 from COUNT).</li><li><strong>You want to organize vocabulary for indexing and search</strong> → SKOS. Labels, hierarchy, mappings — no world assumption needed.</li></ul><p>And the production shape of a knowledge graph project, end to end: map source data to RDF → <strong>validate with SHACL</strong> at ingestion → <strong>enrich with OWL</strong> (materialize inferences into their own named graph) → serve <strong>SPARQL</strong> (with property paths doing the everyday “inference”) → organize all human-facing categorization in <strong>SKOS</strong>. Validate before you infer — reasoning over garbage produces industrial quantities of derived garbage.</p><p>If you’re starting from zero, start smaller than you think. Find a messy reference dataset you actually care about — countries, products, org charts, your CI pipeline’s history — convert a slice of it to Turtle, drop Apache Jena Fuseki in a container, and write ten SPARQL queries against it. That is exactly what this article is: the data is GeoNames’ countryInfo.txt (CC BY 4.0), converted to Turtle; the queries were run with rdflib and Apache Jena Fuseki 5.1, and the validation report came out of pySHACL. You&#39;ll learn more from one skos:broader* query over your own data than from any paper on description logics.</p><p>And you’ll find your own Eritrea. Every real dataset has one: a place where somebody had to decide what to do about a fact they didn’t have, and chose a value instead of an absence. Finding it is the moment the question stops being philosophical.</p><h3>The Knowledge Graphs series</h3><p>This article opens a new brick wall — a series on knowledge graphs for working developers. 🟩 bricks are laid, ⬜ bricks are coming:</p><ul><li>🟩 <strong>What Does a Missing Fact Mean? RDF, SKOS, OWL, SHACL, and SPARQL — you are here</strong></li><li>⬜ RDF vs Labeled Property Graphs: when to pick Neo4j instead (coming soon)</li><li>⬜ dotNetRDF: SPARQL and SHACL from C# (coming soon)</li><li>⬜ Building a knowledge-graph engine for MTG Commander decks (coming soon)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80659187e86b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Feature Flags with Deterministic Hashing: Canary Rollouts by User in .NET]]></title>
            <link>https://medium.com/@viniciusrossado/feature-flags-with-deterministic-hashing-canary-rollouts-by-user-in-net-44d18b8094dc?source=rss-63114b03eecf------2</link>
            <guid isPermaLink="false">https://medium.com/p/44d18b8094dc</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[feature-flags]]></category>
            <dc:creator><![CDATA[Vinicius Rossado]]></dc:creator>
            <pubDate>Wed, 12 Aug 2026 13:00:47 GMT</pubDate>
            <atom:updated>2026-08-12T13:00:47.313Z</atom:updated>
            <content:encoded><![CDATA[<p>You’re replacing a legacy payment engine. You can’t flip 100% of traffic to the new one on day one — you want 5%, then 20%, then 50%, watching error rates at every step. And there’s one hard requirement: the same user must always land on the same system. A user who sees the new checkout on Monday and the legacy one on Tuesday is a support ticket waiting to happen.</p><p>The obvious answers — cookies, sticky sessions, a routing table in Redis — all add state you have to store, replicate, and expire. There’s a simpler answer: math. Hash the user ID, take a number from 0 to 99, compare it to a threshold. No storage, no session affinity, and it works identically on every server in the fleet.</p><p>Here’s how the whole thing works in .NET, and the one mistake that will quietly break it in production.</p><h3>The flag decides, the proxy routes</h3><p>First, a separation of concerns worth being explicit about: the feature flag does not route traffic. It makes a decision — “this user goes to the new system” — and something else (a YARP proxy, a gateway middleware, an if in a controller) executes that decision.</p><p>Keeping those two responsibilities apart means you can reuse the same decision logic whether you’re routing whole requests at the edge or branching inside a single service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y543NjnT0SlYD3jJ6hwypA.png" /><figcaption>The whole decision is one hash: same GUID, same bucket, same system — on every server, with no stored state.</figcaption></figure><h3>From a GUID to a number between 0 and 99</h3><p>The core trick is three steps: hash the user ID, turn the first bytes of the hash into an integer, and take modulo 100.</p><pre>// Step by step<br>var userId = Guid.NewGuid();<br> <br>// 1. GUID -&gt; 16 bytes<br>var bytes = userId.ToByteArray();<br>// e.g. [0x55, 0x0e, 0x84, 0x00, ...]<br> <br>// 2. SHA256 -&gt; 32 bytes, deterministic on any machine<br>var hash = SHA256.HashData(bytes);<br>// e.g. [0x3A, 0xFF, 0xF9, 0x3A, 0xBB, ...]<br> <br>// 3. First 4 bytes -&gt; uint (unsigned: no negative values,<br>//    no Math.Abs(int.MinValue) overflow edge case)<br>var raw = BitConverter.ToUInt32(hash, 0);<br>// e.g. 989462330<br> <br>// 4. Modulo -&gt; 0..99<br>var hashValue = (int)(raw % 100);<br>// e.g. 30<br> <br>// 5. Decide<br>var thresholdPercent = 20;<br>bool goesToNew = hashValue &lt; thresholdPercent; // 30 &lt; 20 -&gt; Legacy</pre><p>Why does % 100 give you 0–99 here? Modulo returns the remainder of a division, and any <em>non-negative</em> integer divided by 100 has a remainder between 0 and 99. The word non-negative is doing real work: in C#, % on a negative int returns a negative remainder (-7 % 100 == -7), and BitConverter.ToInt32 goes negative about half the time. That&#39;s why the code reads the bytes as an unsigned uint — no negative values can exist, so no Math.Abs is needed (and the classic Math.Abs(BitConverter.ToInt32(...)) variant has a genuine one-in-four- billion bug: Math.Abs(int.MinValue) throws OverflowException). So every user maps to exactly one bucket:</p><ul><li><strong>7 % 100</strong>: 7 — Yes → New System</li><li><strong>150 % 100</strong>: 50 — No → Legacy</li><li><strong>989462330 % 100</strong>: 30 — No → Legacy</li><li><strong>1000 % 100</strong>: 0 — Yes → New System</li><li><strong>19 % 100</strong>: 19 — Yes → New System</li><li><strong>20 % 100</strong>: 20 — No → Legacy</li></ul><p>Because SHA256 output is uniformly distributed, roughly 20% of your users will land below 20. And because SHA256 is a pure function — same input, same output, every time — user A gets the same hashValue on every request, on every server, forever. That&#39;s sticky behavior without a cookie, a session, or a single row of state. It&#39;s determinism by construction.</p><p>One caveat: uniform distribution is a statistical property. With 5,000 users, a 20% threshold will give you very close to 20%. With 50 users, it might give you 12% or 28%. If your user base is small (say, under 500), use an explicit canary list instead of a percentage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dYK-pnJXxYftJA96yERnJg.png" /><figcaption>Every user is a brick; raising the threshold only flips new bricks — the ones already teal stay teal.</figcaption></figure><h3>Why SHA256 and not GetHashCode()?</h3><p>This is the mistake that breaks the whole scheme:</p><pre>// WRONG in any multi-server deployment<br>var value = Math.Abs(userId.GetHashCode()) % 100;</pre><p>GetHashCode() is only guaranteed to be stable <em>within a single process</em>. For strings, .NET Core randomizes the hash seed per process on purpose (as a HashDoS mitigation), and even where it doesn&#39;t, the algorithm can differ across runtimes and versions. Two servers behind your load balancer can compute different results for the same GUID — which means the same user bounces between Legacy and New System depending on which instance handles the request. Exactly the bug you built this to avoid, and it will pass every test on your single-process dev machine.</p><ul><li><strong>GetHashCode()</strong>: Per process — No — No</li><li><strong>SHA256.HashData()</strong>: Always — Yes — Yes</li><li><strong>LaunchDarkly / Azure AppConfig</strong>: Always — Yes — Recommended</li></ul><p>And no, you don’t need SHA256’s cryptographic strength here — you need its <em>stability</em> and uniform distribution. Any stable hash (xxHash, Murmur3) works too; SHA256 is just already in the BCL as a one-liner.</p><p>A related question that comes up: “does this work if my user ID is a GUID rather than an int?” Yes — the hash never needed a number. It operates on bytes. Guid.ToByteArray() gives you 16 bytes, SHA256 happily consumes any byte sequence, and the distribution is identical to hashing an int.</p><h3>The implementation in .NET</h3><p>The decision function is small enough to inline anywhere:</p><pre>using System.Security.Cryptography;<br> <br>public static class FeatureFlagRouter<br>{<br>    public static bool ShouldUseNewSystem(Guid userId, int threshold)<br>    {<br>        var bytes = userId.ToByteArray();     // 16 bytes<br>        var hash = SHA256.HashData(bytes);    // 32 bytes<br>        var value = (int)(BitConverter.ToUInt32(hash, 0) % 100);<br>        return value &lt; threshold;<br>    }<br>}</pre><p>Note that this is byte-for-byte the same formula as the step-by-step version above — that’s deliberate, and it matters more than it looks. ToUInt32 % 100 and Math.Abs(ToInt32) % 100 are <em>not</em> equivalent: they disagree on every hash whose sign bit is set, which is roughly half of all users. Switch formulas mid-rollout and you silently re-bucket half your user base — precisely the stickiness violation this whole design exists to prevent. Pick one formula before the first percentage ships, and treat it as frozen.</p><p>At the gateway, a middleware turns the decision into a routing hint that YARP (or whatever proxy you use) acts on:</p><pre>using System.Security.Claims;<br>using Microsoft.FeatureManagement;<br> <br>public class TrafficRoutingMiddleware(<br>    RequestDelegate next,<br>    IVariantFeatureManager features)<br>{<br>    public async Task InvokeAsync(HttpContext context)<br>    {<br>        var ct = context.RequestAborted;<br>        var phase = await features.GetVariantAsync(<br>            &quot;MigrationPhase&quot;, ct);<br> <br>        if (phase?.Configuration?.Value == &quot;legacy-off&quot; ||<br>            await features.IsEnabledAsync(&quot;NewPaymentEngine&quot;, ct))<br>        {<br>            context.Request.Headers[&quot;X-Route-To&quot;] = &quot;new&quot;;<br>        }<br>        else if (Guid.TryParse(<br>            context.User.FindFirst(&quot;sub&quot;)?.Value<br>                ?? context.User.FindFirst(<br>                    ClaimTypes.NameIdentifier)?.Value,<br>            out var userId))<br>        {<br>            // Percentage rollout by deterministic hash<br>            if (FeatureFlagRouter.ShouldUseNewSystem(userId, 20))<br>                context.Request.Headers[&quot;X-Route-To&quot;] = &quot;new&quot;;<br>        }<br> <br>        await next(context);<br>    }<br>}</pre><p>One trap hides in the claim lookup: the default JwtBearer handler <em>renames</em> inbound claims, so sub arrives as ClaimTypes.NameIdentifier unless you set options.MapInboundClaims = false. The fallback above handles both; without it, every authenticated user silently fails the parse and lands on the legacy side — a rollout stuck at 0% with no error in sight.</p><p>For branching <em>inside</em> a service, Microsoft.FeatureManagement gives you a clean boolean check backed by configuration:</p><pre>// Program.cs<br>builder.Services.AddFeatureManagement();<br> <br>// In a controller<br>[ApiController]<br>[Route(&quot;api/payments&quot;)]<br>public class PaymentController(<br>    IVariantFeatureManager features,<br>    INewPaymentService newService,<br>    ILegacyPaymentService legacyService) : ControllerBase<br>{<br>    [HttpPost]<br>    public async Task&lt;IActionResult&gt; Process(<br>        PaymentRequest req, CancellationToken ct)<br>    {<br>        if (await features.IsEnabledAsync(&quot;NewPaymentEngine&quot;, ct))<br>            return Ok(await newService.ProcessAsync(req, ct));<br> <br>        return Ok(await legacyService.ProcessAsync(req, ct));<br>    }<br>}</pre><p>And the flags themselves in appsettings.json:</p><pre>{<br>  &quot;FeatureManagement&quot;: {<br>    &quot;NewPaymentEngine&quot;:      true,<br>    &quot;NewInventoryCheck&quot;:     false,<br>    &quot;IdempotencyValidation&quot;: true,<br>    &quot;SagaOrchestrationMode&quot;: false<br>  },<br>  &quot;feature_management&quot;: {<br>    &quot;feature_flags&quot;: [<br>      {<br>        &quot;id&quot;: &quot;MigrationPhase&quot;,<br>        &quot;enabled&quot;: true,<br>        &quot;variants&quot;: [<br>          { &quot;name&quot;: &quot;dual-write&quot;,<br>            &quot;configuration_value&quot;: &quot;dual-write&quot; },<br>          { &quot;name&quot;: &quot;new-source-of-truth&quot;,<br>            &quot;configuration_value&quot;: &quot;new-source-of-truth&quot; },<br>          { &quot;name&quot;: &quot;legacy-off&quot;,<br>            &quot;configuration_value&quot;: &quot;legacy-off&quot; }<br>        ],<br>        &quot;allocation&quot;: {<br>          &quot;default_when_enabled&quot;: &quot;dual-write&quot;<br>        }<br>      }<br>    ]<br>  }<br>}</pre><p>Note that MigrationPhase isn&#39;t a boolean, and it can&#39;t be a plain string either — writing &quot;MigrationPhase&quot;: &quot;dual-write&quot; in the boolean schema fails bool.TryParse silently and the flag just reads as disabled, no error raised. A non-boolean flag is a <strong>variant flag</strong>: you declare the named variants explicitly and the allocation section picks one (default_when_enabled pins the current phase). Moving through the <a href="https://medium.com/@viniciusrossado/killing-a-legacy-system-without-a-big-bang-the-strangler-fig-pattern-in-net-eeef47e21814">strangler migration —</a> dual-write → new-source-of-truth → legacy-off — means changing default_when_enabled, not the flag&#39;s raw value.</p><h3>Where the flag value lives</h3><p>appsettings.json is fine to start, but every threshold change costs you a redeploy — painful when you want to go 5% → 20% → 50% over a week, or roll back to 0% at 2 a.m. The realistic options:</p><ul><li><strong>appsettings.json</strong>: No — Early on; redeploys are acceptable</li><li><strong>Azure App Configuration</strong>: Yes — Production; native % support, audit</li><li><strong>LaunchDarkly / Flagsmith</strong>: Yes — Scale; UI, one-click rollback, A/B</li><li><strong>Flags in your own DB</strong>: Yes — Full control, zero platform cost</li></ul><p>If you go the database route, don’t hit the database on every request. Cache the flags in memory and refresh them in the background. Here’s a refresher that follows the rules a BackgroundService should: a PeriodicTimer instead of a Task.Delay loop, a scoped DbContext resolved per tick via IServiceScopeFactory, and a try/catch around the body so one transient DB hiccup doesn&#39;t kill the loop — an unhandled exception in ExecuteAsync stops the refresher for good, and depending on host configuration can take the whole app with it.</p><p>Why the scope dance? A DbContext is registered as scoped by default, so injecting it straight into a singleton hosted service either throws &quot;Cannot consume scoped service from singleton&quot; at startup (when scope validation is on — the default in Development) or, worse, <em>silently resolves it from the root provider in Production</em>, pinning one context and its ever-growing change tracker to the lifetime of the process. Create a scope per tick — or inject an IDbContextFactory&lt;T&gt; (AddDbContextFactory) and create a fresh context each iteration; both are documented patterns.</p><pre>public sealed class FlagRefreshService : BackgroundService<br>{<br>    private readonly IServiceScopeFactory _scopeFactory;<br>    private readonly FlagCache _cache;<br>    private readonly ILogger&lt;FlagRefreshService&gt; _logger;<br> <br>    public FlagRefreshService(<br>        IServiceScopeFactory scopeFactory,<br>        FlagCache cache,<br>        ILogger&lt;FlagRefreshService&gt; logger)<br>    {<br>        _scopeFactory = scopeFactory;<br>        _cache = cache;<br>        _logger = logger;<br>    }<br> <br>    protected override async Task ExecuteAsync(<br>        CancellationToken stoppingToken)<br>    {<br>        using var timer =<br>            new PeriodicTimer(TimeSpan.FromSeconds(30));<br> <br>        while (await timer.WaitForNextTickAsync(stoppingToken))<br>        {<br>            try<br>            {<br>                await using var scope =<br>                    _scopeFactory.CreateAsyncScope();<br>                var db = scope.ServiceProvider<br>                    .GetRequiredService&lt;FlagDbContext&gt;();<br> <br>                var flags = await db.FeatureFlags<br>                    .AsNoTracking()<br>                    .ToListAsync(stoppingToken);<br> <br>                _cache.Replace(flags);<br>            }<br>            catch (OperationCanceledException)<br>                when (stoppingToken.IsCancellationRequested)<br>            {<br>                break; // clean shutdown<br>            }<br>            catch (Exception ex)<br>            {<br>                _logger.LogError(ex,<br>                    &quot;Flag refresh failed; keeping last snapshot&quot;);<br>            }<br>        }<br>    }<br>}</pre><p>On failure it logs the exception (as the exception parameter, not glued into the message) and keeps serving the last known snapshot — stale flags for 30 seconds beat a crashed rollout controller.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k5GAZohVd2e4dj_OMKXK4g.png" /><figcaption>The request path reads flags from memory; a background refresher keeps the cache warm and survives transient DB failures.</figcaption></figure><h3>Percentage isn’t the only strategy</h3><p>Hash-based percentage rollout is the workhorse, but it’s one of several strategies, each with a real trade-off:</p><ul><li><strong>% of users</strong>: Hash userId; below threshold → new — Gradual prod rollout — Sticky by math; users in the same account may split</li><li><strong>By environment</strong>: Different config per env: staging=new, prod=legacy — Validate in staging first — Zero complexity; no gradual rollout in prod</li><li><strong>Canary group</strong>: Explicit list of userIds (e.g. internal team) — Small base (&lt;500 users) — Total control; manual list doesn’t scale</li><li><strong>By tenant / region</strong>: Specific customers migrate first — B2B SaaS with customer agreement — Perfect isolation; runs two systems per tenant longer</li></ul><p>They compose well: start with a canary list of internal users, move to a hash-based percentage as confidence grows, and keep a tenant-level override for the customer who signed a contract saying nothing changes until Q3.</p><h3>Takeaway</h3><p>A deterministic hash gives you the property every gradual rollout needs — the same user always sees the same system — for free, with no stored state. The rules that make it work in production:</p><ul><li><strong>Decision and routing are separate.</strong> The flag decides; the proxy routes.</li><li><strong>Hash with </strong><strong>SHA256.HashData, never </strong><strong>GetHashCode().</strong> The latter is not stable across machines, and the failure mode is invisible until you have two servers.</li><li><strong>hash % 100 &lt; threshold</strong> turns any user ID — int or GUID — into a stable 0–99 bucket.</li><li><strong>Percentages need volume.</strong> Under ~500 users, use an explicit canary list.</li><li><strong>Make the threshold changeable at runtime</strong>, and if it lives in your own database, refresh it in a BackgroundService that survives transient failures.</li></ul><p>Start at 5%, watch your dashboards, and let the math handle the stickiness.</p><h3>The Legacy Modernization in .NET series</h3><p>This article is one brick in a series on modernizing legacy systems in .NET — 🟩 bricks are laid, ⬜ bricks are coming:</p><ul><li>🟩 <a href="https://medium.com/@viniciusrossado/killing-a-legacy-system-without-a-big-bang-the-strangler-fig-pattern-in-net-eeef47e21814">Killing a Legacy System Without a Big Bang: The Strangler Fig Pattern</a></li><li>🟩 <a href="https://medium.com/@viniciusrossado/the-anti-corruption-layer-protecting-your-new-domain-model-from-the-legacy-system-9f72c5423dea">The Anti-Corruption Layer</a></li><li>⬜ <strong>Feature Flags with Deterministic Hashing — you are here</strong></li><li>🟩 <a href="https://medium.com/@viniciusrossado/the-outbox-pattern-idempotent-consumers-events-that-never-get-lost-in-net-136d60457042">The Outbox Pattern + Idempotent Consumers</a></li><li>⬜ The Saga Pattern (coming soon)</li><li>⬜ Resilience: Retry, Jitter, Circuit Breaker (coming soon)</li><li>⬜ Change Data Capture with Debezium (coming soon)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44d18b8094dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Outbox Pattern + Idempotent Consumers: Events That Never Get Lost in .NET]]></title>
            <link>https://medium.com/@viniciusrossado/the-outbox-pattern-idempotent-consumers-events-that-never-get-lost-in-net-136d60457042?source=rss-63114b03eecf------2</link>
            <guid isPermaLink="false">https://medium.com/p/136d60457042</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[outbox-pattern]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Vinicius Rossado]]></dc:creator>
            <pubDate>Wed, 22 Jul 2026 05:58:27 GMT</pubDate>
            <atom:updated>2026-07-22T07:06:30.477Z</atom:updated>
            <content:encoded><![CDATA[<p>You save an order to the database. Then you publish an OrderCreated event to the broker. Two lines of code, and one of the most reliable ways to corrupt a distributed system.</p><p>Between those two lines lives a failure window that will eventually be hit in production: the broker is down, the pod gets killed, the network blips. When it happens, your services quietly disagree about what’s true — the order exists but inventory never heard about it, or the event went out for an order that was never committed.</p><p>The fix is a pair of patterns that work as a team: the <strong>Outbox pattern</strong> on the producer side, and an <strong>idempotent consumer</strong> on the other end. Neither is enough alone. Together they give you a guarantee that’s easy to state and hard to break: <em>events are never lost, and duplicates are never harmful</em>.</p><p>Let’s build both in .NET, with EF Core and a BackgroundService. (If you came here from <a href="https://medium.com/@viniciusrossado/killing-a-legacy-system-without-a-big-bang-the-strangler-fig-pattern-in-net-eeef47e21814">the Strangler Fig post</a> in this series — this is the machinery behind that LegacyMirrorRequested event I promised to unpack.)</p><h3>The dual-write problem</h3><p>The root issue is that a database and a message broker are two different systems. Short of a full distributed transaction (2PC/XA) — which most modern brokers like Kafka, RabbitMQ, and cloud queues don’t support, and which teams avoid anyway for its blocking and availability costs — you can’t commit to both atomically. With two separate writes, whichever order you pick there’s a crash point that leaves them inconsistent:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dl_-1uVFAKY70-5sAMyP0g.png" /><figcaption>Both failure lanes have a crash window; the outbox lane commits state and intent together — all or nothing.</figcaption></figure><ol><li><strong>Save to DB ✓ → 2. Publish ✗</strong>: Event lost forever. Inventory never decrements.</li></ol><ul><li><strong>1. Publish ✓ → 2. Save to DB ✗</strong>: Ghost event with no corresponding data.</li><li><strong>Outbox: both in one DB transaction</strong>: Atomic — all or nothing.</li></ul><p>Retries don’t save you here. If the process dies after the commit but before the publish, there’s nothing left to retry — the intent to publish died with the process. The intent has to be <em>persisted</em>, and it has to be persisted <strong>in the same transaction as the business change</strong>.</p><p>That’s the whole Outbox pattern in one sentence.</p><h3>Step 1: Write the event to an outbox table, not to the broker</h3><p>Instead of publishing directly, the handler writes the event as a row in an OutboxMessages table, using the same DbContext — and therefore the same transaction — as the order itself:</p><pre>public async Task CreateOrderAsync(<br>    CreateOrderCommand cmd, CancellationToken ct)<br>{<br>    var order = Order.Create(cmd);<br>    var evt = new OrderCreated(<br>        order.Id, order.CustomerId,<br>        order.ProductId, order.Quantity, order.Total);<br> <br>    // Same DbContext -&gt; same transaction -&gt; atomic commit<br>    _db.Orders.Add(order);<br>    _db.OutboxMessages.Add(new OutboxMessage<br>    {<br>        Id          = Guid.NewGuid(),<br>        EventType   = nameof(OrderCreated),<br>        Payload     = JsonSerializer.Serialize(evt),<br>        CreatedAt   = DateTimeOffset.UtcNow,<br>        PublishedAt = null // null = not published yet<br>    });<br> <br>    await _db.SaveChangesAsync(ct); // all or nothing<br>}</pre><p>The golden rule: <strong>the event and the business state commit in the same database transaction. Never publish to the broker before that commit.</strong></p><p>If SaveChangesAsync fails, neither the order nor the event exists. If it succeeds, both exist. There is no in-between state anymore — the failure window is gone. The broker hasn&#39;t seen anything yet, and that&#39;s fine: delivery is now someone else&#39;s job.</p><h3>Step 2: The relay worker</h3><p>That someone is a small background process that polls the outbox for unpublished rows, pushes them to the broker, and only marks them as published after the broker confirms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0vOwUdmdrjHbbYOl9Vah6g.png" /><figcaption>End to end: one transaction persists the intent, the relay retries until the broker confirms, and the consumer makes duplicates harmless.</figcaption></figure><p>A few .NET realities shape how this worker should be written. BackgroundService is a singleton, but DbContext is scoped — so the worker resolves a fresh scope per tick via IServiceScopeFactory. An unhandled exception escaping ExecuteAsync permanently ends that service&#39;s loop — the runtime never restarts it. Before .NET 6 this failure was silent (nothing logged, host kept running with a zombie worker); since .NET 6 the default is the opposite failure mode: the exception is logged and <strong>the entire host shuts down</strong> (BackgroundServiceExceptionBehavior.StopHost). Either way, one flaky broker call shouldn&#39;t kill your relay — so each tick is wrapped in a try/catch. And for the loop cadence, PeriodicTimer beats a Task.Delay loop: ticks fire on a fixed schedule, so the interval doesn&#39;t drift by however long your handler takes (overlapping ticks are coalesced instead of piling up), and shutdown is tidier — cancel the token and WaitForNextTickAsync throws, or just Dispose the timer and it returns false, exiting the loop with no exception at all.</p><pre>public sealed class OutboxRelayWorker(<br>    IServiceScopeFactory scopeFactory,<br>    ChannelWriter&lt;OutboxMessage&gt; writer,<br>    ILogger&lt;OutboxRelayWorker&gt; logger) : BackgroundService<br>{<br>    protected override async Task ExecuteAsync(CancellationToken ct)<br>    {<br>        using var timer = new PeriodicTimer(TimeSpan.FromSeconds(5));<br> <br>        while (await timer.WaitForNextTickAsync(ct))<br>        {<br>            try<br>            {<br>                await PublishPendingAsync(ct);<br>            }<br>            catch (OperationCanceledException)<br>                when (ct.IsCancellationRequested)<br>            {<br>                throw; // graceful shutdown, let the host observe it<br>            }<br>            catch (Exception ex)<br>            {<br>                // Transient failure must NOT kill the loop.<br>                logger.LogError(<br>                    ex, &quot;Outbox relay tick failed; retrying next tick&quot;);<br>            }<br>        }<br>    }<br> <br>    private async Task PublishPendingAsync(CancellationToken ct)<br>    {<br>        // Singleton worker + scoped DbContext = scope per tick.<br>        await using var scope = scopeFactory.CreateAsyncScope();<br>        var db = scope.ServiceProvider<br>            .GetRequiredService&lt;OrdersDbContext&gt;();<br> <br>        var pending = await db.OutboxMessages<br>            .Where(m =&gt; m.PublishedAt == null)<br>            .OrderBy(m =&gt; m.CreatedAt)<br>            .Take(20)<br>            .ToListAsync(ct);<br> <br>        foreach (var msg in pending)<br>        {<br>            // Publish: Channel, RabbitMQ, Azure Service Bus...<br>            await writer.WriteAsync(msg, ct);<br> <br>            // Mark AFTER the broker confirms — never before.<br>            msg.PublishedAt = DateTimeOffset.UtcNow;<br>            await db.SaveChangesAsync(ct);<br>        }<br>    }<br>}</pre><p>Here the “broker” is an in-process System.Threading.Channels channel to keep the example runnable, but the shape is identical for RabbitMQ or Service Bus: publish, await the confirmation, then flip PublishedAt.</p><p>### The question that reveals the whole design</p><p><em>What if the relay publishes the message but crashes before marking it as published?</em></p><p>Then PublishedAt is still null, and the next tick publishes the same message again. The consumer receives a duplicate.</p><p>That’s not a bug — it’s the deal you signed. This architecture gives you <strong>at-least-once delivery</strong>: the event will definitely arrive, but it may arrive more than once. Exactly-once <em>delivery</em> across a database and a broker isn’t realistically achievable; what you can build is exactly-once <em>processing</em>. Which is why the consumer side is not optional.</p><h3>Step 3: The idempotent consumer</h3><p>The consumer keeps its own ProcessedEvents table. Before doing any work, it checks whether this event ID has already been handled. And critically, it records &quot;I processed this&quot; <strong>in the same transaction as the business effect</strong> — otherwise you&#39;ve just recreated the dual-write problem one service downstream.</p><pre>public sealed class InventoryEventConsumer(<br>    IServiceScopeFactory scopeFactory,<br>    ChannelReader&lt;OutboxMessage&gt; reader,<br>    ILogger&lt;InventoryEventConsumer&gt; logger) : BackgroundService<br>{<br>    protected override async Task ExecuteAsync(CancellationToken ct)<br>    {<br>        await foreach (var msg in reader.ReadAllAsync(ct))<br>        {<br>            try<br>            {<br>                await ConsumeAsync(msg, ct);<br>            }<br>            catch (OperationCanceledException)<br>                when (ct.IsCancellationRequested)<br>            {<br>                throw;<br>            }<br>            catch (Exception ex)<br>            {<br>                // One poison message must not stop the consumer.<br>                logger.LogError(<br>                    ex, &quot;Failed to consume event {EventId}&quot;, msg.Id);<br>                // Retry / dead-letter policy goes here.<br>            }<br>        }<br>    }<br> <br>    private async Task ConsumeAsync(<br>        OutboxMessage msg, CancellationToken ct)<br>    {<br>        await using var scope = scopeFactory.CreateAsyncScope();<br>        var db = scope.ServiceProvider<br>            .GetRequiredService&lt;InventoryDbContext&gt;();<br> <br>        // Have we already handled this event?<br>        var duplicate = await db.ProcessedEvents<br>            .AnyAsync(e =&gt; e.EventId == msg.Id, ct);<br> <br>        if (duplicate)<br>        {<br>            logger.LogWarning(<br>                &quot;Duplicate event {EventId} - skipping&quot;, msg.Id);<br>            return; // idempotent: safe to ignore<br>        }<br> <br>        var evt = JsonSerializer<br>            .Deserialize&lt;OrderCreated&gt;(msg.Payload)!;<br> <br>        // Business effect — against the SAME DbContext,<br>        // so it commits with the ProcessedEvents row below.<br>        var stock = await db.Stock<br>            .SingleAsync(s =&gt; s.ProductId == evt.ProductId, ct);<br>        stock.Quantity -= evt.Quantity;<br> <br>        // Record it — SAME transaction as the business effect.<br>        db.ProcessedEvents.Add(new ProcessedEvent<br>        {<br>            EventId     = msg.Id,<br>            ProcessedAt = DateTimeOffset.UtcNow<br>        });<br> <br>        await db.SaveChangesAsync(ct);<br>    }<br>}</pre><p>One SaveChangesAsync commits both the stock decrement and the ProcessedEvents row atomically. If the consumer crashes mid-way, nothing was committed, the redelivered event finds no ProcessedEvents row, and processing happens cleanly on the retry. If it committed, the redelivery is detected and skipped. Either way: exactly-once <em>effect</em>.</p><p>One subtlety that silently breaks this guarantee: if you extract the stock update into an injected service, that service must share this same scoped DbContext and must <strong>not</strong> call SaveChangesAsync itself. Two saves = two transactions = a crash window between them, and you&#39;ve rebuilt the dual-write problem inside your own consumer. That&#39;s why the decrement is inlined against db here.</p><p>For belt-and-braces, put a <strong>unique index on </strong><strong>ProcessedEvents.EventId</strong>. Two consumer instances racing on the same duplicate will both pass the AnyAsync check, but only one commit will survive — the other fails on the constraint and can be safely treated as a duplicate.</p><h3>What the combination guarantees</h3><ul><li><strong>Event never lost</strong>: Outbox row commits with the business state, before any publish</li><li><strong>Delivery guaranteed</strong>: Relay retries until the broker confirms (at-least-once)</li><li><strong>Duplicates harmless</strong>: Consumer checks ProcessedEvents before acting</li><li><strong>No downstream inconsistency</strong>: ProcessedEvent + business effect commit in one transaction</li></ul><p>A few production notes worth knowing before you ship this:</p><ul><li><strong>Prune the outbox.</strong> Published rows accumulate fast. A cleanup job that deletes rows where PublishedAt is older than a few days keeps the polling query cheap.</li><li><strong>Index for the poll.</strong> A filtered index on PublishedAt IS NULL (or WHERE PublishedAt = NULL equivalent in your database) makes the relay query O(pending), not O(table).</li><li><strong>Ordering is per-poll, not global.</strong> OrderBy(CreatedAt) preserves rough ordering, but consumers should not depend on strict global order — design events to be commutative or version-checked where it matters.</li><li><strong>Polling vs. CDC.</strong> Polling every few seconds is simple and fine for most systems. If you need lower latency at high volume, log-tailing tools like Debezium read the outbox table from the database’s write-ahead log instead — same pattern, different transport.</li></ul><h3>Takeaway</h3><p>The Outbox pattern isn’t clever code — it’s an honest admission that, without distributed transactions nobody wants to run, you can’t commit atomically to two systems. So you stop trying. Commit once, to your own database, and let a retrying relay handle delivery. Then accept the consequence of retries — duplicates — and neutralize them with an idempotency check that commits alongside the business effect.</p><p>At-least-once delivery plus idempotent consumption equals exactly-once processing. That’s the entire trick, and it’s two tables and two background services away from any .NET codebase you own.he Outbox Pattern + Idempotent Consumers: Events That Never Get Lost in .NET</p><p>You save an order to the database. Then you publish an OrderCreated event to the broker. Two lines of code, and one of the most reliable ways to corrupt a distributed system.</p><p>Between those two lines lives a failure window that will eventually be hit in production: the broker is down, the pod gets killed, the network blips. When it happens, your services quietly disagree about what’s true — the order exists but inventory never heard about it, or the event went out for an order that was never committed.</p><p>The fix is a pair of patterns that work as a team: the <strong>Outbox pattern</strong> on the producer side, and an <strong>idempotent consumer</strong> on the other end. Neither is enough alone. Together they give you a guarantee that’s easy to state and hard to break: <em>events are never lost, and duplicates are never harmful</em>.</p><p>Let’s build both in .NET, with EF Core and a BackgroundService. (If you came here from <a href="https://medium.com/@viniciusrossado/killing-a-legacy-system-without-a-big-bang-the-strangler-fig-pattern-in-net-eeef47e21814">the Strangler Fig post</a> in this series — this is the machinery behind that LegacyMirrorRequested event I promised to unpack.)</p><h3>The dual-write problem</h3><p>The root issue is that a database and a message broker are two different systems. Short of a full distributed transaction (2PC/XA) — which most modern brokers like Kafka, RabbitMQ, and cloud queues don’t support, and which teams avoid anyway for its blocking and availability costs — you can’t commit to both atomically. With two separate writes, whichever order you pick there’s a crash point that leaves them inconsistent:</p><p><strong>[IMAGE HERE]</strong> Two-lane failure diagram. Lane 1: “DB write ✓ → broker publish ✗” with the event falling into a gap (lost forever). Lane 2: “broker publish ✓ → DB write ✗” with an orphaned event and no matching row. A third lane shows the Outbox: order row + outbox row committed inside one transaction boundary box, labeled “atomic — all or nothing”. Use the generic building-blocks style: teal blocks = committed state, gray blocks = missing/pending. No brand trade dress.</p><ul><li><strong>1. Save to DB ✓ → 2. Publish ✗</strong>: Event lost forever. Inventory never decrements.</li><li><strong>1. Publish ✓ → 2. Save to DB ✗</strong>: Ghost event with no corresponding data.</li><li><strong>Outbox: both in one DB transaction</strong>: Atomic — all or nothing.</li></ul><p>Retries don’t save you here. If the process dies after the commit but before the publish, there’s nothing left to retry — the intent to publish died with the process. The intent has to be <em>persisted</em>, and it has to be persisted <strong>in the same transaction as the business change</strong>.</p><p>That’s the whole Outbox pattern in one sentence.</p><h3>Step 1: Write the event to an outbox table, not to the broker</h3><p>Instead of publishing directly, the handler writes the event as a row in an OutboxMessages table, using the same DbContext — and therefore the same transaction — as the order itself:</p><pre>public async Task CreateOrderAsync(<br>    CreateOrderCommand cmd, CancellationToken ct)<br>{<br>    var order = Order.Create(cmd);<br>    var evt = new OrderCreated(<br>        order.Id, order.CustomerId,<br>        order.ProductId, order.Quantity, order.Total);<br> <br>    // Same DbContext -&gt; same transaction -&gt; atomic commit<br>    _db.Orders.Add(order);<br>    _db.OutboxMessages.Add(new OutboxMessage<br>    {<br>        Id          = Guid.NewGuid(),<br>        EventType   = nameof(OrderCreated),<br>        Payload     = JsonSerializer.Serialize(evt),<br>        CreatedAt   = DateTimeOffset.UtcNow,<br>        PublishedAt = null // null = not published yet<br>    });<br> <br>    await _db.SaveChangesAsync(ct); // all or nothing<br>}</pre><p>The golden rule: <strong>the event and the business state commit in the same database transaction. Never publish to the broker before that commit.</strong></p><p>If SaveChangesAsync fails, neither the order nor the event exists. If it succeeds, both exist. There is no in-between state anymore — the failure window is gone. The broker hasn&#39;t seen anything yet, and that&#39;s fine: delivery is now someone else&#39;s job.</p><h3>Step 2: The relay worker</h3><p>That someone is a small background process that polls the outbox for unpublished rows, pushes them to the broker, and only marks them as published after the broker confirms.</p><p><strong>[IMAGE HERE]</strong> Flow diagram — API handler writes [Order row][Outbox row] into the database inside one transaction box; a “Relay worker” loop pulls pending outbox rows (gray blocks) and moves them through a broker/ channel into the consumer, turning them teal once PublishedAt is set. Show the tick cycle (PeriodicTimer, 5s) as a circular arrow on the relay. Generic building-blocks style, teal = published, gray = pending.</p><p>A few .NET realities shape how this worker should be written. BackgroundService is a singleton, but DbContext is scoped — so the worker resolves a fresh scope per tick via IServiceScopeFactory. An unhandled exception escaping ExecuteAsync permanently ends that service&#39;s loop — the runtime never restarts it. Before .NET 6 this failure was silent (nothing logged, host kept running with a zombie worker); since .NET 6 the default is the opposite failure mode: the exception is logged and <strong>the entire host shuts down</strong> (BackgroundServiceExceptionBehavior.StopHost). Either way, one flaky broker call shouldn&#39;t kill your relay — so each tick is wrapped in a try/catch. And for the loop cadence, PeriodicTimer beats a Task.Delay loop: ticks fire on a fixed schedule, so the interval doesn&#39;t drift by however long your handler takes (overlapping ticks are coalesced instead of piling up), and shutdown is tidier — cancel the token and WaitForNextTickAsync throws, or just Dispose the timer and it returns false, exiting the loop with no exception at all.</p><pre>public sealed class OutboxRelayWorker(<br>    IServiceScopeFactory scopeFactory,<br>    ChannelWriter&lt;OutboxMessage&gt; writer,<br>    ILogger&lt;OutboxRelayWorker&gt; logger) : BackgroundService<br>{<br>    protected override async Task ExecuteAsync(CancellationToken ct)<br>    {<br>        using var timer = new PeriodicTimer(TimeSpan.FromSeconds(5));<br> <br>        while (await timer.WaitForNextTickAsync(ct))<br>        {<br>            try<br>            {<br>                await PublishPendingAsync(ct);<br>            }<br>            catch (OperationCanceledException)<br>                when (ct.IsCancellationRequested)<br>            {<br>                throw; // graceful shutdown, let the host observe it<br>            }<br>            catch (Exception ex)<br>            {<br>                // Transient failure must NOT kill the loop.<br>                logger.LogError(<br>                    ex, &quot;Outbox relay tick failed; retrying next tick&quot;);<br>            }<br>        }<br>    }<br> <br>    private async Task PublishPendingAsync(CancellationToken ct)<br>    {<br>        // Singleton worker + scoped DbContext = scope per tick.<br>        await using var scope = scopeFactory.CreateAsyncScope();<br>        var db = scope.ServiceProvider<br>            .GetRequiredService&lt;OrdersDbContext&gt;();<br> <br>        var pending = await db.OutboxMessages<br>            .Where(m =&gt; m.PublishedAt == null)<br>            .OrderBy(m =&gt; m.CreatedAt)<br>            .Take(20)<br>            .ToListAsync(ct);<br> <br>        foreach (var msg in pending)<br>        {<br>            // Publish: Channel, RabbitMQ, Azure Service Bus...<br>            await writer.WriteAsync(msg, ct);<br> <br>            // Mark AFTER the broker confirms — never before.<br>            msg.PublishedAt = DateTimeOffset.UtcNow;<br>            await db.SaveChangesAsync(ct);<br>        }<br>    }<br>}</pre><p>Here the “broker” is an in-process System.Threading.Channels channel to keep the example runnable, but the shape is identical for RabbitMQ or Service Bus: publish, await the confirmation, then flip PublishedAt.</p><p>### The question that reveals the whole design</p><p><em>What if the relay publishes the message but crashes before marking it as published?</em></p><p>Then PublishedAt is still null, and the next tick publishes the same message again. The consumer receives a duplicate.</p><p>That’s not a bug — it’s the deal you signed. This architecture gives you <strong>at-least-once delivery</strong>: the event will definitely arrive, but it may arrive more than once. Exactly-once <em>delivery</em> across a database and a broker isn’t realistically achievable; what you can build is exactly-once <em>processing</em>. Which is why the consumer side is not optional.</p><h3>Step 3: The idempotent consumer</h3><p>The consumer keeps its own ProcessedEvents table. Before doing any work, it checks whether this event ID has already been handled. And critically, it records &quot;I processed this&quot; <strong>in the same transaction as the business effect</strong> — otherwise you&#39;ve just recreated the dual-write problem one service downstream.</p><pre>public sealed class InventoryEventConsumer(<br>    IServiceScopeFactory scopeFactory,<br>    ChannelReader&lt;OutboxMessage&gt; reader,<br>    ILogger&lt;InventoryEventConsumer&gt; logger) : BackgroundService<br>{<br>    protected override async Task ExecuteAsync(CancellationToken ct)<br>    {<br>        await foreach (var msg in reader.ReadAllAsync(ct))<br>        {<br>            try<br>            {<br>                await ConsumeAsync(msg, ct);<br>            }<br>            catch (OperationCanceledException)<br>                when (ct.IsCancellationRequested)<br>            {<br>                throw;<br>            }<br>            catch (Exception ex)<br>            {<br>                // One poison message must not stop the consumer.<br>                logger.LogError(<br>                    ex, &quot;Failed to consume event {EventId}&quot;, msg.Id);<br>                // Retry / dead-letter policy goes here.<br>            }<br>        }<br>    }<br> <br>    private async Task ConsumeAsync(<br>        OutboxMessage msg, CancellationToken ct)<br>    {<br>        await using var scope = scopeFactory.CreateAsyncScope();<br>        var db = scope.ServiceProvider<br>            .GetRequiredService&lt;InventoryDbContext&gt;();<br> <br>        // Have we already handled this event?<br>        var duplicate = await db.ProcessedEvents<br>            .AnyAsync(e =&gt; e.EventId == msg.Id, ct);<br> <br>        if (duplicate)<br>        {<br>            logger.LogWarning(<br>                &quot;Duplicate event {EventId} - skipping&quot;, msg.Id);<br>            return; // idempotent: safe to ignore<br>        }<br> <br>        var evt = JsonSerializer<br>            .Deserialize&lt;OrderCreated&gt;(msg.Payload)!;<br> <br>        // Business effect — against the SAME DbContext,<br>        // so it commits with the ProcessedEvents row below.<br>        var stock = await db.Stock<br>            .SingleAsync(s =&gt; s.ProductId == evt.ProductId, ct);<br>        stock.Quantity -= evt.Quantity;<br> <br>        // Record it — SAME transaction as the business effect.<br>        db.ProcessedEvents.Add(new ProcessedEvent<br>        {<br>            EventId     = msg.Id,<br>            ProcessedAt = DateTimeOffset.UtcNow<br>        });<br> <br>        await db.SaveChangesAsync(ct);<br>    }<br>}</pre><p>One SaveChangesAsync commits both the stock decrement and the ProcessedEvents row atomically. If the consumer crashes mid-way, nothing was committed, the redelivered event finds no ProcessedEvents row, and processing happens cleanly on the retry. If it committed, the redelivery is detected and skipped. Either way: exactly-once <em>effect</em>.</p><p>One subtlety that silently breaks this guarantee: if you extract the stock update into an injected service, that service must share this same scoped DbContext and must <strong>not</strong> call SaveChangesAsync itself. Two saves = two transactions = a crash window between them, and you&#39;ve rebuilt the dual-write problem inside your own consumer. That&#39;s why the decrement is inlined against db here.</p><p>For belt-and-braces, put a <strong>unique index on </strong><strong>ProcessedEvents.EventId</strong>. Two consumer instances racing on the same duplicate will both pass the AnyAsync check, but only one commit will survive — the other fails on the constraint and can be safely treated as a duplicate.</p><h3>What the combination guarantees</h3><ul><li><strong>Event never lost</strong>: Outbox row commits with the business state, before any publish</li><li><strong>Delivery guaranteed</strong>: Relay retries until the broker confirms (at-least-once)</li><li><strong>Duplicates harmless</strong>: Consumer checks ProcessedEvents before acting</li><li><strong>No downstream inconsistency</strong>: ProcessedEvent + business effect commit in one transaction</li></ul><p>A few production notes worth knowing before you ship this:</p><ul><li><strong>Prune the outbox.</strong> Published rows accumulate fast. A cleanup job that deletes rows where PublishedAt is older than a few days keeps the polling query cheap.</li><li><strong>Index for the poll.</strong> A filtered index on PublishedAt IS NULL (or WHERE PublishedAt = NULL equivalent in your database) makes the relay query O(pending), not O(table).</li><li><strong>Ordering is per-poll, not global.</strong> OrderBy(CreatedAt) preserves rough ordering, but consumers should not depend on strict global order — design events to be commutative or version-checked where it matters.</li><li><strong>Polling vs. CDC.</strong> Polling every few seconds is simple and fine for most systems. If you need lower latency at high volume, log-tailing tools like Debezium read the outbox table from the database’s write-ahead log instead — same pattern, different transport.</li></ul><h3>Takeaway</h3><p>The Outbox pattern isn’t clever code — it’s an honest admission that, without distributed transactions nobody wants to run, you can’t commit atomically to two systems. So you stop trying. Commit once, to your own database, and let a retrying relay handle delivery. Then accept the consequence of retries — duplicates — and neutralize them with an idempotency check that commits alongside the business effect.</p><p>At-least-once delivery plus idempotent consumption equals exactly-once processing. That’s the entire trick, and it’s two tables and two background services away from any .NET codebase you own.</p><h3>The Legacy Modernization in .NET series</h3><p>This article is one brick in a series on modernizing legacy systems in .NET — 🟩 bricks are laid, ⬜ bricks are coming:</p><ul><li>🟩 <a href="https://medium.com/@viniciusrossado/killing-a-legacy-system-without-a-big-bang-the-strangler-fig-pattern-in-net-eeef47e21814">Killing a Legacy System Without a Big Bang: The Strangler Fig Pattern</a></li><li>🟩 <a href="https://medium.com/@viniciusrossado/the-anti-corruption-layer-protecting-your-new-domain-model-from-the-legacy-system-9f72c5423dea">The Anti-Corruption Layer</a></li><li>⬜ Feature Flags with Deterministic Hashing (coming soon)</li><li>🟩 <strong>The Outbox Pattern + Idempotent Consumers — you are here</strong></li><li>⬜ The Saga Pattern (coming soon)</li><li>⬜ Resilience: Retry, Jitter, Circuit Breaker (coming soon)</li><li>⬜ Change Data Capture with Debezium (coming soon)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=136d60457042" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Anti-Corruption Layer: Protecting Your New Domain Model From the Legacy System]]></title>
            <link>https://medium.com/@viniciusrossado/the-anti-corruption-layer-protecting-your-new-domain-model-from-the-legacy-system-9f72c5423dea?source=rss-63114b03eecf------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f72c5423dea</guid>
            <category><![CDATA[legacy-systems]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <dc:creator><![CDATA[Vinicius Rossado]]></dc:creator>
            <pubDate>Tue, 21 Jul 2026 19:28:53 GMT</pubDate>
            <atom:updated>2026-07-22T07:06:11.078Z</atom:updated>
            <content:encoded><![CDATA[<p>You finally got the green light to build the new system. Clean domain model, value objects, proper enums, the works. Then you open the legacy database and there it is: TBL_ORDR, with a CUST_CD column and a STAT_CD that holds &quot;O&quot;, &quot;C&quot;, or &quot;X&quot; — and nobody remembers who decided that.</p><p>Here’s the trap: the moment your new domain code references TBL_ORDR directly, the legacy system has won. Its naming, its stringly-typed statuses, its quirks — they all leak into the code you were supposed to keep clean. Any schema change on the old side now breaks the new side.</p><p>The Anti-Corruption Layer (ACL) is the pattern that stops this. It’s not glamorous, but during a migration it’s the single thing standing between your new domain model and slow contamination.</p><h3>The problem without an ACL</h3><p>Without an ACL, your shiny new OrderService has to know that orders live in TBL_ORDR, that customers are identified by CUST_CD, and that &quot;X&quot; means cancelled. That knowledge spreads. Six months in, half your &quot;new&quot; codebase is fluent in legacy column names, and you&#39;ve built a second legacy system with better formatting.</p><p>The failure mode is subtle because each individual shortcut looks harmless. “It’s just one query.” “It’s just one status mapping.” The ACL exists to give that knowledge exactly one place to live — and to keep that place out of your domain.</p><h3>What the ACL actually is</h3><p>An ACL is a translation boundary. On one side: the legacy model, ugly and untouchable. On the other: your domain model, clean and unaware the legacy system exists. The ACL sits in the middle and translates in both directions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p51uVCEkOlE6oJn04lNo3Q.png" /><figcaption>The ACL translates in both directions: legacy rows become value objects on the way in, and the clean model becomes legacy columns on the way out.</figcaption></figure><p>Two directions matter:</p><ul><li><strong>Inbound (Legacy → Domain).</strong> Runs when you read legacy data. Translates TBL_ORDR with its cryptic columns into an Order built from value objects.</li><li><strong>Outbound (Domain → Legacy).</strong> Runs when the new system still has to write back to the old one — typically during a dual-write phase or via a background sync job. Translates a clean Order back into the ugly TBL_ORDR shape.</li></ul><p>The placement rule is non-negotiable: <strong>the ACL lives in the Infrastructure layer.</strong> The Domain layer defines an interface (say, IOrderRepository). Infrastructure implements it with the translation inside. Domain never imports anything from the legacy world — not a type, not a column name, not a status code.</p><h3>Inbound: Legacy → Domain</h3><p>The inbound translator is where legacy knowledge gets quarantined. It knows the column names, it knows the status codes, and it fails loudly when it meets something it doesn’t recognize:</p><pre>// Legacy model (ugly table, never touch it)<br>public class TBL_ORDR<br>{<br>    public int      ORDR_ID  { get; set; }<br>    public string   CUST_CD  { get; set; } = &quot;&quot;;<br>    public decimal  TOT_AMT  { get; set; }<br>    public string   STAT_CD  { get; set; } = &quot;&quot;; // O / C / X<br>    public DateTime CREAT_DT { get; set; }<br>}<br> <br>// ACL Inbound — Infrastructure layer<br>public sealed class LegacyInboundAcl<br>{<br>    public Order Translate(TBL_ORDR raw) =&gt; new Order(<br>        Id:         OrderId.From(raw.ORDR_ID),<br>        CustomerId: CustomerId.From(raw.CUST_CD),<br>        Total:      Money.InEuros(raw.TOT_AMT),<br>        Status: raw.STAT_CD switch<br>        {<br>            &quot;O&quot; =&gt; OrderStatus.Open,<br>            &quot;C&quot; =&gt; OrderStatus.Closed,<br>            &quot;X&quot; =&gt; OrderStatus.Cancelled,<br>            _   =&gt; throw new UnknownLegacyStatusException(raw.STAT_CD)<br>        },<br>        CreatedAt: new DateTimeOffset(raw.CREAT_DT, TimeSpan.Zero)<br>    );<br>}</pre><p>Two details worth calling out:</p><p><strong>The </strong><strong>switch throws on unknown values.</strong> This is deliberate. If the legacy system starts producing a STAT_CD of &quot;P&quot; tomorrow, you want an exception at the boundary, not a silently mis-mapped order deep inside your domain logic. Corrupt data should die at the door.</p><p><strong>The output is all value objects.</strong> OrderId.From(...), Money.InEuros(...) — the translation isn&#39;t just renaming fields, it&#39;s upgrading raw primitives into types that enforce your domain&#39;s invariants.</p><p>The repository that uses it implements the Domain-owned interface, so callers never see any of this:</p><pre>public sealed class LegacyOrderRepository : IOrderRepository<br>{<br>    private readonly LegacyDbContext _db;<br>    private readonly LegacyInboundAcl _inbound;<br> <br>    public LegacyOrderRepository(<br>        LegacyDbContext db, LegacyInboundAcl inbound)<br>    {<br>        _db = db;<br>        _inbound = inbound;<br>    }<br> <br>    public async Task&lt;Order?&gt; GetAsync(<br>        OrderId id, CancellationToken cancellationToken = default)<br>    {<br>        var raw = await _db.TBL_ORDR<br>            .AsNoTracking()<br>            .FirstOrDefaultAsync(<br>                o =&gt; o.ORDR_ID == id.Value, cancellationToken);<br> <br>        return raw is null ? null : _inbound.Translate(raw);<br>    }<br>}</pre><h3>Outbound: Domain → Legacy</h3><p>During a migration you rarely get to cut over in one move. Reports, integrations, and that one Excel export the finance team loves still read from the legacy database. So for a while, the new system has to keep the old tables up to date — either by dual-writing on every change or by mirroring in a background sync job.</p><p>That write path needs the same translation, in reverse:</p><pre>// ACL Outbound — Infrastructure layer<br>public sealed class LegacyOutboundAcl<br>{<br>    private readonly LegacyDbContext _legacyDb;<br> <br>    public LegacyOutboundAcl(LegacyDbContext legacyDb)<br>        =&gt; _legacyDb = legacyDb;<br> <br>    public TBL_ORDR Translate(Order order) =&gt; new TBL_ORDR<br>    {<br>        ORDR_ID  = order.Id.Value,<br>        CUST_CD  = order.CustomerId.Value,<br>        TOT_AMT  = order.Total.Amount,<br>        CREAT_DT = order.CreatedAt.UtcDateTime,<br>        STAT_CD  = order.Status switch<br>        {<br>            OrderStatus.Open      =&gt; &quot;O&quot;,<br>            OrderStatus.Closed    =&gt; &quot;C&quot;,<br>            OrderStatus.Cancelled =&gt; &quot;X&quot;,<br>            _ =&gt; throw new UnmappableDomainStatusException(<br>                     order.Status)<br>        }<br>    };<br> <br>    public async Task MirrorAsync(<br>        Order order, CancellationToken cancellationToken)<br>    {<br>        var legacy = Translate(order);<br> <br>        var exists = await _legacyDb.TBL_ORDR<br>            .AsNoTracking()<br>            .AnyAsync(o =&gt; o.ORDR_ID == legacy.ORDR_ID,<br>                cancellationToken);<br> <br>        if (exists)<br>            _legacyDb.TBL_ORDR.Update(legacy);<br>        else<br>            _legacyDb.TBL_ORDR.Add(legacy);<br> <br>        await _legacyDb.SaveChangesAsync(cancellationToken);<br>        _legacyDb.ChangeTracker.Clear(); // safe re-mirror in same scope<br>    }<br>}</pre><p>Two traps hide in that write path. First, EF Core’s Update <strong>never inserts</strong> — on a detached entity with a set key it just marks the row Modified, so mirroring an order that doesn&#39;t exist in the legacy table yet throws DbUpdateConcurrencyException (&quot;expected to affect 1 row(s), but actually affected 0&quot;). During a dual-write phase new orders are exactly the common case, hence the explicit existence check. Second, the timestamp: CreatedAt.UtcDateTime, not .DateTime — the inbound ACL reads CREAT_DT as UTC, and .DateTime would hand back offset-local time, silently corrupting every round-trip for non-UTC offsets.</p><p>Again the mapping throws when it can’t translate. If your domain grows a new OrderStatus that the legacy schema has no code for, that&#39;s a migration decision a human needs to make — not something a mapper should paper over with a default value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jlbyL5MJqhYtjwRrhWGwDw.png" /><figcaption>During dual write and sync, the outbound ACL keeps the legacy database fresh — reports and integrations never notice the migration.</figcaption></figure><p>In production, MirrorAsync usually ends up driven by a background sync job. I won&#39;t repeat the hosting recipe here — <a href="https://medium.com/@viniciusrossado/killing-a-legacy-system-without-a-big-bang-the-strangler-fig-pattern-in-net-eeef47e21814">the previous post in this series </a>(on the Strangler Fig pattern) covers the full BackgroundService setup: a DI scope per tick, PeriodicTimer, and the try/catch that keeps one transient legacy-DB failure from stopping the whole host. The short version: treat the sync path as production code, because it is.</p><h3>Where each piece lives</h3><p>The whole pattern collapses if the layering isn’t enforced. Here’s the layout in a Clean Architecture solution:</p><pre>/PayCore<br>  /PayCore.Domain<br>    Order.cs              &lt;- record, value objects<br>    OrderStatus.cs        &lt;- clean enum<br>    IOrderRepository.cs   &lt;- interface, no mention of legacy<br> <br>  /PayCore.Application<br>    CreateOrderCommand.cs<br>    OrderService.cs       &lt;- uses IOrderRepository, impl-agnostic<br> <br>  /PayCore.Infrastructure<br>    /Acl<br>      LegacyInboundAcl.cs   &lt;- all legacy knowledge lives here<br>      LegacyOutboundAcl.cs<br>    /Repositories<br>      LegacyOrderRepository.cs  &lt;- IOrderRepository via the ACL</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GPvO8QsnL2rmF4YuIRsmCQ.png" /><figcaption>Only Infrastructure knows the legacy system exists. Domain defines the interface, Application consumes it, and the translation stays quarantined.</figcaption></figure><p><strong>Domain</strong>: Order, OrderId, Money, OrderStatus, IOrderRepository — Never</p><ul><li><strong>Application</strong>: CreateOrderCommand, OrderService — Never</li><li><strong>Infrastructure</strong>: LegacyInboundAcl, LegacyOutboundAcl, LegacyOrderRepository — Only here</li></ul><p>This layout is also your answer to the interview classic “where exactly does the ACL live?”: Infrastructure. Domain defines the interface, Application consumes it, Infrastructure implements it with the translation inside. When the legacy schema changes — and it will — you touch Infrastructure and nothing else.</p><h3>Takeaway</h3><p>An ACL isn’t extra ceremony; it’s a containment strategy. The legacy model is going to influence something — the only question is whether that influence is confined to two small translator classes or smeared across your entire new codebase.</p><p>Three rules to hold the line:</p><ol><li><strong>Legacy types never cross into Domain or Application.</strong> If a class outside Infrastructure mentions TBL_ORDR, the layer has failed.</li><li><strong>Translate in both directions, and throw on the unknown.</strong> Unknown legacy status codes and unmappable domain values are boundary errors, not things to guess about.</li><li><strong>Know your write-path traps.</strong> EF Core’s Update never inserts — dual-writing new orders needs an explicit upsert — and timestamps must round-trip through the same clock (UtcDateTime, not .DateTime).</li></ol><p>Do that, and when the legacy system finally gets switched off, you delete one Infrastructure folder — and the rest of your codebase never even notices it was there.</p><h3>The Legacy Modernization in .NET series</h3><p>This article is one brick in a series on modernizing legacy systems in .NET — 🟩 bricks are laid, ⬜ bricks are coming:</p><ul><li>🟩 <a href="https://medium.com/@viniciusrossado/killing-a-legacy-system-without-a-big-bang-the-strangler-fig-pattern-in-net-eeef47e21814">Killing a Legacy System Without a Big Bang: The Strangler Fig Pattern</a></li><li>🟩 <strong>The Anti-Corruption Layer — you are here</strong></li><li>⬜ Feature Flags with Deterministic Hashing (coming soon)</li><li>🟩 <a href="https://medium.com/@viniciusrossado/the-outbox-pattern-idempotent-consumers-events-that-never-get-lost-in-net-136d60457042">The Outbox Pattern + Idempotent Consumers</a></li><li>⬜ The Saga Pattern (coming soon)</li><li>⬜ Resilience: Retry, Jitter, Circuit Breaker (coming soon)</li><li>⬜ Change Data Capture with Debezium (coming soon)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f72c5423dea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Killing a Legacy System Without a Big Bang: The Strangler Fig Pattern in .NET]]></title>
            <link>https://medium.com/@viniciusrossado/killing-a-legacy-system-without-a-big-bang-the-strangler-fig-pattern-in-net-eeef47e21814?source=rss-63114b03eecf------2</link>
            <guid isPermaLink="false">https://medium.com/p/eeef47e21814</guid>
            <category><![CDATA[strangler-fig-pattern]]></category>
            <category><![CDATA[acl]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[migration]]></category>
            <category><![CDATA[legacy-modernization]]></category>
            <dc:creator><![CDATA[Vinicius Rossado]]></dc:creator>
            <pubDate>Thu, 16 Jul 2026 14:17:18 GMT</pubDate>
            <atom:updated>2026-09-05T08:31:46.830Z</atom:updated>
            <content:encoded><![CDATA[<p>You have a legacy system that everyone is afraid to touch. The schema has columns like TBL_ORDR.TOT_AMT, half the business logic lives in stored procedures, and the last person who understood it left two years ago. The obvious temptation is to rewrite the whole thing and switch over on some glorious weekend.</p><p>Don’t. The industry has largely turned against the big bang rewrite — Joel Spolsky famously called the full rewrite “the single worst strategic mistake a software company can make” — and the failure mode is brutal: you deliver zero value until go-live, and when go-live goes wrong, there is no rollback, because the old system has already drifted out of sync with reality.</p><p>The Strangler Fig pattern is the alternative. Named after the fig tree that grows around a host tree until the host dies, it replaces the legacy system piece by piece while everything stays in production. This post walks through a concrete migration I’ve modeled for .NET services — three phases, plus the backfill that makes them possible — with real code for each step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9AHKsdFSP-putDq7XbzssA.png" /><figcaption>How production traffic shifts across the migration — the legacy system is strangled gradually, never in one jump.</figcaption></figure><h3>Why not just rewrite it?</h3><p>Three properties make the strangler approach win over a rewrite:</p><ul><li><strong>Risk is low and distributed.</strong> Every step is small, shippable, and reversible. A rewrite concentrates all its risk into one cutover day.</li><li><strong>Value lands from day one.</strong> The first migrated endpoint is serving production traffic in week one, not in month eighteen.</li><li><strong>Rollback is always available.</strong> At any phase you can route traffic back to the legacy system with a config change.</li></ul><p>The whole migration is driven by one feature flag — migration-phase — that moves through three values: dual-write, new-source-of-truth, and legacy-off. But before the flag can flip for the first time, there&#39;s a bootstrap step that most write-ups skip.</p><h3>Phase 0 — Backfill</h3><p>Before you can dual-write, the new database has to already agree with the legacy one about everything that existed before you started. Phase 1 doesn’t create parity — it preserves it. So the first real step is a one-time backfill, and it should run through the <strong>inbound Anti-Corruption Layer</strong>: the same translator that upgrades ugly legacy rows into clean domain objects for live traffic is the one that migrates the history. If the translation is wrong, you want to find out now, on a snapshot, not later in production.</p><p>Run the backfill against a snapshot first. Then run it again in catch-up mode against the changes that happened since — the write-ahead log or a CDC feed — until the delta shrinks to seconds. During all of this the legacy system is still the source of truth; the new database is just chasing it. The moment the delta is negligible, flip the flag to dual-write.</p><p>Any drift that remains is what the sync validator (below) is for on day one — its first job isn’t checking Phase 1 writes, it’s confirming the backfill converged.</p><h3>Phase 1 — Dual write</h3><p>In phase 1, the new system becomes authoritative for writes, but the legacy database keeps receiving a mirrored copy of everything. The mirror goes through an <strong>outbound Anti-Corruption Layer (ACL)</strong> that translates your clean domain model back into the legacy schema’s ugly columns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Oz1WYw3mn8FKQ6YEb6KMw.png" /><figcaption>Phase 1: one atomic commit writes the order and queues the mirror; a worker replays it into the legacy DB through the outbound ACL.</figcaption></figure><p>The critical design decision: the mirror is <strong>best-effort</strong>, and a failure writing to the legacy database must never roll back the committed write in the new one. The clean way to get both properties is to not call the legacy database from the request path at all — route the mirror through the outbox you’re already writing to:</p><pre>public async Task CreateOrderAsync(<br>    CreateOrderCommand cmd, CancellationToken ct)<br>{<br>    var order = Order.Create(cmd);<br> <br>    await _newDb.Orders.AddAsync(order, ct);<br>    await _outbox.AddEventAsync(new OrderCreated(order), ct);<br>    await _outbox.AddEventAsync(<br>        new LegacyMirrorRequested(order.Id), ct);<br>    await _newDb.SaveChangesAsync(ct); // ← one atomic commit<br> <br>    // No inline call to the legacy DB. A background worker<br>    // consumes LegacyMirrorRequested and does the mirroring.<br>}</pre><p>Both events commit atomically with the order itself, and a background worker picks up LegacyMirrorRequested and calls the outbound ACL. That&#39;s what makes &quot;best-effort&quot; actually true instead of aspirational: the request path never pays legacy-DB latency, retries with backoff are automatic, and a mirror that keeps failing lands in a dead-letter queue you can inspect — not in a warning log you&#39;ll never grep. (The outbox mechanics — idempotent consumers, retries, DLQs — deserve their own post; it&#39;s <a href="https://medium.com/@viniciusrossado/the-outbox-pattern-idempotent-consumers-events-that-never-get-lost-in-net-136d60457042">next in this series.)</a></p><p>Reads can still be served by either system — the legacy app keeps serving clients that haven’t been migrated yet.</p><p>Because you now have two databases that are supposed to agree, you also run a <strong>sync validator job</strong>: a background service that periodically compares both sides and logs discrepancies. It doesn’t fix anything automatically — it just tells you whether you can trust the new system.</p><pre>public class SyncValidatorJob(IServiceScopeFactory scopeFactory, ILogger&lt;SyncValidatorJob&gt; logger)<br>    : BackgroundService<br>{<br>    protected override async Task ExecuteAsync(CancellationToken ct)<br>    {<br>        using var timer = new PeriodicTimer(TimeSpan.FromHours(1));<br>        do<br>        {<br>            try<br>            {<br>                // BackgroundService is a singleton — resolve scoped deps per run<br>                await using var scope = scopeFactory.CreateAsyncScope();<br>                var newDb     = scope.ServiceProvider.GetRequiredService&lt;NewDbContext&gt;();<br>                var legacyDb  = scope.ServiceProvider.GetRequiredService&lt;LegacyDbContext&gt;();<br>                var watermark = scope.ServiceProvider.GetRequiredService&lt;ISyncWatermark&gt;();<br> <br>                var since = await watermark.GetLastCheckedAsync(ct);<br>                var until = DateTimeOffset.UtcNow.AddMinutes(-1); // skip in-flight writes<br> <br>                var newOrders = await newDb.Orders.AsNoTracking()<br>                    .Where(o =&gt; o.UpdatedAt &gt;= since &amp;&amp; o.UpdatedAt &lt; until)<br>                    .ToListAsync(ct);<br> <br>                var ids = newOrders.Select(o =&gt; o.Id.Value).ToList();<br>                var legacyById = await legacyDb.TBL_ORDR.AsNoTracking()<br>                    .Where(l =&gt; ids.Contains(l.ORDR_ID))<br>                    .ToDictionaryAsync(l =&gt; l.ORDR_ID, ct);<br> <br>                foreach (var order in newOrders)<br>                {<br>                    if (!legacyById.TryGetValue(order.Id.Value, out var legacy))<br>                        logger.LogWarning(&quot;Order {OrderId} missing in legacy&quot;, order.Id);<br>                    else if (legacy.TOT_AMT != order.Total.Amount)<br>                        logger.LogWarning(&quot;Order {OrderId} has divergent total&quot;, order.Id);<br>                }<br> <br>                await watermark.SetLastCheckedAsync(until, ct);<br>            }<br>            catch (Exception ex) when (ex is not OperationCanceledException)<br>            {<br>                // one failed run must not stop the host — StopHost is the default since .NET 6<br>                logger.LogError(ex, &quot;Sync validation run failed; retrying next cycle&quot;);<br>            }<br>        } while (await timer.WaitForNextTickAsync(ct));<br>    }<br>}</pre><p>The validator windows on UpdatedAt because full-table scans stop being feasible the moment you have real data — and the one-minute lag on until is there so you don&#39;t false-alarm on writes that are still in flight through the mirror. Tune that lag to your outbox retry profile: a mirror retry that outlives it produces one false &quot;missing&quot; log before the watermark moves on. The persisted watermark means a restart picks up where the last pass left off. (One practical note: Contains over a very large ids list has limits of its own — keep the window small enough that a pass stays in the low thousands of rows.)</p><p>Two classic BackgroundService traps are worth calling out, because both would bite here. A hosted service is a singleton, so you can&#39;t constructor-inject a scoped DbContext — under scope validation the app fails at startup, and without it you silently keep one context (and its ever-growing change tracker) for the process lifetime. Resolve contexts from a per-iteration scope instead. And since .NET 6, an unhandled exception in ExecuteAsync stops the whole host — a &quot;non-critical&quot; validator crashing your service on one transient DB error is not the kind of irony you want in production.</p><p><strong>When do you leave phase 1?</strong> When the validator stops logging discrepancies that matter. Not zero discrepancies — zero discrepancies <em>the business cares about</em>. That, plus green integration tests and a team that’s comfortable with the new data model, is your exit criterion.</p><h3>Phase 2 — The new system is the source of truth</h3><p>Flip the flag to new-source-of-truth and the dual write disappears: writes go 100% to the new system. But the legacy database usually still has consumers — reports, batch jobs, that one integration nobody admits owning. So instead of mirroring on every write, a <strong>sync job</strong> polls for changed records and pushes them to the legacy side through the same outbound ACL.</p><pre>public class LegacySyncJob(IServiceScopeFactory scopeFactory, ILegacyOutboundAcl acl,<br>    ILogger&lt;LegacySyncJob&gt; logger) : BackgroundService<br>{<br>    protected override async Task ExecuteAsync(CancellationToken ct)<br>    {<br>        using var timer = new PeriodicTimer(TimeSpan.FromSeconds(30));<br>        while (await timer.WaitForNextTickAsync(ct))<br>        {<br>            try<br>            {<br>                await using var scope = scopeFactory.CreateAsyncScope();<br>                var db = scope.ServiceProvider.GetRequiredService&lt;NewDbContext&gt;();<br> <br>                var unsynced = await db.Orders<br>                    .Where(o =&gt; o.LastSyncedAt &lt; o.UpdatedAt)<br>                    .OrderBy(o =&gt; o.UpdatedAt) // deterministic batch — EF warns on Take without OrderBy<br>                    .Take(100)<br>                    .ToListAsync(ct);<br> <br>                foreach (var order in unsynced)<br>                {<br>                    await acl.MirrorAsync(order, ct); // must be idempotent — a batch may be retried<br>                    order.LastSyncedAt = DateTimeOffset.UtcNow;<br>                }<br> <br>                await db.SaveChangesAsync(ct);<br>            }<br>            catch (Exception ex) when (ex is not OperationCanceledException)<br>            {<br>                logger.LogWarning(ex, &quot;Legacy sync pass failed; retrying next tick&quot;);<br>            }<br>        }<br>    }<br>}</pre><p>Two things change conceptually here:</p><ul><li>The <strong>validator is removed</strong> — comparing two databases makes no sense when one of them is deliberately eventual.</li><li>The legacy database now runs <strong>seconds to tens of seconds behind</strong>. That’s deliberate eventual consistency. If a legacy consumer can’t tolerate the lag, either shorten the polling interval or migrate that consumer <em>before</em> leaving phase 1.</li></ul><h3>Phase 3 — Legacy off</h3><p>The final flag value, legacy-off, is mostly a deletion exercise: the legacy database is shut down and archived, the sync job and outbound ACL are deleted, and the proxy routes 100% of traffic to the new system.</p><p>One component may survive: the <strong>inbound ACL</strong>. If external clients still send requests in the legacy format, the inbound ACL keeps translating their ugly payloads into your clean domain — no legacy system required.</p><p>The scary question is: <em>how do you know nobody is still using the legacy system?</em> Don’t guess — measure. Put an unsampled signal on the legacy endpoints: a plain request counter (OpenTelemetry metrics) or access logs, backed by tracing at 100% sampling on those routes — with default head sampling, zero exported spans doesn’t prove zero traffic. If the count stays at zero for N days, where N is longer than your longest business cycle (think quarterly batch jobs), you have strong evidence there are no consumers left. Complement that with the Sunset (RFC 8594) and Deprecation (RFC 9745) headers to warn stragglers ahead of time, and turn the legacy off per tenant with feature flags rather than all at once.</p><h3>Routing traffic: YARP as the front door</h3><p>Everything above assumes something sits in front of both systems deciding where each request goes. In .NET, YARP (Yet Another Reverse Proxy) does this from configuration — and if you back it with something like Azure App Configuration, you can change routing without a redeploy.</p><pre>{<br>  &quot;ReverseProxy&quot;: {<br>    &quot;Routes&quot;: {<br>      &quot;new-payments&quot;:    { &quot;ClusterId&quot;: &quot;new-system&quot;, &quot;Match&quot;: { &quot;Path&quot;: &quot;/api/payments/{**catch-all}&quot; } },<br>      &quot;new-orders&quot;:      { &quot;ClusterId&quot;: &quot;new-system&quot;, &quot;Match&quot;: { &quot;Path&quot;: &quot;/api/orders/{**catch-all}&quot; } },<br>      &quot;legacy-fallback&quot;: { &quot;ClusterId&quot;: &quot;legacy&quot;,     &quot;Match&quot;: { &quot;Path&quot;: &quot;/{**catch-all}&quot; } }<br>    },<br>    &quot;Clusters&quot;: {<br>      &quot;new-system&quot;: { &quot;Destinations&quot;: { &quot;d1&quot;: { &quot;Address&quot;: &quot;https://new-api/&quot; } } },<br>      &quot;legacy&quot;:     { &quot;Destinations&quot;: { &quot;d1&quot;: { &quot;Address&quot;: &quot;https://legacy-api/&quot; } } }<br>    }<br>  }<br>}</pre><p>The routing pattern matters as much as the proxy. Four strategies, each with a trade-off:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ia2D0Lj1gDQJ1X2xUNN7sw.png" /><figcaption>The four routing strategies: pick by rollout granularity vs. operational complexity.</figcaption></figure><ul><li><strong>By route</strong> (/api/payments/* → new): migrate feature by feature. Simple — until a feature depends on data the legacy still owns.</li><li><strong>By feature flag</strong> (header set via middleware): gradual rollout without redeploys, at the cost of a flag lookup per request.</li><li><strong>By user hash</strong> (SHA256(userId) % 100 &lt; threshold): canary by user, deterministic, so each user consistently sees the same system. <a href="https://medium.com/@viniciusrossado/feature-flags-with-deterministic-hashing-canary-rollouts-by-user-in-net-44d18b8094dc">The next post in this series</a> takes this one apart in detail.</li><li><strong>By tenant</strong>: the B2B SaaS favorite — total isolation per customer, but you live with two systems for longer.</li></ul><h3>Takeaway</h3><p>The Strangler Fig pattern isn’t clever architecture — it’s risk management expressed as architecture. One flag, three phases, and at every point in the migration you can answer the question “what happens if this goes wrong?” with “we route back and try again tomorrow.”</p><p>If you’re staring at a legacy system right now, don’t start by designing the new system. Start by putting a proxy in front of the old one. That single, boring step is what makes every other step possible.</p><h3>The Legacy Modernization in .NET series</h3><p>This article is one brick in a series on modernizing legacy systems in .NET — 🟩 bricks are laid, ⬜ bricks are coming:</p><ul><li>🟩 <strong>Killing a Legacy System Without a Big Bang: The Strangler Fig Pattern — you are here</strong></li><li>🟩 <a href="https://medium.com/@viniciusrossado/the-anti-corruption-layer-protecting-your-new-domain-model-from-the-legacy-system-9f72c5423dea">The Anti-Corruption Layer</a></li><li>🟩 <a href="https://medium.com/@viniciusrossado/feature-flags-with-deterministic-hashing-canary-rollouts-by-user-in-net-44d18b8094dc">Feature Flags with Deterministic Hashing</a></li><li>🟩 <a href="https://medium.com/@viniciusrossado/the-outbox-pattern-idempotent-consumers-events-that-never-get-lost-in-net-136d60457042">The Outbox Pattern + Idempotent Consumers</a></li><li>⬜ The Saga Pattern (coming soon)</li><li>⬜ Resilience: Retry, Jitter, Circuit Breaker (coming soon)</li><li>⬜ Change Data Capture with Debezium (coming soon)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eeef47e21814" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>